1. 程式人生 > >過濾器應用(四)之許可權過濾器

過濾器應用(四)之許可權過濾器

package com.jjyy.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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itheima.domain.User;

public class PrivilegeFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		//獲取訪問的資源uri
		String uri = req.getRequestURI().substring(req.getContextPath().length());
		
		//檢查訪問的資源是否是以/admin或/user開頭,如果是則表明需要許可權
		if(uri.startsWith("/admin") || uri.startsWith("/user")){
			//如果使用者沒有登入,則提示使用者先進行登入操作
			if(req.getSession(false)==null || req.getSession().getAttribute("user")==null){
				resp.getWriter().write("該資源需要許可權,請先進行登入!!");
				resp.setHeader("Refresh", "3;url="+req.getContextPath()+"/login.jsp");
				return;
			}else{//如果使用者已經登入
				User user = (User) req.getSession().getAttribute("user");
				if(uri.startsWith("/admin") && "admin".equals(user.getRole())){
					//如果當前資源需要admin許可權而當前使用者是admin則放行
					chain.doFilter(request, response);
				}else if(uri.startsWith("/user") && "user".equals(user.getRole())){
					//如果當前資源需要user許可權而當前使用者是user則放行
					chain.doFilter(request, response);
				}else{
					//如果上面兩個都不符合提示使用者許可權不足
					throw new RuntimeException("您不具有對應的許可權!!!!");
				}
			}
		}else{//如果不是則不需要許可權,直接放行
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

}