通常情况下,SpringMVC可以通过入参的方式绑定HttpServletRequest
和HttpServletReponse
(SpringMVC在调用处理器时会自动创建对应的HttpServletRequest
和HttpServletReponse
对象并传入适配的控制器方法中),例如:
@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;
}
然而如果每个控制器方法都需要HttpServletRequest
和HttpServletReponse
对象的话,相对的还是比较繁琐冗余的。此时就可以使用更优雅的方式来获取HttpServletRequest
和HttpServletReponse
两个对象。
使用的代码如下
//获取response对象
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//获取request对象
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
为了方便调用,可以创建一个BaseController
类并实现相应获取request
和response
对象的方法,让该类作为所有控制器类的父类后就可以直接使用实现的对应方法来获取request
和response
对象了,代码如下
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();
}
}
网友评论