Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf construct URL with variable

I have the following code setting a variable in my controller:

model.set("type", type);

In the thymeleaf view I want to construct a form with action url:

/mycontroller/{type}

Any ideas how to achieve this? I've read thymeleaf documentation with no luck.

like image 413
Chris Avatar asked Feb 18 '13 14:02

Chris


3 Answers

As user482745 suggests in the comments (now deleted), the string concatenation I previously suggested

<form th:action="@{/mycontroller/} + ${type}">

will fail in some web contexts.

Thymeleaf uses LinkExpression that resolves the @{..} expression. Internally, this uses HttpServletResponse#encodeURL(String). Its javadoc states

For robust session tracking, all URLs emitted by a servlet should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies.

In web applications where the session tracking is done through the URL, that part will be appended to the string emitted for @{..} before the ${..} is appended. You don't want this.

Instead, use path variables as suggested in the documentation

You can also include parameters in the form of path variables similarly to normal parameters but specifying a placeholder inside your URL’s path:

<a th:href="@{/order/{id}/details(id=3,action='show_all')}">

So your example would look like

<form th:action="@{/mycontroller/{path}(path=${type})}"> //adding ending curly brace
like image 94
Sotirios Delimanolis Avatar answered Nov 14 '22 05:11

Sotirios Delimanolis


If You don't want to use string concatenation (proposed by Sotirios), You can use expression preprocessing in URL link:

<form th:action="@{/mycontroller/__${type}__}">
like image 23
lu_ko Avatar answered Nov 14 '22 05:11

lu_ko


You need concatenate string inside @{}.

<form th:action="@{'/mycontroller/' + ${type}}">

@{} is used for URL rewriting. Part of URL rewriting is keeping track of session. First time user request URL, app server adds to url ;jsessionid=somehexvalue and generates cookie with jsessionid. When client sends cookie during next request server knows client supports cookies. If server knows that client support cookies, server will not keep addind jsessionid in URL.

My preferred way is literal substitution with the pipeline syntax (|).

<form th:action="@{|/mycontroller/${type}|}">

Thymeleaf path variable syntax is

<form th:action="@{/mycontroller/{pathParam}(pathParam=${type}}">

Reference: Thymeleaf Standard URL Syntax

like image 18
user482745 Avatar answered Nov 14 '22 06:11

user482745