如何在 Java 中使用 servlet 过滤器来更改传入的 servlet 请求 url?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2725102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:08:56  来源:igfitidea点击:

How to use a servlet filter in Java to change an incoming servlet request url?

javaurlservletsrequestservlet-filters

提问by Frank

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

如何使用 servlet 过滤器更改传入的 servlet 请求 url

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

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

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:

更新:根据以下 BalusC 的步骤,我想出了以下代码:

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.xmllook like this:

中的相关条目web.xml如下所示:

<filter>
    <filter-name>urlRewriteFilter</filter-name>
    <filter-class>com.example.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>urlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

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

我用预期的结果尝试了服务器端和客户端重定向。它奏效了,感谢 BalusC!

采纳答案by BalusC

  1. Implement javax.servlet.Filter.
  2. In doFilter()method, cast the incoming ServletRequestto HttpServletRequest.
  3. Use HttpServletRequest#getRequestURI()to grab the path.
  4. Use straightforward java.lang.Stringmethods like substring(), split(), concat()and so on to extract the part of interest and compose the new path.
  5. 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), orcast the incoming ServletResponseto HttpServletResponseand then HttpServletResponse#sendRedirect()to redirect the response to the new URL (client side redirect, reflected in browser address bar).
  6. Register the filter in web.xmlon an url-patternof /*or /Check_License/*, depending on the context path, or if you're on Servlet 3.0 already, use the @WebFilterannotation for that instead.
  1. 实施javax.servlet.Filter
  2. doFilter()方法中,将传入的转换ServletRequestHttpServletRequest.
  3. HttpServletRequest#getRequestURI()抢的路径。
  4. 使用简单的java.lang.String方法,如substring()split()concat()等提取感兴趣的部分,构成了新的路径。
  5. 使用ServletRequest#getRequestDispatcher()thenRequestDispatcher#forward()将请求/响应转发到新 URL(服务器端重定向,未反映在浏览器地址栏中),将传入的内容转换ServletResponseHttpServletResponse然后HttpServletResponse#sendRedirect()将响应重定向到新 URL(客户端重定向,反映在浏览器地址栏)。
  6. 根据上下文路径web.xmlurl-patternof/*或上注册过滤器/Check_License/*,或者如果您已经在 Servlet 3.0 上,请改用@WebFilter注释。

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

如果 URL需要更改,请不要忘记在代码中添加检查,如果不需要,则调用FilterChain#doFilter(),否则它将在无限循环中调用自身。

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

或者,您也可以仅使用现有的 3rd 方 API 来为您完成所有工作,例如Tuckey 的 UrlRewriteFilter,它可以像使用 Apache 的mod_rewrite.

回答by Pascal Thivent

You could use the ready to use Url Rewrite Filterwith a rule like this one:

您可以将准备使用的Url Rewrite Filter与这样的规则一起使用:

<rule>
  <from>^/Check_License/Dir_My_App/Dir_ABC/My_Obj_([0-9]+)$</from>
  <to>/Check_License?Contact_Id=My_Obj_</to>
</rule>

Check the Examplesfor more... examples.

查看示例以获取更多...示例。

回答by Xtreme Biker

A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.

基于BalusC's answer步骤的简单 JSF Url Prettyfier 过滤器。过滤器将所有以 /ui 路径(假设您已将所有 xhtml 文件存储在那里)开头的请求转发到同一路径,但添加了 xhtml 后缀。

public class UrlPrettyfierFilter implements Filter {

    private static final String JSF_VIEW_ROOT_PATH = "/ui";

    private static final String JSF_VIEW_SUFFIX = ".xhtml";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
        String requestURI = httpServletRequest.getRequestURI();
        //Only process the paths starting with /ui, so as other requests get unprocessed. 
        //You can register the filter itself for /ui/* only, too
        if (requestURI.startsWith(JSF_VIEW_ROOT_PATH) 
                && !requestURI.contains(JSF_VIEW_SUFFIX)) {
            request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
                .forward(request,response);
        } else {
            chain.doFilter(httpServletRequest, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}