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


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com