java 该改变request url,如何在Java中使用servlet过滤器来更改传入的servlet请求URL?...

How can I use a servlet filter to change an incoming servlet request url from

http://nm-java.appspot.com/Check_License/Dir_My_App/Dir_ABC/My_Obj_123

to

http://nm-java.appspot.com/Check_License?Contact_Id=My_Obj_123

?

Update: according to BalusC's steps below, I came up with the following code:

public class UrlRewriteFilter implements Filter {

@Override

public void init(FilterConfig config) throws ServletException {

//

}

@Override

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {

HttpServletRequest request = (HttpServletRequest) req;

String requestURI = request.getRequestURI();

if (requestURI.startsWith("/Check_License/Dir_My_App/")) {

String toReplace = requestURI.substring(requestURI.indexOf("/Dir_My_App"), requestURI.lastIndexOf("/") + 1);

String newURI = requestURI.replace(toReplace, "?Contact_Id=");

req.getRequestDispatcher(newURI).forward(req, res);

} else {

chain.doFilter(req, res);

}

}

@Override

public void destroy() {

//

}

}

The relevant entry in web.xml look like this:

urlRewriteFilter

com.example.UrlRewriteFilter

urlRewriteFilter

/*

I tried both server-side and client-side redirect with the expected results. It worked, thanks BalusC!

解决方案

Use straightforward java.lang.String methods like substring(), split(), concat() and so on to extract the part of interest and compose the new path.

Use either ServletRequest#getRequestDispatcher() and then RequestDispatcher#forward() to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incoming ServletResponse to HttpServletResponse and then HttpServletResponse#sendRedirect() to redirect the response to the new URL (client side redirect, reflected in browser address bar).

Register the filter in web.xml on an url-pattern of /* or /Check_License/*, depending on the context path, or if you're on Servlet 3.0 already, use the @WebFilter annotation for that instead.

Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter(), else it will call itself in an infinite loop.

Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值