Spring MVC的RequestContextHolder使用误区

转载自:http://www.cnblogs.com/softidea/p/6125087.html

在spring mvc中,为了随时都能取到当前请求的request对象,可以通过RequestContextHolder的静态方法getRequestAttributes()获取Request相关的变量,如request, response等。

为了更加方便地在项目中获取request、response对象,我写了个工具类RequestHolder.java

public class RequestHolder {
    public static HttpServletRequest getRequest(){
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return req;
    }

    public static HttpServletResponse getResponse(){
        HttpServletResponse resp = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();
        return resp;
    }
}


在大部分的情况下,它都能很好地工作。但是,当请求为multipart类型的请求的时候,如文件上传,form表单的enctype类型为"multipart/form-data",这种情况下,RequestHolder.getRequest().getParameter()是得不到参数值的!!因为通过RequestHolder.getRequest()获取到的request对象是org.apache.catalina.connector.RequestFacade的实例。

public class RequestFacade implements HttpServletRequest 

DisptcherServlet会当前请求是否为multipart类型,如果是的话,将request对象转为MultipartHttpServletRequet,具体的见源码

    protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpServletRequest processedRequest = request;
        ......
                processedRequest = checkMultipart(request);
                multipartRequestParsed = processedRequest != request;
        ......
                // Actually invoke the handler.
                mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
        ......
    }

    protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
        if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
            if (request instanceof MultipartHttpServletRequest) {
                logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " +
                        "this typically results from an additional MultipartFilter in web.xml");
            }
            else {
                return this.multipartResolver.resolveMultipart(request);
            }
        }
        // If not returned before: return original request.
        return request;
    }


 

解决办法: 

直接将HttpServletRequest作为Spring MVC的Controller的方法入参,如下

	@RequestMapping(value="say3",method=RequestMethod.GET)
	public ModelAndView say2(HttpServletRequest request){
		//其中第一个参数为View Name,第二个参数为要传递的数据的key,第三个参数为数据对象。在这里要注意的是:数据是默认被存放在request中的
		return new ModelAndView("say", "msg", request.getParameter("msg"));
	}


 


 

你可能感兴趣的:(Spring,MVC,Spring,Spring,Framwork,SSH)