---
title: "通过服务器的404文件没有找到的错误处理，实现url rewrite的功能"
author: "haimav"
date: "2009-09-25T19:04:26Z"
tags: []
slug: "404-url-rewrite"
draft: false
lastmod: "2009-09-25T19:04:26Z"
id: 477489
url: "https://haimav.iteye.com/blog/477489"
---

本站提供的功能如下  
[http://www.java2000.net/f29](http://www.java2000.net/f29)  
会被自动转发到  
[http://www.java2000.net/forumdisplay.jsp?fid=29](http://www.java2000.net/forumdisplay.jsp?fid=29)

因为系统并不存在f29,所以使用了404的错误处理页面来实现这个功能  
页面代码如下

```
<%@ page language="java" contentType="text/html; charset=GBK" isErrorPage="true" pageEncoding="GBK"%>
<%
  response.setStatus(HttpServletResponse.SC_OK);
  String key = (String) request.getAttribute("javax.servlet.forward.servlet_path");
  if (key != null) {
    int index = key.lastIndexOf("/");
    if (index != -1) {
      key = key.substring(index + 1);
      if (key.startsWith("f") || key.startsWith("p")) {
        try {
          long id = Long.parseLong(key.substring(1));
          String url = key.startsWith("f") ? "forumdisplay.jsp?fid=" : "viewthread.jsp?tid=";
%>
<jsp:forward page="<%=url+id%>"></jsp:forward>
<%
  return;
        } catch (Exception ex) {}
      }
%>
<jsp:forward page="<%=response.encodeURL("search.jsp")%>"><jsp:param name="keyword" value="<%=key %>" /></jsp:forward>
<%
  return;
    }
  }
%>
对不起，您请求的页面没有找到!
```