web.xml文件:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 3 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"> 4 <session-config> 5 <session-timeout>10</session-timeout> 6 </session-config> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 <filter> 11 <filter-name>UrlRewriterHelper</filter-name> 12 <filter-class>helper.UrlRewriterHelper</filter-class> 13 </filter> 14 <filter-mapping> 15 <filter-name>UrlRewriterHelper</filter-name> 16 <url-pattern>/*</url-pattern> 17 </filter-mapping> 18 </web-app>
UrlRewriterHelper文件:
1 package helper; 2 3 import java.io.IOException; 4 import java.net.HttpRetryException; 5 6 import javax.servlet.Filter; 7 import javax.servlet.FilterChain; 8 import javax.servlet.FilterConfig; 9 import javax.servlet.RequestDispatcher; 10 import javax.servlet.ServletException; 11 import javax.servlet.ServletRequest; 12 import javax.servlet.ServletResponse; 13 import javax.servlet.http.HttpServletRequest; 14 15 public class UrlRewriterHelper implements Filter { 16 17 @Override 18 public void destroy() { 19 // TODO Auto-generated method stub 20 21 } 22 23 @Override 24 public void doFilter(ServletRequest arg0, ServletResponse response, 25 FilterChain arg2) throws IOException, ServletException { 26 // TODO Auto-generated method stub 27 if (arg0 instanceof HttpServletRequest) { 28 HttpServletRequest request = (HttpServletRequest) arg0; 29 String url = request.getRequestURI(); 30 int beginIndex = url.lastIndexOf(".htm"); 31 if (beginIndex == url.length() - 4) { 32 String newUrl = url.substring(0, beginIndex) + ".jsp"; 33 String contextRoot = request.getContextPath(); 34 beginIndex = newUrl.indexOf(contextRoot); 35 if (beginIndex == 0) { 36 newUrl = newUrl.substring(contextRoot.length()); 37 RequestDispatcher dispatcher = request.getRequestDispatcher(newUrl); 38 dispatcher.forward(request, response); 39 return; 40 } 41 } 42 } 43 arg2.doFilter(arg0, response); 44 } 45 46 @Override 47 public void init(FilterConfig arg0) throws ServletException { 48 // TODO Auto-generated method stub 49 50 } 51 52 }
Jsp通过Filter实现UrlRewriter原理,布布扣,bubuko.com
原文:http://www.cnblogs.com/qiyebao/p/3694565.html