forked from thymeleaf/thymeleaf.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspringmvcaccessdata.html
321 lines (256 loc) · 11.5 KB
/
springmvcaccessdata.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Spring MVC and Thymeleaf: how to access data from templates - Thymeleaf: java XML/XHTML/HTML5 template engine</title>
<link rel="stylesheet" type="text/css" media="all" href="css/thymeleaf.css" />
<link rel="shortcut icon" href="http://www.thymeleaf.org/favicon.ico" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1276954-9']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript" src="sh/scripts/shCore.js"></script>
<script type="text/javascript" src="sh/scripts/shBrushXml.js"></script>
<script type="text/javascript" src="sh/scripts/shBrushJava.js"></script>
<link href="sh/styles/shCore.css" rel="stylesheet" type="text/css" />
<link href="sh/styles/shThemeThymeleaf.css" rel="stylesheet" type="text/css" />
</head>
<body lang="en" dir="ltr">
<div id="page">
<div id="menu">
<ul>
<li><a href="index.html" title="Home">Home</a></li>
<li><a href="features.html" title="Features">Features</a></li>
<li><a href="download.html" title="Download">Download</a></li>
<li><a href="documentation.html" title="Documentation">Documentation</a></li>
<li><a href="ecosystem.html" title="Ecosystem">Ecosystem</a></li>
<li><a href="http://forum.thymeleaf.org" title="User Forum">User Forum</a></li>
<li><a href="issuetracking.html" title="Issue Tracking">Issue Tracking</a></li>
</ul>
</div>
<div id="header">
<a href="index.html" title="Thymeleaf home"><img src="images/thymeleaflogonameverysmall.png" class="logo" alt="Thymeleaf Template Engine"/></a>
</div>
<div id="breadcrumb">
<a href="index.html">thymeleaf</a>
::
<a href="documentation.html">documentation</a>
::
articles
::
<span class="current">spring mvc and thymeleaf - how to access data from templates</span>
</div>
<div id="content">
<h1>Spring MVC and Thymeleaf: how to access data from templates</h1>
<p id="author">
<i>By Rafał Borowiec — <a href="http://blog.codeleak.pl" target="_blank">http://blog.codeleak.pl</a></i>
</p>
<p>
In a typical Spring MVC application, <kbd>@Controller</kbd> classes are responsible for preparing a model map
with data and selecting a view to be rendered. This <em>model map</em> allows for the complete abstraction
of the view technology and, in the case of Thymeleaf, it is transformed into a
<kbd>VariablesMap</kbd> object (part of the Thymeleaf <em>template execution context</em>) that makes all the
defined variables available to expressions executed in templates.
</p>
<h2>Spring model attributes</h2>
<p>
Spring MVC calls the pieces of data that can be accessed during the execution of views
<em>model attributes</em>. The equivalent term in Thymeleaf language is <em>context variables</em>.
</p>
<p>
There are several ways of adding model attributes to a view in Spring MVC. Below you will find some
common cases:
</p>
<p>
Add attribute to <kbd>Model</kbd> via its <kbd>addAttribute</kbd> method:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("messages", messageRepository.findAll());
return "message/list";
}
]]></script>
<p>
Return <kbd>ModelAndView</kbd> with model attributes included:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@RequestMapping(value = "message", method = RequestMethod.GET)
public ModelAndView messages() {
ModelAndView mav = new ModelAndView("message/list");
mav.addObject("messages", messageRepository.findAll());
return mav;
}
]]></script>
<p>
Expose common attributes via methods annotated with <kbd>ModelAttribute</kbd>:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@ModelAttribute("messages")
public List<Message> messages() {
return messageRepository.findAll();
}
]]></script>
<p>
As you may have noticed, in all the above cases the <kbd>messages</kbd> attribute is added to the
model and it will be available in Thymeleaf views.
</p>
<p>
In Thymeleaf, these model attributes (or <em>context variables</em> in Thymeleaf jargon) can be
accessed with the following syntax: <kbd>${attributeName}</kbd>, where <kbd>attributeName</kbd> in our
case is <kbd>messages</kbd>. This is a <a target="_blank"
href="http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/expressions.html">Spring EL</a>
expression. In short, Spring EL (Spring Expression Language) is a language that supports querying and
manipulating an object graph at runtime.
</p>
<p>
You can access model attributes in views with Thymeleaf as follows:
</p>
<script type="syntaxhighlighter" class="brush:html"><![CDATA[
<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>
]]></script>
<h2>Request parameters</h2>
<p>
Request parameters can be easily accessed in Thymeleaf views. Request parameters are passed from the client
to server like:
</p>
<script type="syntaxhighlighter" class="brush:html;gutter:false"><![CDATA[
https://example.com/query?q=Thymeleaf+Is+Great!
]]></script>
<p>
Let's assume we have a <kbd>@Controller</kbd> that sends a redirect with a request parameter:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@Controller
public class SomeController {
@RequestMapping("/")
public String redirect() {
return "redirect:/query?q=Thymeleaf Is Great!";
}
}
]]></script>
<p>
In order to access the <kbd>q</kbd> parameter you can use the <kbd>param.</kbd> prefix:
</p>
<script type="syntaxhighlighter" class="brush:html"><![CDATA[
<p th:text="${param.q[0]}" th:unless="${param.q == null}">Test</p>
]]></script>
<p>
Two things are important to notice in the above example:
</p>
<ul>
<li><kbd>${param.q != null}</kbd> checks if the parameter <kbd>q</kbd> is set.</li>
<li>Parameters are always string arrays, as they can be multivalued (e.g. <kbd>https://example.com/query?q=Thymeleaf%20Is%20Great!&q=Really%3F</kbd>).</li>
</ul>
<p>
Another way to access request parameters is by using the special object <kbd>#httpServletRequest</kbd> that
gives you direct access to the <kbd>javax.servlet.http.HttpServletRequest</kbd> object:
</p>
<script type="syntaxhighlighter" class="brush:html"><![CDATA[
<p th:text="${#httpServletRequest.getParameter('q')}"
th:unless="${#httpServletRequest.getParameter('q') == null}">Test</p>
]]></script>
<h2>Session attributes</h2>
<p>
In the below example we add <kbd>mySessionAttribute</kbd> to session:
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@RequestMapping({"/"})
String index(HttpSession session) {
session.setAttribute("mySessionAttribute", "someValue");
return "index";
}
]]></script>
<p>
Similarly to the request parameters, session attributes can be access by using the <kbd>session.</kbd> prefix:
</p>
<script type="syntaxhighlighter" class="brush:html"><![CDATA[
<div th:text="${session.mySessionAttribute}">[...]</div>
]]></script>
<p>
Or by using <kbd>#httpSession</kbd>, that gives you direct access to the
<kbd>javax.servlet.http.HttpSession</kbd> object.
</p>
<h2>ServletContext attributes</h2>
<p>
The ServletContext attributes are shared between requests and sessions. In order to access
ServletContext attributes in Thymeleaf you can use the <kbd>application.</kbd> prefix:
</p>
<script type="syntaxhighlighter" class="brush:html"><![CDATA[
<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>
]]></script>
<h2>Spring beans</h2>
<p>
Thymeleaf allows accessing beans registered at the Spring Application Context with the
<kbd>@beanName</kbd> syntax, for example:
</p>
<script type="syntaxhighlighter" class="brush:html"><![CDATA[
<div th:text="${@urlService.getApplicationUrl()}">...</div>
]]></script>
<p>
In the above example, <kbd>@urlService</kbd> refers to a Spring Bean registered at your context, e.g.
</p>
<script type="syntaxhighlighter" class="brush:java"><![CDATA[
@Configuration
public class MyConfiguration {
@Bean(name = "urlService")
public UrlService urlService() {
return new FixedUrlService("somedomain.com/myapp); // some implementation
}
}
public interface UrlService {
String getApplicationUrl();
}
]]></script>
<p>
This is fairly easy and useful in some scenarios.
</p>
</div>
<div id="footer">
<div id="googleplus">
<div id="plusone-div" class="plusone"></div>
<script type="text/javascript">
gapi.plusone.render('plusone-div',{"size": "small", "count": "true", "href": "http://www.thymeleaf.org"});
</script>
</div>
<div id="twitter">
<a href="http://twitter.com/thymeleaf" class="twitter-follow-button" data-show-count="false">Follow @thymeleaf</a>
<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
</div>
<div id="copy">
Copyright © The <a href="team.html">THYMELEAF Team</a>. See <a href="documentation.html">applicable licenses</a>.
</div>
</div>
</div>
<script type="text/javascript">
SyntaxHighlighter.all();
</script>
</body>
</html>