javascript
Spring MVC和Thymeleaf:如何从模板访问数据
在典型的Spring MVC應用程序中, @Controller類負責使用數(shù)據(jù)準備模型映射并選擇要呈現(xiàn)的視圖。 該model map允許視圖技術的完整抽象,對于Thymeleaf而言,它被轉換為Thymeleaf VariablesMap對象,該對象使所有定義的變量可用于模板中執(zhí)行的表達式。
彈簧模型屬性
Spring MVC調用在執(zhí)行視圖model attributes期間可以訪問的數(shù)據(jù)。 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();}您可能已經(jīng)注意到,在上述所有情況下,`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>請求參數(shù)
在Thymeleaf視圖中可以輕松訪問請求參數(shù)。 請求參數(shù)從客戶端傳遞到服務器,例如:
https://example.com/query?q=Thymeleaf+Is+Great!假設我們有一個@Controller,它發(fā)送帶有請求參數(shù)的重定向:
@Controllerpublic class SomeController {@RequestMapping("/")public String redirect() {return "redirect:/query?q=Thymeleaf Is Great!";}}為了訪問q參數(shù),您可以使用param。前綴:
<p th:text="${param.q[0]}" th:unless="${param.q == null}">Test</p>在上面的示例中需要注意兩點:
- $ {param.q!= null}`檢查是否設置了參數(shù)`q`
- 參數(shù)始終是字符串數(shù)組,因為它們可以是多值的(例如`https://example.com/query?q=Thymeleaf%20Is%20Great!&q=Really%3F)
訪問請求參數(shù)的另一種方法是使用特殊對象#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";}與請求參數(shù)類似,可以使用`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
總結
以上是生活随笔為你收集整理的Spring MVC和Thymeleaf:如何从模板访问数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用手机怎么裁剪图片电脑如何剪切图片
- 下一篇: Apache CXF 3.0:CDI 1