SpringMVC过滤器:登录过滤

直接贴代码

package com.scau.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.scau.model.Farmer;

/**
 * 果农登录检测Filter
 * @author CSH
 *
 */
public class FarmerFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
		String[] doNotFilterUrls = {"/farmer/", "/farmer/login", "/farmer/index", "/farmer/logout"};
		String url = request.getRequestURI();
		
		//默认需要doFilter
		boolean doFilter = true;
		
		for (String u : doNotFilterUrls){
			if(url.equals(u)){
				doFilter = false;
				break;
			}
		}
		
		//需要doFilter
		if (doFilter){
			Farmer farmer = (Farmer) request.getSession().getAttribute("farmer");
			if (farmer == null){
				response.getWriter().println("<script>");  
		                response.getWriter().println("self.top.location.href='/farmer/login'");
		                response.getWriter().println("alert('页面已过期,请重新登录');");
		                response.getWriter().println("</script>");  
				return ;
			} else {
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}
	}

}

web.xml

  <!-- 果农的登录检测 -->
  <filter>
  	<filter-name>FarmerFilter</filter-name>
  	<filter-class>com.scau.filter.FarmerFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>FarmerFilter</filter-name>
  	<url-pattern>/farmer/*</url-pattern>
  </filter-mapping>


你可能感兴趣的:(java,springMVC,filter,登录检测)