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。

<!-- 用户登录检测过滤器 -->
	<filter>
		<filter-name>LoginCheckFilter</filter-name>
		<filter-class>
			com.tnt.web.filter.LoginCheckFilter
		</filter-class>
		<init-param>
			<param-name>loginPage</param-name>
			<param-value>/logon.jsp</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>LoginCheckFilter</filter-name>
		<url-pattern>/index.jsp</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>LoginCheckFilter</filter-name>
		<url-pattern>/indexadmin.jsp</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>LoginCheckFilter</filter-name>
		<url-pattern>/right.jsp</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>LoginCheckFilter</filter-name>
		<url-pattern>/main/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>LoginCheckFilter</filter-name>
		<url-pattern>/tree/*</url-pattern>
	</filter-mapping>
 

你可能感兴趣的:(filter,web项目)