Filter

因为业务需要   往往对过滤器有一定的要求
baidu了下才知道filter和servlet一样 都是部署在web容器上的组件
生命周期:servlet是在请求的时候才初始化的    filter是web容器初始化的就初始化了
2者销毁都是在web容器销毁的时候destory();


	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		// TODO Auto-generated method stub
		log.debug("limitFilter success");
			HttpServletRequest request = (HttpServletRequest) arg0;        
		        HttpServletResponse response = (HttpServletResponse) arg1;        
//		            
		       
		          HttpSession session = request.getSession();      
		         sessionKey=session.getAttribute("skey");
		          System.out.println("sk=  "+sessionKey);
		       if(sessionKey == null){  
		        //  if(1==1){
		        	System.out.println("===");
			        String s= 	request.getContextPath();
			        System.out.println("s  "+s);
			        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+s+"/regist.jsp";
		        	System.out.println("basePath  "+basePath);
		        	//response.sendRedirect("/OnlineC/regist.jsp");
			       	session.setAttribute("skey", "s111");
			     	request.getRequestDispatcher("/regist.jsp").forward(request, response);
			       	
				    System.out.println("后面是return");
			    return ;
		         }    
		         //当有 response.sendRedirect    return可以有   正常显示    return之后是web。xmljinrufilter
		          //
		         
		         System.out.println("-----");
		     arg2.doFilter(arg0, arg1);   
	}



当在doFilter中有重定向或者转发的时候都要return;否则出现异常


而且最后一定要加上FilterChain.doFilter();


web.xml配置filter:
<filter> 
	 	<filter-name>fr</filter-name>
	 	<filter-class>filter.LimitFilter</filter-class>
	 </filter>
	 <filter-mapping>
		 <filter-name>fr</filter-name>
		 <url-pattern>*</url-pattern>
         //这里也可以加上4中过滤方式
		 
	 </filter-mapping>

你可能感兴趣的:(filter)