美文网首页
SpringMVC优雅的获取HttpSevletRequest及

SpringMVC优雅的获取HttpSevletRequest及

作者: wingedsnake | 来源:发表于2019-01-08 13:42 被阅读0次

    通常情况下,SpringMVC可以通过入参的方式绑定HttpServletRequestHttpServletReponse(SpringMVC在调用处理器时会自动创建对应的HttpServletRequestHttpServletReponse对象并传入适配的控制器方法中),例如:

    @Controller
    //通过参数,传入HttpServletRequest对象和HttpServletResponse对象
    public Object rest(HttpServletRequest request,HttpServletResponse reponse){      
      Map<String,Object> map = new HashMap<>();
      System.err.println(request);
      map.put("k1","v1");
      map.put("k2","v2");
      return map;
     }
    

    然而如果每个控制器方法都需要HttpServletRequestHttpServletReponse对象的话,相对的还是比较繁琐冗余的。此时就可以使用更优雅的方式来获取HttpServletRequestHttpServletReponse两个对象。
    使用的代码如下

    //获取response对象
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    //获取request对象
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    

    为了方便调用,可以创建一个BaseController类并实现相应获取requestresponse对象的方法,让该类作为所有控制器类的父类后就可以直接使用实现的对应方法来获取requestresponse对象了,代码如下

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    public class BaseController {
    
        /**
         * 获取request对象
         */
        public HttpServletRequest getRequest() {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }
        
        /**
         * 获取Response对象
         */
        public HttpServletResponse getResponse() {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        }
        
        /**
         * 获取Session对象
         */
        public HttpSession getSession() {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:SpringMVC优雅的获取HttpSevletRequest及

          本文链接:https://www.haomeiwen.com/subject/qbvvrqtx.html