web项目用户登录验证filter

package com.tnt.web.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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class LoginCheckFilter implements Filter {
	//protected Log log = LogFactory.getLog(getClass());

	/**
	 * 登陆页面
	 */
	private String loginPage = "";

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpSession session = httpServletRequest.getSession();
		if (session == null || session.getAttribute("user") == null) {
			HttpServletResponse httpServletResponse = (HttpServletResponse) response;
			httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + loginPage);
//			httpServletRequest.getRequestDispatcher(loginPage).forward(httpServletRequest, httpServletResponse);
		} else {
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.loginPage = filterConfig.getInitParameter("loginPage");
	}

	public void destroy() {

	}
}
这是filter类。

在web.xml中配置filter。


	
		LoginCheckFilter
		
			com.tnt.web.filter.LoginCheckFilter
		
		
			loginPage
			/logon.jsp
		
	
	
		LoginCheckFilter
		/index.jsp
	
	
		LoginCheckFilter
		/indexadmin.jsp
	
	
		LoginCheckFilter
		/right.jsp
	
	
		LoginCheckFilter
		/main/*
	
	
		LoginCheckFilter
		/tree/*
	
 

你可能感兴趣的:(java编程)