話不多說,直接上代碼
創建一個Filter類
1 package com.weibo.util; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 /** 14 * 原理是,將所有的地址中包含JSP的訪問攔截,將訪問重定位到網站的跟目錄 15 * @author yu 16 */ 17 public class URLFilter implements Filter{ 18 19 @Override 20 public void destroy() { 21 // TODO Auto-generated method stub 22 23 } 24 25 @Override 26 public void doFilter(ServletRequest request, ServletResponse response, 27 FilterChain filterch) throws IOException, ServletException { 28 // TODO Auto-generated method stub 29 HttpServletRequest httpreq = (HttpServletRequest) request; 30 StringBuffer url = httpreq.getRequestURL(); 31 if(url.indexOf("jsp") > 0) //判斷地址中是否包含"JSP" 32 { 33 HttpServletResponse httpres = (HttpServletResponse) response; 34 httpres.sendRedirect(httpreq.getContextPath()); //跳轉到網站根目錄,也可以根據自己的需要重定位到自己的Action 35 return; 36 }else{ //不包含JSP,則繼續執行 37 filterch.doFilter(request, response); 38 } 39 40 } 41 42 @Override 43 public void init(FilterConfig arg0) throws ServletException { 44 // TODO Auto-generated method stub 45 46 } 47 48 }
在web.xml中配置Filter,注意:應將此過濾器放在Struts的前面
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> 3 <display-name>final</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 </welcome-file-list> 12 <filter> 13 <filter-name>URLfilter</filter-name> 14 <filter-class>com.weibo.util.URLFilter</filter-class> 15 </filter> 16 <filter-mapping> 17 <filter-name>URLfilter</filter-name> 18 <url-pattern>/*</url-pattern> 19 </filter-mapping> 20 21 22 <filter> 23 <filter-name>struts</filter-name> 24 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 25 </filter> 26 <filter-mapping> 27 <filter-name>struts</filter-name> 28 <url-pattern>/*</url-pattern> 29 </filter-mapping> 30 31 </web-app>