In a typical Spring MVC application, @Controller
classes are responsible for preparing a model map with data and selecting a view to be rendered. This model map allows for the complete abstraction of the view technology and, in the case of Thymeleaf, it is transformed into a VariablesMap
object (part of the Thymeleaf template execution context) that makes all the defined variables available to expressions executed in templates.
Spring model attributes
Spring MVC calls the pieces of data that can be accessed during the execution of views model attributes. The equivalent term in Thymeleaf language is context variables.
There are several ways of adding model attributes to a view in Spring MVC. Below you will find some common cases:
Add attribute to Model
via its addAttribute
method:
@RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("messages", messageRepository.findAll());
return "message/list";
}
Return ModelAndView
with model attributes included:
@RequestMapping(value = "message", method = RequestMethod.GET)
public ModelAndView messages() {
ModelAndView mav = new ModelAndView("message/list");
mav.addObject("messages", messageRepository.findAll());
return mav;
}
Expose common attributes via methods annotated with @ModelAttribute
:
@ModelAttribute("messages")
public List<Message> messages() {
return messageRepository.findAll();
}
As you may have noticed, in all the above cases the messages
attribute is added to the model and it will be available in Thymeleaf views.
In Thymeleaf, these model attributes (or context variables in Thymeleaf jargon) can be accessed with the following syntax: ${attributeName}
, whereattributeName
in our case is messages
. This is a Spring EL expression. In short, Spring EL (Spring Expression Language) is a language that supports querying and manipulating an object graph at runtime.
You can access model attributes in views with Thymeleaf as follows:
<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>
Request parameters
Request parameters can be easily accessed in Thymeleaf views. Request parameters are passed from the client to server like:
https://example.com/query?q=Thymeleaf+Is+Great!
Let’s assume we have a @Controller
that sends a redirect with a request parameter:
@Controller
public class SomeController {
@RequestMapping("/")
public String redirect() {
return "redirect:/query?q=Thymeleaf Is Great!";
}
}
In order to access the q
parameter you can use the param.
prefix:
<p th:text="${param.q[0]}" th:unless="${param.q == null}">Test</p>
Two things are important to notice in the above example:
-
${param.q != null}
checks if the parameterq
is set - Parameters are always string arrays, as they can be multivalued (e.g.
https://example.com/query?q=Thymeleaf%20Is%20Great!&q=Really%3F
).
Another way to access request parameters is by using the special object #httpServletRequest
that gives you direct access to thejavax.servlet.http.HttpServletRequest
object:
<p th:text="${#httpServletRequest.getParameter('q')}" th:unless="${#httpServletRequest.getParameter('q') == null}">Test</p>
Session attributes
In the below example we add mySessionAttribute
to session:
@RequestMapping({"/"})
String index(HttpSession session) {
session.setAttribute("mySessionAttribute", "someValue");
return "index";
}
Similarly to the request parameters, session attributes can be access by using the session.
prefix:
<div th:text="${session.mySessionAttribute}">[...]</div>
Or by using #httpSession
, that gives you direct access to the javax.servlet.http.HttpSession
object.
ServletContext attributes
The ServletContext attributes are shared between requests and sessions. In order to access ServletContext attributes in Thymeleaf you can use theapplication.
prefix:
<table>
<tr>
<td>My context attribute</td>
<!-- Retrieves the ServletContext attribute 'myContextAttribute' -->
<td th:text="${application.myContextAttribute}">42</td>
</tr>
<tr>
<td>Number of attributes</td>
<!-- Returns the number of attributes -->
<td th:text="${application.size()}">42</td>
</tr>
<tr th:each="attr : ${application.keySet()}">
<td th:text="${attr}">javax.servlet.context.tempdir</td>
<td th:text="${application.get(attr)}">/tmp</td>
</tr>
</table>
Spring beans
Thymeleaf allows accessing beans registered at the Spring Application Context with the @beanName
syntax, for example:
<div th:text="${@urlService.getApplicationUrl()}">...</div>
In the above example, @urlService
refers to a Spring Bean registered at your context, e.g.
@Configuration
public class MyConfiguration {
@Bean(name = "urlService")
public UrlService urlService() {
return new FixedUrlService("somedomain.com/myapp); // some implementation
}
}
public interface UrlService {
String getApplicationUrl();
}
This is fairly easy and useful in some scenarios.
转自:http://www.thymeleaf.org/doc/springmvcaccessdata.html
相关推荐
WxParse-微信小程序富文本解析自定义组件,支持HTML和markdown解析
那些年,与你同分同位次的同学都去了哪里?全国各大学在辽宁2020-2024年各专业最低录取分数及录取位次数据,高考志愿必备参考数据
Chartjs微信小程序改编_Chartjs-wecat-mini-app
网上好不容易找到的,特此分享。
该项目汇集了55个文件,涵盖Java编程语言的源码和小型作品,具体包括15个XML配置文件、13个Java源文件、12个Git忽略文件、6个IML项目文件、5个文档文件、2个Markdown文件、1个文档和1个PNG图像文件。这些文件构成了一个完整的Java开发资源包。
那些年,与你同分同位次的同学都去了哪里?全国各大学在辽宁2020-2024年各专业最低录取分数及录取位次数据,高考志愿必备参考数据
该项目为2022年暑期实习期间由190822班贺忍小组开发的应急互助信息管理系统源码,采用Java作为后端开发语言,并结合Vue、JavaScript、HTML、SVG等前端技术实现。该系统源码包含684个文件,其中Java文件282个,Vue文件101个,SVG文件87个,JavaScript文件84个,XML文件34个,PNG文件26个,JPG文件13个,VM文件13个,SCSS文件9个,BAT文件7个。该系统旨在提供高效、便捷的应急互助信息管理服务。
全国大学生电子设计大赛项目合集全国电赛优秀作品电赛B题风力摆控制系统设计(原理图+源代码+设计报告等)
该项目为基于SpringBoot框架的Java课程资料,包含35个文件,其中26个为Java源文件,3个为SQL脚本,1个为Git忽略文件,1个为Maven构建配置文件,1个为XML配置文件,1个为Markdown文档,以及1个属性文件。这些资料旨在辅助教学活动,适用于相关Java课程的教学和实践。
那些年,与你同分同位次的同学都去了哪里?全国各大学在辽宁2020-2024年各专业最低录取分数及录取位次数据,高考志愿必备参考数据
职业心理测试综合素养测试32个文件职业心理测试综合素养测试32个文件
STM32硬件资料硬件工程师手册全STM32硬件资料硬件工程师手册全
微信小程序关注WXReading阅读
那些年,与你同分同位次的同学都去了哪里?全国各大学在辽宁2020-2024年各专业最低录取分数及录取位次数据,高考志愿必备参考数据
数据集格式:Pascal VOC格式+YOLO格式(不包含分割路径的txt文件,仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数):2694 标注数量(xml文件个数):2694 标注数量(txt文件个数):2694 标注类别数:4 标注类别名称:["concrete_mixer_truck","dump","dump_truck","excavator"] 标注类别中文名称:混凝土搅拌车、自卸汽车、自卸卡车、挖掘机 每个类别标注的框数: concrete_mixer_truck 框数 = 744 dump 框数 = 17 dump_truck 框数 = 2605 excavator 框数 = 1901 总框数:5267 使用标注工具:labelImg 标注规则:对类别进行画矩形框
微信小程序图表库,微信小程式图表_wx-Charts
那些年,与你同分同位次的同学都去了哪里?全国各大学在辽宁2020-2024年各专业最低录取分数及录取位次数据,高考志愿必备参考数据
那些年,与你同分同位次的同学都去了哪里?全国各大学在辽宁2020-2024年各专业最低录取分数及录取位次数据,高考志愿必备参考数据
T型NPC两级式光伏并网系统,前级boost升压DC-DC,采用MPPT控制(电导增量法),后级T型三电平进行并网,母线电压外环,电流内环,采用SPWM调制。 1.电导增量法,中点电位平衡控制 2.两级联调,T型三电平相较于普通的逆变器,其正弦度更高,THD更低 3.提供参考文献 支持simulink2022以下版本,联系跟我说什么版本,我给转成你需要的版本(默认发2016b)。
codemining-eclipse插件