jun - 云代码空间
—— 相信 ,梦
package cn.itcast.web.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 cn.itcast.domain.User; //权限过滤器---没有配置文件 public class _PrivilegeFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // 1.将请求与响应对象强制转换成http协议下的 HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; response.setContentType("text/html;charset=utf-8"); // 2.完成操作--通过user的role来判断当前资源是否可以访问(url极另的权限控制) // 2.1 得到访问的资源路径,判断它是否需要权限控制 String uri = request.getRequestURI(); String contextpath = request.getContextPath(); String path = uri.substring(contextpath.length()); // 这些路径是需要权限控制的 if (path.equals("/bookselect") || path.equals("/bookinsert") || path.equals("/bookupdate") || path.equals("/bookdelete")) { // 2.2 得到当前登录用户 User user = (User) request.getSession().getAttribute("user"); if (user != null) { // 登录 // 2.3得到当前用户的role String role = user.getRole(); if ("admin".equals(role)) { if (path.equals("/bookinsert") || path.equals("/bookupdate") || path.equals("/bookdelete")) { // 说明当前要访问的资源,当前admin角色可以访问 chain.doFilter(request, response); return; } else { throw new RuntimeException("权限不足"); } } else { // 这是user角色 if (path.equals("/bookselect")) { chain.doFilter(request, response); return; } else { throw new RuntimeException("权限不足"); } } } else { // 没有登录 response.getWriter().write( "请<a href='" + request.getContextPath() + "/demo1/login.jsp'>登录</a>"); return; } } else { chain.doFilter(request, response); return; } // 3.放行 // chain.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException { } }