在典型的Spring MVC应用中,@Controller修饰的类负责model map中数据的准备和指定跳转到的view。在Thymeleaf中,上述这些内容被转化为Thymeleaf的上下文对象,使得所有在上下文中定义的变量,在templates模板表达式中可用。
1.Spring模型属性(Spring model attributes)
添加属性到Model
@RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("messages", messageRepository.findAll());
return "message/list";
}
返回ModelAndView
@RequestMapping(value = "message", method = RequestMethod.GET)
public ModelAndView messages() {
ModelAndView mav = new ModelAndView("message/list");
mav.addObject("messages", messageRepository.findAll());
return mav;
}
在使用了Thymeleaf的view中,就可以获取到model中的值,进行相关操作了
<tr th:each="message : ${messages}">
<td th:text="${message.id}">1</td>
<td><a href="#" th:text="${message.title}">Title ...</a></td>
<td th:text="${message.text}">Text ...</td>
</tr>
2.请求参数(Request parameters)
假设在@Controller所修饰的类中,发送一个重定向请求,该请求带有参数
@Controller
public class SomeController {
@RequestMapping("/")
public String redirect() {
return "redirect:/query?q=Thymeleaf+Is+Great!";
}
}
为了接收这个参数,可以使用param.作为前缀
<p th:text="${param.q}">Test</p>
如果参数被赋值为数组或集合,则使用${param.q}获得的是序列化后的数组或集合
<p th:text="${param.q[0] + ' ' + param.q[1]}" th:unless="${param.q == null}">Test</p>
另一种获取请求参数的方式是通过#request,它相当于直接接入的是javax.servlet.http.HttpServletRequest
<p th:text="${#request.getParameter('q')}" th:unless="${#request.getParameter('q') == null}">Test</p>
3.会话属性(Session attributes)
如下,向session中添加属性
@RequestMapping({"/"})
String index(HttpSession session) {
session.setAttribute("mySessionAttribute", "someValue");
return "index";
}
在页面中session会话中属性的获取,可以通过添加session.作为前缀
<p th:text="${session.mySessionAttribute}" th:unless="${session == null}">[...]</p>
另一种获取会话中参数的方式是通过#session,相当于直接接入javax.servlet.http.HttpSession
${#session.getAttribute('mySessionAttribute')}
4.Servlet上下文属性(ServletContext attributes)
servlet上下文属性在requst、session中是共享的,如果在使用了Thymeleaf的页面中需要使用servlet上下文属性时,需要使用#servletContext.作为前缀
<table>
<tr>
<td>My context attribute</td>
<!-- Retrieves the ServletContext attribute 'myContextAttribute' -->
<td th:text="${#servletContext.getAttribute('myContextAttribute')}">42</td>
</tr>
<tr th:each="attr : ${#servletContext.getAttributeNames()}">
<td th:text="${attr}">javax.servlet.context.tempdir</td>
<td th:text="${#servletContext.getAttribute(attr)}">/tmp</td>
</tr>
</table>
5.Spring实体对象(Spring beans)
Thymeleaf允许接入注册在Spring应用上下文中的beans(Spring Application Context),使用@beanName
<div th:text="${@urlService.getApplicationUrl()}">...</div>
@urlService注册的spring bean 如下
@Configuration
public class MyConfiguration {
@Bean(name = "urlService")
public UrlService urlService() {
return () -> "domain.com/myapp";
}
}
public interface UrlService {
String getApplicationUrl();
}
参考链接:https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html