SpringMVC优雅的获取HttpSevletRequest及HttpServletResponse简录

https://cloud.tencent.com/developer/article/1403947

通常情况下,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();
}

}

posted @ 2019-11-21 16:24  cuiqq  阅读(606)  评论(0编辑  收藏  举报