一个登陆验证的过滤器

 
  
 import javax.servlet.Filter; 
 import javax.servlet.FilterConfig; 
 import javax.servlet.ServletException; 
 import javax.servlet.ServletRequest; 
 import javax.servlet.ServletResponse; 
 import javax.servlet.FilterChain; 
 import java.io.IOException; 
 import javax.servlet.http.HttpServletRequest; 
 import javax.servlet.http.HttpServletResponse; 
 import javax.servlet.http.HttpSession; 
 import org.apache.log4j.Logger; 
  
 import com.gvninc.utils.StringUtils; 
  
 /** 
  * 登录验证过滤器 <br> 
  * Author:BluesLee <br> 
  * CreateDate:2008-6-21 <br> 
  * Modifier:BluesLee <br> 
  * ModifyDate:2008-6-21 <br> 
  * Version:1.0 <br> 
  * Copyright(c)2008 深蓝工作室 <br> 
  * All right reserved. <br> 
  * 
  */ 
 public class LoginRightFilter implements Filter { 
 	private Logger logger = Logger.getLogger(this.getClass()); 
  
 	/** 
 	 * 未登陆时跳转目标页面 
 	 */ 
 	private static String FORWARD = "/login.jsp"; 
 	/** 
 	 * 登录验证过滤器初始化  <br> 
 	 * Author:BluesLee <br> 
 	 * CreateDate:2008-6-21 <br> 
 	 * Modifier:BluesLee <br> 
 	 * ModifyDate:2008-6-21 <br> 
 	 * Version:1.0 <br> 
 	 * 
 	 * @param filterConfig 
 	 * @throws ServletException 
 	 */ 
 	public void init(FilterConfig filterConfig) throws ServletException { 
 		String forward = filterConfig.getInitParameter("forward"); 
 		StringUtils util=new StringUtils(); 
 		if (util.isNotNullStr(forward)) { 
 			LoginRightFilter.FORWARD = forward; 
 		} 
 	} 
  
 	/** 
 	 * 登录验证过滤  <br> 
 	 * Author:BluesLee <br> 
 	 * CreateDate:2008-6-21 <br> 
 	 * Modifier:BluesLee <br> 
 	 * ModifyDate:2008-6-21 <br> 
 	 * Version:1.0 <br> 
 	 * 
 	 * @param servletRequest 
 	 * @param servletResponse 
 	 * @param filterChain 
 	 * @throws IOException 
 	 * @throws ServletException 
 	 */ 
 	public void doFilter(ServletRequest servletRequest, 
 			ServletResponse servletResponse, FilterChain filterChain) 
 			throws IOException, ServletException { 
 		HttpServletRequest request = (HttpServletRequest) servletRequest; 
 		HttpServletResponse response = (HttpServletResponse) servletResponse; 
 		HttpSession session = request.getSession(true); 
  
 		Object user = session.getAttribute("user"); 
  
 		if (user != null) { 
 			filterChain.doFilter(servletRequest, servletResponse); 
 		} else { 
 			logger.warn("用户未登陆,请先登陆!"); 
 			String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() + request.getContextPath() + LoginRightFilter.FORWARD; 
 			StringBuffer scriptString=new StringBuffer(); 
 			scriptString.append(" <script>\n\r"); 
 			scriptString.append("self.top.location.href=\""+url+"\"\n\r"); 
 			scriptString.append(" </script>\n\r"); 
 			response.getOutputStream().print(scriptString.toString()); 
 		} 
 	} 
 	public void destroy() { 
 	} 
 } 
  
 

你可能感兴趣的:(过滤器)