赞
踩
request与response是Tomcat服务器在收到客户端请求后自己生成的,无需我们自己创建,但是在使用的时候可以有以下三种方式去获取
方法上直接使用,通过DispatcherServlet将参数传到MethodHandler直接使用
@RequestMapping(path = {"/test10"}, method = RequestMethod.POST)
@ResponseBody
public BaseRes test10(HttpServletRequest request, HttpServletResponse response) {
final HttpSession session = request.getSession();//创建session,如果没有则创建
session.setAttribute("name","lisi");
session.setAttribute("passwrod","123456");
session.setAttribute();
final Cookie cookie = new Cookie("name","wangwu");
response.addCookie(cookie);//向浏览器返回cookie
logger.info("session信息:{},sessionID:{}",session.getAttributeNames(),session.getId());
final BaseRes success = BaseRes.success();
success.setData(session.getAttributeNames());
return success;
}
RequestContextHolder,持有上下文的Request容器。可以用来获取当前请求信息以及响应信息,都是保存在ThreadLocal中,与线程绑定。
@RequestMapping(path = {"/test13"}, method = RequestMethod.POST) @ResponseBody public BaseRes test13() { HttpServletRequest requests = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); HttpServletResponse responses = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); final Cookie[] cookies = requests.getCookies(); String value= "default"; for (Cookie cookie:cookies){ if (cookie.getName().equals("name")){ value=cookie.getValue(); } } final Cookie cookie = new Cookie("name","xxxxxx"); responses.addCookie(cookie);//向浏览器返回cookie final BaseRes success = BaseRes.success(); success.setData(value); return success; }
底层使用的RequestContextHolder,它在请求进来的时候进行注入,
参考:探讨 SpringMVC 能否注入 Request 和 Response
@Autowired private HttpServletRequest request; @Autowired private HttpServletResponse response; @RequestMapping(path = {"/test12"}, method = RequestMethod.POST) @ResponseBody public BaseRes test12() { final Cookie[] cookies = request.getCookies(); String value= "default"; for (Cookie cookie:cookies){ if (cookie.getName().equals("name")){ value=cookie.getValue(); } } final Cookie cookie = new Cookie("name","dddd"); this.response.addCookie(cookie);//向浏览器返回cookie final BaseRes success = BaseRes.success(); success.setData(value); return success; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。