1

I am using Spring MVC with Spring Controllers. I want to always add a trailing slash if it is not present at the end of the url. How can I do this?

www.mysite.com/something -> www.mysite.com/something/
www.mysite.com/somethingelse/ -> www.mysite.com/somethingelse/
2
  • How are you running this app? Tomcat, Jetty, standalone or embedded? Commented Sep 28, 2018 at 23:46
  • @diginoise Tomcat. Commented Sep 29, 2018 at 0:37

1 Answer 1

1

You can achieve that using an HandlerInterceptor :

The interceptor will check if the request URI ends with a slash. If it does, the request is processed, if not, the response is redirected with the same URI with a trailing slash. In the example below, I ignore requests with a query string, since I don't kow how you want to handle this case.

The interceptor :

@Component
public class TrailingSlashInterceptor extends HandlerInterceptorAdapter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(StringUtils.isBlank(request.getQueryString()) && !request.getRequestURI().endsWith("/")) {
            response.sendRedirect(request.getRequestURL().append("/").toString());
            return false;
        }
        return true;
    }
}

Register and map the interceptor in your config :

@Autowired
private TrailingSlashInterceptor trailingSlashInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry
        .addInterceptor(trailingSlashInterceptor)
        .addPathPatterns("/**")
        .excludePathPatterns("/static/**");
}

I noticed that in your JSP, if you have some, you have to make URL start with a slash eg: <c:url value="/clients" />

Using this method, all requests that have no trailing slash will be temporary redirected (302) toward the same URI with a trailing slash.

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

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.