Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC: How do I get current url in Thymeleaf

I am using Thymeleaf Template Engine with Spring Web MVC and I am got stuck while creating url's with the help of current url. Is there any way to get current inside Thymeleaf HTML file? eg: Suppose my current url in my browser address bar is:

http://localhost:8080/project/web/category/mobiles

and now I want to make a url like this http://localhost:8080/project/web/category/mobiles/store/samsung

or

http://localhost:8080/project/web/category/mobiles?min_price=10&max_price=100.

So I the code will look like this

<a th:with="currentUrl='http://localhost:8080/project/web/category/mobiles'"     th:href="@{__${currentUrl}__/__${store.name}__}">     Click to More Result </a> 

Here I am using currentUrl variable with hardcoded url, So I want to some solution for the same. The hardcoded value will not work everytime because I have dynamic categories.

I tried the same with relative url but its not working for me.

<a th:href="@{/store/__${store.name}__}">Click to More</a>  //will produce: http://localhost:8080/project/web/store/samsung //I want: http://localhost:8080/project/web/category/mobiles/store/samsung 

Please have a look and let me know if am I doing something wrong.

like image 723
Anil Kumar Pandey Avatar asked May 05 '14 06:05

Anil Kumar Pandey


People also ask

Is Thymeleaf supported by Spring MVC?

Thymeleaf offers a set of Spring integrations that allow you to use it as a fully-featured substitute for JSP in Spring MVC applications.

How do you get the model attribute in Thymeleaf?

In Thymeleaf, these model attributes (or context variables in Thymeleaf jargon) can be accessed with the following syntax: ${attributeName} , where attributeName in our case is messages .

How do I check condition in Thymeleaf?

To achieve similar to if-else condition in Thymeleaf we can use th:switch attribute. Thymeleaf at the first step will evaluate ${condition} expression and if the value is true it will print p tag with TRUE text.


2 Answers

Oh I got the solution for this. I missed the {#httpServletRequest.requestURI} in the documentation.

Here is the solution which is working for me:

<a th:href="@{__${#httpServletRequest.requestURI}__/store/__${store.name}__}">Click to More</a> //Will produce: http://localhost:8080/project/web/category/mobiles/store/samsung 
like image 148
Anil Kumar Pandey Avatar answered Sep 23 '22 13:09

Anil Kumar Pandey


You can get the current URL using two single ' quotes. Example:

<a th:href="@{''(lang=de)}">Deutsch</a> 

Note that this unfortulately does not include existing URL parameters.

like image 38
yglodt Avatar answered Sep 24 '22 13:09

yglodt