-
Notifications
You must be signed in to change notification settings - Fork 188
/
TrailingSlashRedirectingFilter.java
56 lines (51 loc) · 2.21 KB
/
TrailingSlashRedirectingFilter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* Copyright (c) 2010-2019 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.web.boot;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author skublik
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TrailingSlashRedirectingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String pathWithoutContextPath;
String uri = request.getRequestURI();
if (StringUtils.isNotBlank(request.getContextPath()) && uri.startsWith(request.getContextPath())) {
if (uri.length() == request.getContextPath().length()) {
pathWithoutContextPath = "";
} else {
pathWithoutContextPath = uri.substring(request.getContextPath().length());
}
} else {
pathWithoutContextPath = uri;
}
if (StringUtils.isNotBlank(pathWithoutContextPath) && !pathWithoutContextPath.equals("/") && pathWithoutContextPath.endsWith("/")) {
ServletUriComponentsBuilder builder =
ServletUriComponentsBuilder.fromRequest(request);
builder.replacePath(builder.build().getPath().replaceFirst(".$",""));
response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());
response.setHeader(HttpHeaders.LOCATION,
builder.toUriString());
} else {
filterChain.doFilter(request, response);
}
}
}