Is there a way in thymeleaf to get current url's portion after the base url and use it as a string for example in th:text?
Example: http://www.example.com/payment-page/pay I want the /payment-page/pay or payment-page/pay portion. Thanks.
Is there a way in thymeleaf to get current url's portion after the base url and use it as a string for example in th:text?
Example: http://www.example.com/payment-page/pay I want the /payment-page/pay or payment-page/pay portion. Thanks.
you can use this :
<span th:with="url=${#httpServletRequest.requestURI}"/>
<span th:text="${url}"></span>
examle output payment-page/pay for this url http://www.example.com/payment-page/pay.
For anyone searching on this, this answer no longer works with Thymeleaf 3.1.
I had the same issue. This is what I did:
@ControllerAdvice(basePackageClasses = AdminControllersPackage.class)
public class AdminControllerAdvice {
@ModelAttribute("requestURI")
String getRequestServletPath(HttpServletRequest request) {
return request.getServletPath();
}
}
The AdminControllersPackage class is just a marker class which I used so the ControllerAdvice would only apply to controllers in the relevant package. It's an empty definition:
final class AdminControllerPackage {
private AdminControllerPackage() { throw new RuntimeException(); }
}
If you want this to apply to all controllers in your application, you can omit that.
Then you can access requestURI like any other variable in your templates:
<p>The URI is: [[${requestURI}]]</p>
It's actually nice to do things this way, because more often I want to do some logic based on the URI and my ControllerAdvice could do a lot more in Java than I can practically put in a Thymeleaf expression.