Content Table

SpringMVC 获取 Request 和 Response

SpringMVC 中在任意地方取得 HttpServletRequestHttpServletResponse

  1. 在 web.xml 中注册 RequestContextListener (SpringMVC 4 不需要这一步)

    1
    2
    3
    4
    5
    <listener>  
    <listener-class>
    org.springframework.web.context.request.RequestContextListener
    </listener-class>
    </listener>
  2. 获取 HttpServletRequestHttpServletResponse

    1
    2
    3
    4
    5
    6
    public static String testRequestAndResponse() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

    return request.getParameter("name");
    }