我想实现一个自定义过滤器以将 URI 从 https://host123/app/users 更改为 https://host123/abc/users。在本例中,/app 和 /abc 是两个独立的 spring 应用程序,运行相同的 tomcat 服务器(两个 web 应用程序)。所以主机保持不变。 根据我在网上阅读的内容,这可以使用自定义过滤器来完成,因为两个 Spring 应用程序都在同一个 servlet 容器中。我在网上查了一下并创建了一个这样的过滤器:
@Component
public class myFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String reqURI = request.getRequestURI();
if (reqURI.startsWith("/app")) {
CustomServletRequest customRequest = new CustomServletRequest(request);
String reqURI = request.getRequestURI();
String newURI = "/abc" + reqURI.substring(4);
customRequest.setRequestURI(newURI);
filterChain.doFilter(customRequest, response);
} else {
filterChain.doFilter(request, response);
}
}
}
final class CustomServletRequest extends HttpServletRequestWrapper) {
private String modifiedURI;
public CustomServletRequest(HttpServletRequest request) {
super(request);
}
public void setRequestURI(String uri) {
this.modifiedURI = uri;
}
@Override
public String getRequestURI() {
return modifiedURI;
}
@Override
public StringBuffer getRequestURL() {
StringBuffer url = new StringBuffer();
url.append(getScheme()).append("://").append(getServerName()).append(modifiedURI);
return url;
}
}
问题是我收到 https:///app/users 的 404 错误。我无法使用重定向,因为我不想在客户端显示目标 URI。还有其他人遇到过类似的问题吗?上述实现中有什么遗漏/错误吗?我对 Spring 还很陌生,所以非常感谢任何帮助:) TIA!
我不认为你的方法有什么问题。
您也可以使用请求转发而不是 HttpServletRequestWrapper,如下所示:
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String reqURI = request.getRequestURI();
if (reqURI.startsWith("/app")) {
String newURI = "/abc" + reqURI.substring(4);
request.getRequestDispatcher(newURI).forward(request,response);
} else {
filterChain.doFilter(request, response);
}
}