zoukankan      html  css  js  c++  java
  • 通过spring,在项目的任意位置获取当前Request

    需要引入:

    import javax.servlet.http.HttpServletRequest;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;

    使用方法:

    public static HttpServletRequest getRequest(){
        ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =  ra.getRequest();
        return request;
    }

    如果对安全有特别要求,做如下改进:

    /**
         * 
         * @Title: getCurrentRequest
         * @author:liuyx 
         * @date:2016年1月13日下午6:14:43
         * @Description: 获取当前request
         * @return
         * @throws IllegalStateException 当前线程不是web请求抛出此异常.
         */
        public static HttpServletRequest getCurrentRequest() throws IllegalStateException {
            ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attrs == null) {
                throw new IllegalStateException("当前线程中不存在 Request 上下文");
            }
            return attrs.getRequest();
        }
  • 相关阅读:
    CentOS 6.5 伪分布式 安装 hadoop 2.6.0
    单例模式的思想简介
    最有二叉树 哈夫曼树
    二叉树2
    二叉树1
    栈与队列
    线性表
    字符串模式匹配KMP算法
    数据结构(四) 查找 排序
    数据结构(三) 图
  • 原文地址:https://www.cnblogs.com/flying607/p/5128088.html
Copyright © 2011-2022 走看看