Thymeleaf中去的作用域中数据的方法和jsp相似,熟悉jsp的开发者很容易学会
先看一个demo,Model,request,session,ServletContext中的数据
public String One(Model model, HttpServletRequest request, HttpSession session){
Person p1=queryPerson.query(1001);
model.addAttribute("Tom",p1);
model.addAttribute("req","hello");
request.setAttribute("req","Hello");
session.setAttribute("ses","Http!");
request.getServletContext().setAttribute("app","App");
return "Tom";
}
model中的数据实际上就是request中的数据,以下写法都可以拿到数据
<h1 th:utext="${Tom.gender}">Hello</h1>
<h1 th:utext="${req}">Hello</h1>
<h1 th:utext="${#request.getAttribute('req')}"></h1>
<h1 th:utext="${#httpServletRequest.getAttribute('req')}"></h1>
<!--无法得到<h1 th:utext="${session.getAttribute('ses')}"></h1>-->
<h1 th:utext="${session.ses}"></h1>
<h1 th:text="${#request.getSession().getAttribute('ses')}"></h1>
<h1 th:text="${#session.getAttribute('ses')}"></h1>
<h1 th:text="${#httpSession.getAttribute('ses')}"></h1>
<h1 th:utext="${#request.getServletContext().getAttribute('app')}"></h1>
<h1 th:utext="${#servletContext.getAttribute('app')}"></h1>
基本可以看出写法很多,不唯一,有任意的写法都可以
httpServletRequest
<h1 th:utext="${#httpServletRequest.getAttribute('req')}"></h1>
httpSession
<h1 th:text="${#httpSession.getAttribute('ses')}"></h1>
servletContext
<h1 th:utext="${#servletContext.getAttribute('app')}"></h1>
来源:https://blog.csdn.net/weixin_43688691/article/details/99069150