Use regular expressions to do url rewriting in java:
1. Copy the library into your project under `WEB-INF/lib/` 2. Add the `URLRewrite` filter into your `WEB-INF/web.xml`<filter> <filter-name>URLRewrite</filter-name> <filter-class>org.urlrewrite.URLRewrite</filter-class> </filter> <filter-mapping> <filter-name>URLRewrite</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>3. Create the file: `WEB-INF/url-rewriting.xml` 4. Add your rules
<?xml version="1.0" encoding="UTF-8" ?> <url-rewriting> <rewrite from="/best/url$" to="/index.jsp?url=#{0}" /> <rewrite from="/best/url/permanently$" to="/index.jsp?url=#{0}" status="301" /> </url-rewriting>
Where #{0}
will refer to your current URL
<?xml version="1.0" encoding="UTF-8" ?> <url-rewriting> <rewrite from="/best/([^/]+)/$" to="/index.jsp?url=#{0}&mySelection=#{1}" />This is a strong feature because you can generate your own `new url` however you want: generate it using your database maybe.<rewrite from="/index.jsp$" to="/new/url" status="301" /> <rewrite from="/new/url$" to="/index.jsp?nice-url=yes-it-worked" />
</url-rewriting>
You have to extend: org.urlrewrite.URLHandler
and that's it.
Using getResponse
, getRequest
you have access to HTTPServlet.*
.
You can take a look at
<?xml version="1.0" encoding="UTF-8" ? > <url-rewriting> <rewrite from="/best/([^/]+)/$" handler="my.project.MyURLHandlerImplementation" /> <rewrite from="/index.jsp$" to="/new/url" status="301" /> <rewrite from="/new/url$" to="/index.jsp?nice-url=yes-it-worked" /> </url-rewriting>By default are considered only:
- 301 - Permanent redirect
- 302 - Found
- 307 - Temporary redirect (since HTTP 1.1)
But you can use:
- no status code and it will be default to
200
- any other code like
404