URL重写

URL重写说的简单一点就是把浏览器中显示的URL显示为你想要的各种形式的URL链接
除此之外,还能进行URL生成.html .htm .shtml等伪静态页面,更有利于搜索引擎的搜索
最近项目中用到了URL重写,其实URL重写有很多中方法,个人感觉用的比较多的有两种,
一种是写个filter对请求进行拦截,可以使用正则表达式进行匹配
1.配置过滤器一般在web.xml中
<filter>
<filter-name>urlFilter</filter-name>
<filter-class>com.url.filter.URLFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>urlFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>

2.过滤器处理类 URLFilter.java
public class URLFilter implements Filter {
public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain) throws
IOException,ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//做相应的拦截处理
//filterChain.doFilter代表请求已经通过拦截器,可以将请求转发或者重定向
filterChain.doFilter(servletRequest, servletResponse);

}

第二种方法是采用过滤组件,进行url重定向
下载urlrewrite-2.6.0.jar
1.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>confPath</param-name>
<param-value>/WEB-INF/urlrewrite.xml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

2.urlrewrite.xml名字不能改变,放在和web.xml一起即可
下面的正则表达式代表,它会拦截url后缀为0-9的链接,然后转发到jsp/url.jsp页面,并把匹配的正则表达式复制给mid,url.jsp页面可以得到匹配的正则表达式的值

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.1//EN"
"http://tuckey.org/res/dtds/urlrewrite3.1.dtd">
<urlrewrite>
<rule>
<from>^/([0-9]*)$</from>
<to>/jsp/url.jsp?mid=$1</to>
</rule>
</urlrewrite>
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页