2

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.

1
  • 2
    I would try using {#httpServletRequest.requestURI} to get the full URL and then implement a simple function to remove the base URL from the string. Depending on your requirements you could also do this on the server side and pass the relative URL as a string variable to your view. Commented Oct 2, 2017 at 13:22

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.