首页 > 代码库 > Spring URL重写

Spring URL重写

1.利用maven下载相关jar文件,pom文件配置如下:

<dependency>
    <groupId>org.tuckey</groupId>
    <artifactId>urlrewritefilter</artifactId>
    <version>4.0.4</version>
</dependency>

2.在web.xml中配置UrlRewriteFilter,配置如下:

<filter>
  <filter-name>UrlRewriteFilter</filter-name>
  <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
  <!-- 因为urlrewrite.xml只能在web-inf下,所以我们这里可以省略掉urlrewrite.xml的路径配置。 -->
  <init-param>
    <param-name>logLevel</param-name>
    <param-value>WARN</param-value>
  </init-param>
</filter>
  <filter-mapping>
  <filter-name>UrlRewriteFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
</filter-mapping>

3.添加urlrewirte.xml文件,将文件放在WEB-INF目录下(貌似该文件只能放在WEB-INF下)。配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN" "\\urlrewrite3.2.dtd">
<urlrewrite>
  <rule>
    <note>重写loign.jsp成login.html</note>
    <!-- 对应controller中redireact的路径 -->
    <from>login.html</from>
    <!-- 对应实际工程中jsp文件 -->
    <to type="forward">/login.jsp</to>
  </rule>
</urlrewrite>

4.程序controller中的返回内容要与<from>中的内容一致,比如下列代码片返回值得要与urlrewrite中的一致:

@RequestMapping(value="http://www.mamicode.com/login.do")
public String login(HttpServletRequest request, HttpServletResponse response, Role role) throws Exception {
if (userService.selectRoleByNameAndPassword(role)) {
    return "index";
  } else {
    return "redirect:login.html";
  }
}

Spring URL重写