Filter应用二简单的权限管理

Filter应用二简单的权限管理

  • 黑名单方式

记录哪些用户不能够访问那些网页

  • 白名单方式

记录那些用户能够访问哪些网页

案例介绍

采用黑名单方式:p1.jsp,p2.jsp,p3.jsp等三个页面,haha不能访问p1.jsp;xixi不能访问p2.jsp
没有登陆的用户,不能访问p1,p2,p3等页面
紧跟Filter应用一的代码来制作简单的权限管理

  • 在根目录下添加page包,并在包下创建p1,p2,p3等三个jsp页面,联系整体组织架构如下:

  • 添加登陆页面

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>登陆页面</title>
 8 </head>
 9 <body>
10       登陆页面<br><br>
11      <div id="info"></div>
12      <form action="CheckLogin" method="post">
13      <input type="hidden" name="status" value="0"/>
14      姓&nbsp;名:<input type="text" name="userName"/><br>
15      密&nbsp;码:<input type="password" name="pwd"/><br>
16      <input type="submit" id="sub" value="提交"/>
17      </form>
18      <br><br>
19      <a href="register.jsp">注册页面</a>
20      <a href="login.jsp">登陆页面</a>
21 </body>
22 </html>
  • 在监听器服务器启动时添加一个HashMap用来存储黑名单的信息,并将信息存放在application当中,取名right

 1 package com.wy.listener;
 2 
 3 import java.util.HashMap;
 4 import javax.servlet.ServletContextEvent;
 5 import javax.servlet.ServletContextListener;
 6 import javax.servlet.annotation.WebListener;
 7 
 8 /**
 9  * Application Lifecycle Listener implementation class FilterListener
10  *
11  */
12 @WebListener
13 public class FilterListener implements ServletContextListener {
14 
15     /**
16      * Default constructor. 
17      */
18     public FilterListener() {
19         // TODO Auto-generated constructor stub
20     }
21 
22     /**
23      * @see ServletContextListener#contextDestroyed(ServletContextEvent)
24      */
25     public void contextDestroyed(ServletContextEvent arg0)  { 
26          // TODO Auto-generated method stub
27     }
28 
29     /**
30      * @see ServletContextListener#contextInitialized(ServletContextEvent)
31      */
32     public void contextInitialized(ServletContextEvent arg0)  { 
33          // TODO Auto-generated method stub
34         HashMap<String, String> map=new HashMap<String,String>();
35         map.put("haha", "123456");
36         map.put("xixi", "123456");
37         map.put("youyou", "123456");
38         //将信息存放在application中
39         arg0.getServletContext().setAttribute("USERS", map);
40         
41         /**
42          * 在做一个HashMap来存储黑名单内容
43          * */
44         HashMap<String, String> mapRight=new HashMap<String,String>();
45         mapRight.put("haha", "p1.jsp");
46         mapRight.put("xixi", "p2.jsp");
47         arg0.getServletContext().setAttribute("RIGHTS", mapRight);
48     }
49 }
  • 监听器处理完成之后,再做登陆处理,创建CheckLogin的servlet进行登陆判定以及登陆成功之后的跳转

 1 package com.wy.servlet;
 2 
 3 import java.io.IOException;
 4 import java.util.HashMap;
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 /**
12  * Servlet implementation class CheckLogin
13  */
14 @WebServlet("/CheckLogin")
15 public class CheckLogin extends HttpServlet {
16     private static final long serialVersionUID = 1L;
17        
18     /**
19      * @see HttpServlet#HttpServlet()
20      */
21     public CheckLogin() {
22         super();
23         // TODO Auto-generated constructor stub
24     }
25 
26     /**
27      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
28      */
29     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
30         /**
31          * 获取到页面提交的用户名以及密码
32          * 1.获取到存储的账户信息
33          * 2.如果用户名在这个表中存在,那么如果网页得到的密码与存在用户的密码一致,
34          * 则跳转到主页面,否则还跳回登陆页面
35          */
36         String name=request.getParameter("userName");
37         String pwd=request.getParameter("pwd");
38         @SuppressWarnings("unchecked")
39         HashMap<String, String> map=(HashMap<String, String>) 
40                 request.getServletContext().getAttribute("USERS");
41         if(map.containsKey(name)){
42             String mpwd=map.get(name).toString();
43             if(mpwd.equals(pwd)){
44                 //将当前用户名存储到session中
45                 request.getSession().setAttribute("NAME", name);
46                 response.sendRedirect("main.jsp");
47                 return;
48             }
49         }
50         response.sendRedirect("login.jsp");
51     }
52 
53     /**
54      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
55      */
56     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
57         // TODO Auto-generated method stub
58         doGet(request, response);
59     }
60 }

