title: How to use a servlet filter in Java to change an incoming servlet request url?
body: <p>How can I use a servlet filter to change an incoming servlet request url from</p>
  
  <p><code>http://nm-java.appspot.com/Check_License/Dir_My_App/Dir_ABC/My_Obj_123</code></p>
  
  <p>to</p>
  
  <p><code>http://nm-java.appspot.com/Check_License?Contact_Id=My_Obj_123</code></p>
  
  <p>?</p>
  
  <hr>
  
  <p><strong>Update</strong>: according to BalusC's steps below, I came up with the following code:</p>
  
  <pre><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() {
          //
      }
  }
  </code></pre>
  
  <p>The relevant entry in <code>web.xml</code> look like this:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;filter&gt;
      &lt;filter-name&gt;urlRewriteFilter&lt;/filter-name&gt;
      &lt;filter-class&gt;com.example.UrlRewriteFilter&lt;/filter-class&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;urlRewriteFilter&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  </code></pre>
  
  <p>I tried both server-side and client-side redirect with the expected results. It worked, thanks BalusC!</p>