1. 程式人生 > >配置struts2過濾器 session失效跳轉到登陸頁面

配置struts2過濾器 session失效跳轉到登陸頁面

前言,第一次配置過濾器遇到了一些問題,研究了兩天總結出點規律:沒搞懂之前不要輕易的copy別人的程式碼,.很多人查一下程式碼直接copy web.xml檔案的過濾配置,卻不懂 

<url-pattern>是什麼意思。

一,配置過濾器: SSH專案很多頁面的跳轉都是通過action執行的,而不是寫一個<a href="jsp1/Add.jsp">Forward to Filter URL</a>這樣的路徑直接跳轉的,如果都是通過action跳轉的只要在web.xlm配置就可以全過濾了:

   <filter-name>filterTest</filter-name>   
     <filter-class>com.dwg.FilterAndListener.FilterTest</filter-class>   
  </filter>
<filter-mapping>   
     <filter-name>filterTest</filter-name>   
     <url-pattern>*.action</url-pattern>   
  </filter-mapping> 
對應的filter類:
package com.dwg.Filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class FilterTest extends HttpServlet implements Filter {   
   
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void destroy() {   
        // TODO Auto-generated method stub   
   
    }

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
        HttpServletRequest httpReq=(HttpServletRequest)req;   
        HttpServletResponse httpRes=(HttpServletResponse)res;   
        HttpSession httpSession=httpReq.getSession(); 
        String url = httpReq.getRequestURI();
        //System.out.println(url);
        if(httpSession.getAttribute("username")==null){ 
        	if(url.endsWith("index.jsp") || url.endsWith("LoginUser.action") ){
        		chain.doFilter(req, res);
        	}
        	else{
        	//System.out.println("User物件空值");
        	httpRes.sendRedirect(httpReq.getContextPath()+"/index.jsp");
        	}
        }else{ 
        	//System.out.println("cale");
            chain.doFilter(req, res);   
        }  
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}   
}

二。很多頁面跳轉是用的<a href="jsp1/Add.jsp">Forward to Filter URL</a>這樣的方式的話web.xml配置就要過濾子目錄:

   <filter-name>filterTest</filter-name>   
     <filter-class>com.dwg.FilterAndListener.FilterTest</filter-class>   
  </filter>
 <filter-mapping>   
     <filter-name>filterTest</filter-name>   
     <url-pattern>/jsp1/*</url-pattern>   
  </filter-mapping> 
        <filter-mapping>   
     <filter-name>filterTest</filter-name>   
     <url-pattern>*.action</url-pattern>   
  </filter-mapping> 
三。也就是說<url-pattern>內容取決你你訪問頁面的方式  把所有的.jsp檔案放到一個資料夾下,但是訪問方式為action方式,web.xml再用子目錄過濾(<url-pattern>/jsp1/*</url-pattern>)是不生效的。