Filter(权限验证)

package com.xxx.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.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
 * 验证用户是否登录,没有登录跳转到登录页面,登录了就放行
 * 
 */
@WebFilter(
		filterName="auth",
		urlPatterns="/*",
		initParams={
				@WebInitParam(name="encoding",value="GBK"),
				@WebInitParam(name="loginPage",value="/login.jsp"),
				@WebInitParam(name="proLogin",value="/proLogin.jsp")
		})
public class AuthFilter implements Filter {
	
	private FilterConfig config;

	//初始化Filter作的事情
	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config=config;
	}
	
	//销毁Filter前作的事情
	//释放资源
	@Override
	public void destroy() {
		this.config=null;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//获取该Filter的配置参数
		String encoding=this.config.getInitParameter("encoding");
		String loginPage=this.config.getInitParameter("loginPage");
		String proLogin=this.config.getInitParameter("proLogin");
		//设置request编码用的字符集
		request.setCharacterEncoding(encoding);
		HttpServletRequest hrequest=(HttpServletRequest) request;
		HttpSession session=hrequest.getSession();
		//获取客户请求的页面
		String requestPath=hrequest.getServletPath();
		//如果session范围的user为null,表示没有登录
		//且用户请求的既不是登录页面,也不是登录处理页面
		if(session.getAttribute("user")==null && !requestPath.endsWith(loginPage) && !requestPath.endsWith(proLogin)){
			//forward到登录页面
			request.setAttribute("tip", "您还没有登录");
			request.getRequestDispatcher(loginPage).forward(request, response);
			
		}else{
			//放行请求
			chain.doFilter(request, response);
		}
	}



}


通过web.xml配置

 
  	auth
  	com.xxx.filter.AuthFilter
  	
  		encoding
  		GBK
  	
  	  	
  		loginPage
  		/login.jsp
  	
  	  	
  		proLogin
  		/proLogin.jsp
  	
  
  
  	auth
  	/*
  









你可能感兴趣的:(Filter(权限验证))