java采用Filter实现用户未登陆不能访问系统资源

1 Filter:
import java.io.IOException;

package com.accp.filter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
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;

import org.apache.log4j.Logger;

public class AuthFilter extends HttpServlet implements Filter {

	private static Logger logger = Logger.getLogger(AuthFilter.class.getName());
	private static final long serialVersionUID = 1L;

	public void doFilter(ServletRequest srequest, ServletResponse sresponse,
			FilterChain filterchain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) srequest;
		HttpServletResponse response = (HttpServletResponse) sresponse;
		HttpSession session = request.getSession();
		String url = request.getRequestURI();
		url = url.substring(url.lastIndexOf("/") + 1, url.length());
		/*
		* 1:login!doLogin.shtml表示用户登录action
		* 2:index.jsp(说明:在我的系统中index.jsp动态切换login.jsp或者系统组件下载download.jsp)		
		* 3:error.jsp表示出错后进入index.jsp
		* 4:login.jsp表示用户登录界面
		*/
		if (!url.equals("login!doLogin.shtml") && !url.equals("index.jsp") && !url.equals("error.jsp") 
			&& !url.equals("login.jsp") && !url.equals("download.jsp") && !url.equals("downloadfile!downloadFile.shtml")) {
			if (session == null || session.getAttribute("user") == null) {
				logger.info(this.getClass().getName() + " method doFilter() -->>> session过期!");
				response.sendRedirect(request.getContextPath() + "/error.jsp");
			} else {
				filterchain.doFilter(srequest, sresponse);
			}
		} else
			filterchain.doFilter(srequest, sresponse);

	}

	public void init(FilterConfig arg0) throws ServletException {
	
	}

	public void destroy() {
	}
2 xml:
<filter>
	<filter-name>authFilter</filter-name>
	<filter-class>com.accp.filter.AuthFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>authFilter</filter-name>
	<url-pattern>*.action</url-pattern>
	<url-pattern>*.jsp</url-pattern>
	<url-pattern>*.do</url-pattern>
	<url-pattern>*.shtml</url-pattern>
</filter-mapping>

说明:*.action、*.jsp、*.do、*.shtml为我的系统中所过滤的。

你可能感兴趣的:(java,jsp,session,filter)