1. 程式人生 > >struts2配置定義過濾器無效

struts2配置定義過濾器無效

今天在用struts2寫一個自定義過濾器的時候發現想要過濾的請求一直沒有進入過濾器,一直覺得奇怪了。

在web.xml中就是這樣配置的。

	<filter>
		<filter-name>login filter</filter-name>
		<filter-class>com.danale.filter.LoginFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>login filter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	 
	</filter-mapping>
 	<filter-mapping>
		<filter-name>login filter</filter-name>
		<url-pattern>*.action</url-pattern>
	 
	</filter-mapping>

我的目地是想將未登入的使用者請求(.jsp   .action),多轉入到過濾器,而且跳轉到login

過濾器是這麼寫的。

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		HttpSession session = request.getSession();
		String url = request.getRequestURI();
		String username = (String) session.getAttribute("username");
		if (username == null || username.equals("")) {
			if (url != null && !url.equals("")
					&& (url.indexOf("Login") < 0 && url.indexOf("login") < 0)) {
				response.sendRedirect("login.jsp");
				return;			}		}
		arg2.doFilter(arg0, arg1);
		return;
	}

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

	}
}
開始覺得這沒有任何問題啊,至少沒發現,

後來把web.xml中的配置改成

	<filter>
		<filter-name>login filter</filter-name>
		<filter-class>com.danale.filter.LoginFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>login filter</filter-name>
		<url-pattern>/*</url-pattern>
	 
	</filter-mapping>
確實起作用的,把所以的請求都攬入過濾器中的,但是出現了一個問題,就是連頁面的css,js等等全部都過濾了,出現了只有html元素的頁面,這也不行。

後面經過查詢,只需要把自定義的過濾器在web.xml中的配置放在struts過濾器的前面才會生效。如:

	<filter>
		<filter-name>login filter</filter-name>
		<filter-class>com.danale.filter.LoginFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>login filter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	 
	</filter-mapping>
 	<filter-mapping>
		<filter-name>login filter</filter-name>
		<url-pattern>*.action</url-pattern>
	 
	</filter-mapping>
	<filter>
		<filter-name>struts-cleanup</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
	</filter>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>

這樣就ok,希望還有更好的解決方法的朋友,發表意見。謝謝