三种方法实现URL重写

URL重写,就把动态URL静态化,便于搜索引擎爬虫抓取你的动态网页

举例
/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("找不到该网页");
}
%>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值