目录
RequestContextHolder 获取 ServletRequest 和 ServletResponse
RequestContextHolder 获取 ServletRequest 和 ServletResponse
1、SpringMVC 的控制层中通常有如下方式获取用户请求的参数:
@RestController
public class UserController {
/**
* 传统方式
* http://localhost:8080/user/clearCache1?tenant_id=440000&token=9e3bc1ba-f7cd-4754-971d-0217841e62b8
* @param request
* @return
*/
@GetMapping("user/clearCache1")
@SuppressWarnings("all")
public String clearCache1(HttpServletRequest request) {
String tenant_id = request.getParameter("tenant_id");//参数不存在时,返回 null
String token = request.getParameter("token");
String result = "tenant_id=" + tenant_id + ",token=" + token;
return result;
}
/**
* 推荐方式
* http://localhost:8080/user/clearCache2?tenant_id=430000&token=5a9da3b3-30a5-4737-8b58-13dbed3a9a57
* @param tenant_id
* @param token
* @return
*/
@GetMapping("user/clearCache2")
public String clearCache2(Long tenant_id, String token) {
String result = "tenant_id=" + tenant_id + ",token=" + token;
return result;
}
/**
* 在控制层以外的地方,在不接收任何参数的情况下获取 HttpServletRequest、HttpServletResponse 的特殊方式
* http://localhost:8080/user/clearCache3?tenant_id=450000&token=2f2ef709-cb50-4b43-acde-07fc1cc8f4bd
* @return
*/
@GetMapping("user/clearCache3")
@SuppressWarnings("all")
public String clearCache3() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = servletRequestAttributes.getRequest();
HttpServletResponse response = servletRequestAttributes.getResponse();
String sessionId = servletRequestAttributes.getSessionId();
System.out.println("】】request=" + request);
System.out.println("】】session=" + request.getSession() + ", id=" + request.getSession().getId());
System.out.println("】】response=" + response);
System.out.println("】】sessionId=" + sessionId);
System.out.println("】】realPath=" + request.getServletContext().getRealPath("/"));
String tenant_id = request.getParameter("tenant_id");
String token = request.getParameter("token");
String result = "tenant_id=" + tenant_id + ",token=" + token;
return result;
}
}
src/main/java/com/wmx/controller/UserController.java · 汪少棠/jpaTransactional - Gitee.com
2、这里重点介绍一下 org.springframework.web.context.request.RequestContextHolder 类 - 请求上下文支持,它在 spring-web-x.x.x.RELEASE.jar 包中。
3、RequestContextHolder 的源码中使用 ThreadLocal 维护了一个如下的静态成员变量:
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal<>("Request attributes");
提供了如下两个静态方法来获取 org.springframework.web.context.request.RequestAttributes 接口:
static RequestAttributes currentRequestAttributes() satic RequestAttributes getRequestAttributes() |
4、RequestAttributes 接口有好几个实现类,其中常用的有 org.springframework.web.context.request.ServletRequestAttributes。它提供了获取如下对象的方法:
javax.servlet.http.HttpServletRequest javax.servlet.http.HttpServletResponse |
5、SpringMVC 利用线程局部变量 ThreadLocal,每次在处理请求前,将请求的 request 和 response 放到 RequestContextHolder 的 ThreadLocal 对象内,后续处理请求时,可以再通过 RequestContextHolder 类获取。
(本文演示环境为:Java JDK 1.8 + Spring Boot 2.0.3(spring-boot-starter-web、内置的 Tomcat ))
Spring MVC 数据响应 ModelAndView
1、浏览器请求后台控制器层,业务完成后,再向前端返回数据,如果是前后端分离的项目,则后台接口都是清一色的 @ResponseBody 直接返回数据。
2、而如果是使用模板引擎的方式,如 JSP、Thymeleaf、Freemark 等等,此时后台返回时既需要设置数据,还需要跳转的视图。
/**
* Spring Boot 集成 Thymeleaf 快速入门 & Spring MVC 数据响应
*
* @author wangMaoXiong
* @version 1.0
* @date 2022/4/9 8:33
*/
@Controller
public class ThymeleafController {
/**
* http://localhost:8080/thymeleaf/home
* 1、org.springframework.ui.Model 是专门用于封装返回的数据的,可以直接 new,也可以直接放在参数中自动注入
*
* @param responseMap
* @return
*/
@RequestMapping("thymeleaf/home")
public String goHome(Map<String, Object> responseMap, Model model) {
// 向页面返回数据方式1:默认 responseMap 的内容会放到请求域中,调整后的新页面上可以直接使用 Thymeleaf 表达式取值
responseMap.put("name", "张三");
responseMap.put("age", 35);
// 向页面返回数据方式2:使用 org.springframework.ui.Model 向页面返回数据
model.addAttribute("code", 200);
model.addAttribute("msg", "管理员向你表示祝贺!");
// 全部基于 Spring Boot 给 Thymeleaf 的默认配置
// 自动跳转到默认的 classpath:/templates/home.html 页面
return "home";
}
/**
* http://localhost:8080/modelAndView/v1/toHome
* 1、org.springframework.web.servlet.ModelAndView:Web MVC 框架中模型和视图的持有者,以便控制器可以在一个返回值中同时返回模型和视图
* * Model :模型,用于封装返回的数据
* * View :视图,用于展示数据的视图(如 html)
*
* @return
*/
@GetMapping("modelAndView/v1/toHome")
public ModelAndView toHome() {
Map<String, Object> responseMap = new HashMap<>(8);
responseMap.put("name", "李四");
responseMap.put("age", 33);
responseMap.put("code", "1000");
responseMap.put("msg", "登陆成功。");
// ModelAndView(String viewName, @Nullable Map<String, ?> model)
ModelAndView modelAndView = new ModelAndView("home", responseMap);
return modelAndView;
}
/**
* http://localhost:8080/modelAndView/v2/toHome
*
* @param modelAndView :可以在方法里面直接 new modelAndView(),也可以放在参数中自动注入
* @return
*/
@GetMapping("modelAndView/v2/toHome")
public ModelAndView toHome(ModelAndView modelAndView) {
Map<String, Object> responseMap = new HashMap<>(8);
responseMap.put("name", "王五");
responseMap.put("age", 34);
responseMap.put("code", "1001");
responseMap.put("msg", "登陆成功。");
// 设置此ModelAndView的视图名称
modelAndView.setViewName("home");
// 将提供的映射中包含的所有属性添加到模型中
modelAndView.addAllObjects(responseMap);
return modelAndView;
}
/**
* http://localhost:8080/request/home
* 最原始的 HttpServletRequest 方式像页面返回数据
*
* @param request
* @return
*/
@RequestMapping("request/home")
public String goHome(HttpServletRequest request) {
request.setAttribute("name", "张三哥");
request.setAttribute("age", 45);
request.setAttribute("code", 2000);
request.setAttribute("msg", "管理员向你表示祝贺.");
// 全部基于 Spring Boot 给 Thymeleaf 的默认配置
// 自动跳转到默认的 classpath:/templates/home.html 页面
return "home";
}
/**
* http://localhost:8080/response/body
* 1、前后台分离的项目,不再需要后台进行页面跳转,后台只需要专注数据处理即可,直接将数据返回给前端
*
* @return
*/
@GetMapping("response/body")
@ResponseBody
public Map<String, Object> body() {
Map<String, Object> responseMap = new HashMap<>(8);
responseMap.put("name", "王老五");
responseMap.put("age", 37);
responseMap.put("code", "1001");
responseMap.put("msg", "登陆成功。");
return responseMap;
}
/**
* http://localhost:8080/print/writer
* 通过输出流的方式返回数据,此时同样不需要在指定跳转视图,通常用于文件下载,验证码图片输出等等
*
* @param response
* @throws IOException
*/
@GetMapping("print/writer")
public void body(HttpServletResponse response) throws IOException {
// 指示服务器响应数据的类型以及编码,告诉浏览器以此种编码进行解码,下面两种方式结果一致
response.setHeader("Content-Type", "text/html;charset=utf-8");
// response.setContentType("text/html;charset=utf-8");
Map<String, Object> responseMap = new HashMap<>(8);
responseMap.put("name", "王老吉");
responseMap.put("age", 39);
responseMap.put("code", "1001");
responseMap.put("msg", "登陆成功");
// response 获取的流浏览器端的编码
PrintWriter printWriter = response.getWriter();
printWriter.print(responseMap.toString());
printWriter.flush();
printWriter.close();
}
/**
* http://localhost:8080/print/outputStream
* 通过输出流的方式返回数据,此时同样不需要在指定跳转视图,通常用于文件下载,验证码图片输出等等
*
* @param response
* @throws IOException
*/
@GetMapping("print/outputStream")
public void outputStream(HttpServletResponse response) throws IOException {
// 指示服务器响应数据的类型以及编码,告诉浏览器以此种编码进行解码,下面两种方式效果一致
// response.setHeader("Content-Type", "text/html;charset=utf-8");
response.setContentType("text/html;charset=utf-8");
Map<String, Object> responseMap = new HashMap<>(8);
responseMap.put("name", "王老吉");
responseMap.put("age", 40);
responseMap.put("code", "1001");
responseMap.put("msg", "登陆成功");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(responseMap.toString().getBytes());
outputStream.flush();
outputStream.close();
}
src/main/java/com/wmx/controller/ThymeleafController.java · 汪少棠/jpaTransactional - Gitee.com
src/main/resources/templates/home.html · 汪少棠/jpaTransactional - Gitee.com