springboot中url地址重写(urlwrite)

在日常网站访问中,会把动态地址改造成伪静态地址。

例如: 访问新闻栏目 /col/1/,这是原有地址,如果这样访问,不利于搜索引擎检索收录,同时安全性也不是很好。

改造之后:

/col/1.html。

改造方法:

1.添加urlrewritefilter

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

2.配置bean

import java.io.IOException;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.tuckey.web.filters.urlrewrite.Conf;
import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter;

@Configuration
public class UrlRewriteFilterConfig extends UrlRewriteFilter {

  private static final String URL_REWRITE = "classpath:/urlrewrite.xml";

  // Inject the Resource from the given location
  @Value(URL_REWRITE)
  private Resource resource;

  // Override the loadUrlRewriter method, and write your own implementation
  protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
    try {
      // Create a UrlRewrite Conf object with the injected resource
      Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(),
          "@@traceability@@");
      checkConf(conf);
    } catch (IOException ex) {
      throw new ServletException("Unable to load URL rewrite configuration file from " + URL_REWRITE, ex);
    }
  }
}

参考网址:http://blog.jdriven.com/2016/02/urlrewritefilter-load-configuration-with-spring-resourceloader/

3.配置urlrewrite.xml

<?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>^/col/(\w+)\.html$</from>
        <to>/col/$1/</to>
    </rule>

    <!-- 栏目列表页,注意html后面没有加$,因为后面还有若干参数 -->
    <rule>
        <from>^/col/list/(\w+)/(\w+)\.html</from>
        <to>/col/list/$1/$2/</to>
    </rule>

    <!-- 文章详情页 -->
    <rule>
        <from>^/art/(\w+)\.html$</from>
        <to>/art/$1/</to>
    </rule>
    
    <!-- 静态网页 -->
    <rule>
        <from>^/static/(\w+)\.html$</from>
        <to>/static/$1/</to>
    </rule>

</urlrewrite>

image

配置说明请参考:http://blog.163.com/zhangmihuo_2007/blog/static/27011075201351433716225/

至此配置完毕,启动测试,注意看红框处,说明加载了urlwrite。

image

访问页面如下,成功了!

image

posted @ 2017-11-10 19:01  huiy_小溪  阅读(11965)  评论(1编辑  收藏  举报