Zamboni
Zamboni

Reputation: 335

Always add trailing slash in url

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/

Upvotes: 1

Views: 2173

Answers (1)

Romain Warnan
Romain Warnan

Reputation: 1042

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.

Upvotes: 1

Related Questions