在典型的Spring MVC应用程序中, @Controller
类负责使用数据准备模型映射并选择要呈现的视图。 该model map
允许视图技术的完整抽象,对于Thymeleaf而言,它被转换为Thymeleaf VariablesMap
对象,该对象使所有定义的变量可用于模板中执行的表达式。
弹簧模型属性
Spring MVC调用在执行视图model attributes
期间可以访问的数据。 Thymeleaf语言中的等效术语是context variables
。 在Spring MVC中,有几种将模型属性添加到视图的方法。 以下是一些常见情况:通过其addAttribute方法向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;}
通过带有@ModelAttribute注释的方法公开公共属性:
@ModelAttribute("messages")
public List<Message> messages() {return messageRepository.findAll();}
您可能已经注意到,在上述所有情况下,`messages`属性都已添加到模型中,并且在Thymeleaf视图中可用。
在Thymeleaf中,可以使用以下语法访问这些模型属性:`$ {attributeName}`,它是Spring EL表达式。
您可以使用Thymeleaf在视图中访问模型属性,如下所示:
<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>
请求参数
在Thymeleaf视图中可以轻松访问请求参数。 请求参数从客户端传递到服务器,例如:
https://example.com/query?q=Thymeleaf+Is+Great!
假设我们有一个@Controller,它发送带有请求参数的重定向:
@Controllerpublic class SomeController {@RequestMapping("/")public String redirect() {return "redirect:/query?q=Thymeleaf Is Great!";}}
为了访问q参数,您可以使用param。前缀:
<p th:text="${param.q[0]}" th:unless="${param.q == null}">Test</p>
在上面的示例中需要注意两点:
- $ {param.q!= null}`检查是否设置了参数`q`
- 参数始终是字符串数组,因为它们可以是多值的(例如`https://example.com/query?q=Thymeleaf%20Is%20Great!&q=Really%3F)
访问请求参数的另一种方法是使用特殊对象#httpServletRequest,它使您可以直接访问javax.servlet.http.HttpServletRequest对象:
<p th:text="${#httpServletRequest.getParameter('q')}" th:unless="${#httpServletRequest.getParameter('q') == null}">Test</p>
会话属性
在下面的示例中,我们将`mySessionAttribute`添加到会话中:
@RequestMapping({"/"})
String index(HttpSession session) {session.setAttribute("mySessionAttribute", "someValue");return "index";}
与请求参数类似,可以使用`session.`前缀访问会话属性:
<div th:text="${session.mySessionAttribute}">[...]</div>
或者通过使用#httpSession,可以直接访问javax.servlet.http.HttpSession对象。
ServletContext属性,Spring Bean
在丹尼尔·费尔南德斯( DanielFernández )的大力帮助下,我为thymeleaf.org写的这篇文章的完整版本可以在这里找到: http : //www.thymeleaf.org/springmvcaccessdata.html
翻译自: https://www.javacodegeeks.com/2014/05/spring-mvc-and-thymeleaf-how-to-acess-data-from-templates.html