举例
/product.jsp?id=1001
/product.jsp?id=1002
/product.jsp?id=1003
重写后,可以用
/product/1001.html
/product/1002.html
/product/1003.html
一、过滤器 用 urlReweite的类库
修改web.xml增加过滤器,然后配置个过滤规则
web.xml修改部分
<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>/*</url-pattern> </filter-mapping>
过滤规则 urlrewrite.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 2.6//EN" "http://tuckey.org/res/dtds/urlrewrite2.6.dtd"> <urlrewrite> <rule> <from>/poduct/(\d+).html$</from> <to>/product.jsp?id=$1</to> </rule> </urlrewrite>
二、使用Apache
# 去掉这个前面的#,启用它
LoadModule rewrite_module modules/mod_rewrite.so
<VirtualHost _default_:80>
# 其它的配置数据
RewriteEngine On
# 下面三行实现动态解析
RewriteRule ^/product/(\d+).html$ /product.jsp?id=$1 [L,PT]
</VirtualHost>
三、使用404页面跳转
web.xml修改部分
<error-page> <error-code>404</error-code> <location>/404.jsp</location> </error-page>
404.jsp 内容
<%@ page language="java" contentType="text/html; charset=UTF-8" isErrorPage="true"%> <% response.setStatus(HttpServletResponse.SC_OK); String key = (String) request.getAttribute("javax.servlet.forward.servlet_path"); try { if (key != null) { int index = key.lastIndexOf("/"); if (index != -1) { key = key.substring(index + 1); if (key.endsWith(".html")) { long id = Long.parseLong(key.substring(0, index-4)); String url = "product.jsp?productid=" + id; out.println(url); request.getRequestDispatcher(url).forward(request, response); } } } } catch(Exception e) { out.println("找不到该网页"); } %>