上述代码主要进行的是登陆判定,页面接收到的用户信息与存储在HashMap中的信息做出对比,并将当前登陆的信息存储在session当中,便于后面进行访问控制权限与当前用户信息与黑名单信息比较判定

  • 创建error.jsp页面用于没有权限或者没有登陆访问提示跳转

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 <%=request.getAttribute("info") %>
11 </body>
12 </html>
  • 创建过滤器(WebRightFilter)来处理访问权限的问题

  1 package com.wy.filter;
  2 
  3 import java.io.IOException;
  4 import java.util.HashMap;
  5 import javax.servlet.DispatcherType;
  6 import javax.servlet.Filter;
  7 import javax.servlet.FilterChain;
  8 import javax.servlet.FilterConfig;
  9 import javax.servlet.RequestDispatcher;
 10 import javax.servlet.ServletException;
 11 import javax.servlet.ServletRequest;
 12 import javax.servlet.ServletResponse;
 13 import javax.servlet.annotation.WebFilter;
 14 import javax.servlet.http.HttpServlet;
 15 import javax.servlet.http.HttpServletRequest;
 16 import javax.servlet.http.HttpServletResponse;
 17 
 18 /**
 19  * Servlet Filter implementation class WebRightFilter
 20  */
 21 @WebFilter(dispatcherTypes = {
 22                 DispatcherType.REQUEST, 
 23                 DispatcherType.FORWARD, 
 24                 DispatcherType.INCLUDE, 
 25                 DispatcherType.ERROR
 26         }
 27                     , urlPatterns = { "/page/*" })
 28 public class WebRightFilter implements Filter {
 29 
 30     /**
 31      * Default constructor. 
 32      */
 33     public WebRightFilter() {
 34         // TODO Auto-generated constructor stub
 35     }
 36 
 37     /**
 38      * @see Filter#destroy()
 39      */
 40     public void destroy() {
 41         // TODO Auto-generated method stub
 42     }
 43 
 44     /**
 45      * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 46      */
 47     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
 48             throws IOException, ServletException {
 49         // TODO Auto-generated method stub
 50         // place your code here
 51         /**
 52          * 转换request和response成httpservletrequest(response)
 53          */
 54         HttpServletRequest req=(HttpServletRequest) request;
 55         HttpServletResponse res=(HttpServletResponse) response;
 56         
 57         RequestDispatcher rd=req.getRequestDispatcher("/error.jsp");
 58         /**
 59          * 处理未登录状态的情况
 60          * 从session当中去除存储的当前账号信息,看看是否已经登陆
 61          * 本来的跳转方式:res.sendRedirect("error.jsp");
 62          * 另外一种页面跳转方式:RequestDispatcher rd=request.getRequestDispatcher("error.jsp");
 63          * 区别在于第二种方式可以携带错误信息
 64          */
 65         String url=req.getRequestURI().toString();
 66         if(req.getSession().getAttribute("NAME")==null){
 67             
 68             //设置报错信息info
 69             req.setAttribute("info", "未登录状态,不能访问["+url+"]!!!");
 70             rd.forward(req, res);
 71             return;
 72         }
 73         /**
 74          * 处理登陆之后能访问以及不能访问的网页示例
 75          * session中只有用户自己看到
 76          * application中所有用户都可看到
 77          */
 78         //得到当前登陆的用户名信息
 79         String name=req.getSession().getAttribute("NAME").toString();
 80         @SuppressWarnings("unchecked")
 81         //从application中获取到application中的存储信息
 82         HashMap<String, String> map=(HashMap<String, String>) 
 83                 req.getServletContext().getAttribute("RIGHTS");
 84         /**
 85          * 判断如果黑名单中有存储的账号信息就要去判断哪些网页他可以访问,哪些不能访问
 86          */
 87         if(map.containsKey(name)){
 88             //通过名字得到当前用户访问的url
 89             String murl=map.get(name);
 90             if(url.endsWith(murl)){
 91                 req.setAttribute("info", "没有权限不能访问["+url+"]!!!");
 92                 rd.forward(req, res);
 93                 return;
 94             }
 95         }
 96         // pass the request along the filter chain
 97         chain.doFilter(request, response);
 98     }
 99 
100     /**
101      * @see Filter#init(FilterConfig)
102      */
103     public void init(FilterConfig fConfig) throws ServletException {
104         // TODO Auto-generated method stub
105     }
106 }

通过session当中保存的用户信息进行判定,查看用户是否有权限访问全部页面信息,主要逻辑通过HashMap中保存黑名单信息与保存在session当中当前登陆用户名是否一致来进行判定,application中存储的用户不能访问的url与当前用户正在访问的url是否一致,若一致则跳转到error页面,提示没有权限访问,否则直接进入该页面即可

  • 主界面(main.jsp)的更新代码内容

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>主页面</title>
 8 </head>
 9 <body>
10 恭喜<%=request.getSession().getAttribute("NAME") %>,登陆成功,进入主界面<br>
11    <a href="page/p1.jsp">p1</a>
12    <a href="page/p2.jsp">p2</a>
13    <a href="page/p3.jsp">p3</a>
14 </body>
15 </html>
原文地址:https://www.cnblogs.com/sinon/p/6674515.html