首页 > 技术文章 > Java使用Filter用户权限控制

lwl80 2020-09-09 15:43 原文

 1 package com.mvc.test;
 2 
 3 import javax.servlet.ServletException;
 4 import javax.servlet.annotation.WebServlet;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.io.IOException;
 9 import java.io.PrintWriter;
10 import java.util.HashSet;
11 import java.util.Set;
12 
13 /**
14  * 用户是否登录,使用全局方法
15  *
16  * @author liuwenlong
17  * @create 2020-09-09 09:23:23
18  */
19 @SuppressWarnings("all")
20 @WebServlet(urlPatterns = "/login")
21 public class Application_Test extends HttpServlet {
22 
23 
24     @Override
25     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
26         resp.setContentType("text/html;charset=UTF-8");
27         PrintWriter out = resp.getWriter();
28         String user = req.getParameter("user");
29         if (user == null) {
30             req.getSession().removeAttribute("islogin");
31             out.print("无效的用户或者密码!");
32             return;
33         }
34 
35         if ("zs".equals(user)) {
36             UserInfo userInfo = new UserInfo(user, "1010", "1", req.getSession().getId());
37             req.getSession().setAttribute("islogin", userInfo);
38             out.print("成功");
39         } else if ("ls".equals(user)) {
40             UserInfo userInfo = new UserInfo(user, "0101", "1" , req.getSession().getId());
41             req.getSession().setAttribute("islogin", userInfo);
42             out.print("成功");
43         } else {
44             out.print("无效用户或者密码");
45         }
46 
47     }
48 
49     //发心跳,接收新的心跳,如果关闭浏览器,就接收不到新的心跳,时间就会超时
50     @Override
51     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
52         resp.setContentType("text/html;charset=UTF-8");
53         PrintWriter out = resp.getWriter();
54         String user = req.getParameter("user");//取出用户
55         String key = "islogin_" + user;//这个用户,然后设置这个用户的时间,重新刷新时间
56         String id = (String) req.getServletContext().getAttribute(key + "id");
57         String id2 = req.getSession().getId();
58 
59         req.getServletContext().setAttribute(key + "_t", System.currentTimeMillis());//记录时间
60         if (id != id2) {
61             req.getSession().setAttribute("islogin", "notlogin");
62             out.print(user + "已经在设备" + id + "登录");
63         } else {
64             out.print("OK");
65         }
66     }
67 }

定义一个Bean

 1 package com.mvc.test;
 2 
 3 /**
 4  * 访问控制 控制权限
 5  *
 6  * @author liuwenlong
 7  * @create 2020-09-09 13:37:37
 8  */
 9 @SuppressWarnings("all")
10 public class UserInfo {
11     private String userid;
12     private String privi;
13     private String heart;
14     private String appid;
15 
16     public UserInfo() {
17     }
18 
19     public UserInfo(String userid, String privi, String heart, String appid) {
20         this.userid = userid;
21         this.privi = privi;
22         this.heart = heart;
23         this.appid = appid;
24     }
25 
26     public String getUserid() {
27         return userid;
28     }
29 
30     public void setUserid(String userid) {
31         this.userid = userid;
32     }
33 
34     public String getPrivi() {
35         return privi;
36     }
37 
38     public void setPrivi(String privi) {
39         this.privi = privi;
40     }
41 
42     public String getHeart() {
43         return heart;
44     }
45 
46     public void setHeart(String heart) {
47         this.heart = heart;
48     }
49 
50     public String getAppid() {
51         return appid;
52     }
53 
54     public void setAppid(String appid) {
55         this.appid = appid;
56     }
57 
58     @Override
59     public String toString() {
60         return "UserInfo{" +
61                 "userid='" + userid + '\'' +
62                 ", privi='" + privi + '\'' +
63                 ", heart='" + heart + '\'' +
64                 ", appid='" + appid + '\'' +
65                 '}';
66     }
67 }

写一个JSP文件,显示

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 <%--权限--%>
 8 ${sessionScope.logininfo}
 9 </body>
10 </html>

 

写一个过滤器

 1 package com.mvc.test;
 2 
 3 import javax.servlet.*;
 4 import javax.servlet.annotation.WebFilter;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 import java.io.IOException;
 8 import java.util.logging.LogRecord;
 9 
10 /**
11  * @author liuwenlong
12  * @create 2020-09-09 13:50:04
13  */
14 @SuppressWarnings("all")
15 //向服务器发起的请求,都要在这里过滤
16 @WebFilter(urlPatterns = "/*")
17 public class MyFilter implements Filter {
18 
19     @Override
20     public void init(FilterConfig filterConfig) throws ServletException {
21 
22     }
23 
24     @Override
25     public void doFilter(ServletRequest request, ServletResponse response, FilterChain Chain) throws IOException, ServletException {
26         HttpServletRequest req = (HttpServletRequest) request;
27         HttpServletResponse resp = (HttpServletResponse) response;
28 
29         req.setCharacterEncoding("utf-8");
30         resp.setCharacterEncoding("utf-8");
31         String sURI = req.getRequestURI();
32         UserInfo userInfo = (UserInfo) req.getSession().getAttribute("islogin");
33         System.out.println(sURI);
34 
35 
36         if (!(sURI.endsWith("login")
37                 || sURI.endsWith("login.jsp")
38                 || sURI.endsWith(".js")
39                 || sURI.endsWith(".css")
40                 || sURI.endsWith(".png")
41         )) {
42             if (userInfo == null) {
43                 req.getSession().setAttribute("error", "pls login");
44                 resp.sendRedirect("login.jsp");
45 //                resp.sendRedirect(req.getContextPath() + "/login.jsp"); //重新定向login.jsp
46                 return;
47             }
48         }
49 
50         //控制器权限
51         //0 [member]0[good]0[order]0[any]
52         String action[] = {"member", "good", "order", "any"};
53 
54         int pos = sURI.lastIndexOf("/");
55         sURI =sURI.substring(pos+1);
56         System.out.println(sURI);
57 
58         if (userInfo != null) {
59             String sPrive = userInfo.getPrivi();//取出权限
60             int i = 0;
61             for (; i < action.length; i++) {
62                 if (sURI.endsWith(action[i])) {
63                     break;
64                 }
65             }
66 
67             if (i < action.length) {
68                 char ch = sPrive.charAt(i);
69                 if (ch == '1') {
70                     req.getSession().setAttribute("logininfo", userInfo.getUserid() + "有"+action[i]+"权限");
71                     resp.sendRedirect("qx.jsp");
72                     return;
73                 } else {
74                     req.getSession().setAttribute("logininfo", userInfo.getUserid() + "没有"+action[i]+"权限");
75                     resp.sendRedirect( "qx.jsp");
76                     return;
77                 }
78             }
79 
80         }
81 
82         Chain.doFilter(request, response);
83     }
84 
85     @Override
86     public void destroy() {
87 
88     }
89 }

测试:先登录zs  ls 

然后每个人访问:member   good  any等 ,出现下列效果

 

推荐阅读