Filter过滤器

今天刚刚学到Filter过滤器,说下今天所学的,什么是过滤器

JavaWeb中的过滤器的概念: 对请求响应进行拦截或者增强的对象,就是过滤器

由于Tomcat服务器的不断更新换代,8之后解决了get里的编码问题,不过post里还是要加一句,这样的:request.setCharacterEncoding("UTF-8");

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        doGet(request, response);
    } 

我说的是如果,如果你的javaweb里只用到一个或两个不相干的过滤器,可以直接用注解代替配置文件web.xml,如果涉及到彼此的那两个过滤器相互有影响了,比如过滤器AuthorityFilter是过滤用户身份的,是管理员或不是管理员,

public class AuthorityFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		System.out.println("---具体权限(xxx管理员)---");
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpSession session = httpRequest.getSession();
		User user = (User)session.getAttribute("user");
		if(user.getFlag() == 1) {	//仓库管理员
			chain.doFilter(request, response);
		} else {	//其他人员
			System.out.println("权限不足...");
			httpRequest.getRequestDispatcher("/index.jsp")
				       .forward(httpRequest, response);
		}
	}

PrivilegeFilter是过滤是否已登录或是未登录又怎么办,也就是我们最开始时候肯定是未登录状态,那么session里一定是空的,

public class PrivilegeFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("-------登录权限判断-------");
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpSession session = httpRequest.getSession();
		if(session.getAttribute("user") == null) {	//未登录
			httpRequest.setAttribute("info", "请先登录.");
			httpRequest.getRequestDispatcher("/login.jsp")
					   .forward(httpRequest, response); 
		} else {	//已登录
			chain.doFilter(request, response);
		}
	}

那么sessionli对象user里也是空的,过滤器AuthorityFilter会影响用户的首次登陆,所以为了避免这样的情况,我们不能再用注解配置了,应该在web.xml里给过滤器配置,并且要注意顺序,因为配置文件xml文件的解析是从上到下的顺序,所以要先放什么,后放什么,例如:



  web1029
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
    encode
    UTF-8
  
  
  	PrivilegeFilter
  	com.igeek.web.filter.PrivilegeFilter
  
   
  	AuthorityFilter
  	com.igeek.web.filter.AuthorityFilter
  
  
  
  	PrivilegeFilter
  	/users/*
  
   
  	AuthorityFilter
  	/users/storage/*
  

 注意先后顺序,还有最后要说的是,servlet里不只能用一个注解配置,可以多个

 

你可能感兴趣的:(JavaEE,Filter,java,web.xml)