如何使用过滤器或 servlet 更改 requestURL [英] how to change the requestURL using filter or servlet
问题描述
如何使用过滤器或 servlet 更改 requestURL.
how to change the requestURL using filter or servlet .
例如如果请求是http://servername1:8080"我想将其更改为http://servername2:7001"
for example if request is "http://servername1:8080" I want to change the same to "http://servername2:7001"
推荐答案
添加以下 servlet 过滤器到您的应用程序:
Add the following servlet filter to your application:
public class RequestUrlRewritingFilter implements Filter {
//Empty init()/destroy() here
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final HttpServletRequestWrapper wrapped = new HttpServletRequestWrapper(request) {
@Override
public StringBuffer getRequestURL() {
final StringBuffer originalUrl = ((HttpServletRequest) getRequest()).getRequestURL();
return new StringBuffer("http://servername2:7001");
}
};
chain.doFilter(wrapped, response);
}
}
所有你想拦截的请求都必须经过它.如您所见,它采用原始 request
方法并通过返回不同的值来覆盖 getRequestURL()
方法.如果您想在旧 URL 的基础上创建新 URL,您仍然可以访问原始请求.
All requests you want to intercept must go through it. As you can see it takes original request
method and overrides getRequestURL()
method by returning a different value. You still have access to the original request if you want to base new URL on the old one.
最后,您必须继续处理请求 chain.doFilter()
但通过提供包装的请求,而不是原始请求.
At the end you must continue processing the request chain.doFilter()
but by providing wrapped request, not the original one.
这篇关于如何使用过滤器或 servlet 更改 requestURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!