servlet过滤器重写URL [英] servlet filter to rewrite URL

查看:164
本文介绍了servlet过滤器重写URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从以下位置重写网址:

I am trying to rewrite a URL from:


  • localhost:8080 / sendEmail / newEmail.pdf? request_id = 23456& emailAddress =

  • localhost:8080/sendEmail/newEmail.pdf?request_id=23456&emailAddress=

收件人:


  • localhost:8080 / sendEmail / newEmail.pdf?request_id = 23456

  • localhost:8080/sendEmail/newEmail.pdf?request_id=23456

过滤器类代码和映射如下。我怎样才能完成这项任务? (一个例子的答案将受到高度赞赏)。

Filter class code and mapping is below. How can I accomplish this task? (An answer with an example would be highly appreciated).

过滤映射:

<filter>
    <filter-name>RequestFilter</filter-name>
    <filter-class>com.abc.ms.email.filter.RequestFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>RequestFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

过滤代码:

public class RequestFilter implements Filter {
    private static final Pattern REWRITE_PATTERN = Pattern.compile("(^[1-9]\\d*)$");

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper((HttpServletRequest)req);
        String url = wrapper.getRequestURL().toString();
        String number = url.substring(url.lastIndexOf("/")).replace("/", "");
        Matcher m = REWRITE_PATTERN.matcher(number);
        if (m.find()) {
            RequestDispatcher dispatcher = wrapper.getRequestDispatcher("request?id=" + m.group(1));
            dispatcher.forward(req, res);
        } else {
            fc.doFilter(wrapper, res);
        }
    }
}


推荐答案

我建议使用现有的实现,而不是自己编写。

I would recommend using an existing implementation, rather than writing this on your own.

似乎有一个 Java URL重写实现,这是Tuckey的URLrewriteFilter。

There seems to be the one Java URL rewriting implementation, which is Tuckey's URLrewriteFilter.

参见: http:/ /tuckey.org/urlrewrite/

这应该做你想要的,还有更多。

This should do what you want, and a lot more.

或者,如果您在Web容器前使用apache,您可能需要查看
mod_rewrite ,这在apache上也是如此。

Alternatively, if you use apache in front of your web container, you might want to look into mod_rewrite, which does the same on apache.

http:// httpd。 apache.org/docs/current/mod/mod_rewrite.html

这篇关于servlet过滤器重写URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