Rewrite URL in Spring Framework
This post is about Spring Framework; if you are not familiar with this framework, reading this article may be useful to you.Using slug in URLs has many benefits, including SEO-friendly and user-friendly. Tuckey is a Java Web Filter which allows you to rewrite URLs before they get to your code ( like Apache’s mod_rewrite).
for using tuckey in spring framework, you must add it’s dependency to pom.xml
:
<dependency>
<groupId>org.tuckey</groupId>
<artifactId>urlrewritefilter</artifactId>
<version>4.0.3</version>
</dependency>
Then in web.xml
must add this filter:
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/portal/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
finally, you should create a urlrewrite.xml
file in procjetName/src/main/webapp/WEB-INF
path and write your rules for rewrite URLs into this file. for example:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN" "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">
<urlrewrite>
<rule>
<from>^/news/(.*)/(.*)$</from>
<to type="passthrough">/rest/news/details/$1?title=$2</to>
</rule>
</urlrewrite>
There are many other things you can do with the tuckey, including: slugify
URLs, showing specific error page for HTTP error responses, URL redirection and so on.