Filter的应用--权限过滤

2023-11-04

因为项目比较长,需要一步步进行实现,所以分解成一个一个需求。

 

一:需求一

1.需求一

  可以看某人的权限,同时,可以对这个用户进行权限的修改。

 

2.程序实现

 

3.程序目录

  

 

4.User.java

 1 package com.web;
 2 
 3 import java.util.List;
 4 
 5 public class User {
 6     private String userName;
 7     private List<Authority> authorities;
 8     public void User(){
 9         
10     }
11     public User(String userName, List<Authority> authorities) {
12         this.userName = userName;
13         this.authorities = authorities;
14     }
15     public String getUserName() {
16         return userName;
17     }
18     public void setUserName(String userName) {
19         this.userName = userName;
20     }
21     public List<Authority> getAuthorities() {
22         return authorities;
23     }
24     public void setAuthorities(List<Authority> authorities) {
25         this.authorities = authorities;
26     }
27     
28 }

 

5.Authority.java

 1 package com.web;
 2 
 3 public class Authority {
 4     private String displayName;
 5     private String url;
 6     public void Authority() {
 7         
 8     }
 9     public Authority(String displayName, String url) {
10         this.displayName = displayName;
11         this.url = url;
12     }
13     public String getDisplayName() {
14         return displayName;
15     }
16     public void setDisplayName(String displayName) {
17         this.displayName = displayName;
18     }
19     public String getUrl() {
20         return url;
21     }
22     public void setUrl(String url) {
23         this.url = url;
24     }
25     
26 }

 

6.UserDao.java

 1 package com.dao;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 import com.web.Authority;
 9 import com.web.User;
10 
11 public class UserDao {
12     //初始化
13     private static Map<String,User> users;
14     private static List<Authority> authorities=null;
15     static {
16         users=new HashMap<String,User>();
17         authorities=new ArrayList<>();
18         
19         authorities.add(new Authority("Article-1", "/article-1.jsp"));
20         authorities.add(new Authority("Article-2", "/article-2.jsp"));
21         authorities.add(new Authority("Article-3", "/article-3.jsp"));
22         authorities.add(new Authority("Article-4", "/article-4.jsp"));    
23         
24         User user1=new User("AAA", authorities.subList(0, 2));
25         users.put("AAA", user1);
26     
27         User user2=new User("BBB", authorities.subList(2, 4));
28         users.put("BBB", user2);
29     }
30     
31     /**
32      * 得到用戶User(String,List<Authority>)
33      * @param userName
34      * @return
35      */
36     public User get(String userName) {
37         return users.get(userName);
38     }
39     
40     /**
41      * 进行更新用户权限
42      * 方法是得到用户,然后对这个用户进行赋权限
43      * @param userName
44      * @param authorities
45      */
46     public void update(String userName,List<Authority> authorities) {
47         users.get(userName).setAuthorities(authorities);
48     }
49     
50     /**
51      * 获取权限,这个是所有的权限
52      */
53     public List<Authority> getAuthorities(){
54         return authorities;
55     }
56 
57     /**
58      * 
59      * @param authorities2
60      * @return
61      */
62     public List<Authority> getAuthorities(String[] urls) {
63         List<Authority> authorities2=new ArrayList<Authority>();
64         for(Authority authority:authorities) {
65             if(urls!=null) {
66                 for(String url : urls) {
67                     if(url.equals(authority.getUrl())) {
68                         authorities2.add(authority);
69                     }
70                 }
71             }
72         }
73         
74         
75         return authorities2;
76     }
77     
78 }

 

7.AuthorityServlet.java

 1 package com.web;
 2 
 3 import java.io.IOException;
 4 import java.lang.reflect.InvocationTargetException;
 5 import java.lang.reflect.Method;
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 
 9 import javax.servlet.ServletException;
10 import javax.servlet.annotation.WebServlet;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 
15 import com.dao.UserDao;
16 public class AuthorityServlet extends HttpServlet {
17     private static final long serialVersionUID = 1L;
18 
19     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20         String methodName=request.getParameter("method");
21         try {
22             Method method=getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
23             method.invoke(this, request,response);
24         } catch (Exception e) {
25             e.printStackTrace();
26         }         
27     }
28     
29     private UserDao userDao=new UserDao();
30     
31     public void getAuthorities(HttpServletRequest request, HttpServletResponse response) throws Exception{
32         String userName=request.getParameter("userName");
33         User user=userDao.get(userName);
34         request.setAttribute("user", user);
35         request.setAttribute("authorities", userDao.getAuthorities());
36         request.getRequestDispatcher("/authority-manager.jsp").forward(request, response);
37     }
38     public void updateAuthorities(HttpServletRequest request, HttpServletResponse response) throws IOException {
39         String userName=request.getParameter("userName");
40         String[] authorities=request.getParameterValues("authoritiy");
41         List<Authority> authoritiesList=userDao.getAuthorities(authorities);
42         userDao.update(userName, authoritiesList);
43         response.sendRedirect(request.getContextPath()+"/authority-manager.jsp");
44     }
45 
46 }

 

8.authority-manager.jsp

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 8 <title>Insert title here</title>
 9 </head>
10 <body>
11     <center>
12         <br><br>
13         <form action="AuthorityServlet?method=getAuthorities" method="post">
14             name:<input type="text" name="userName"/>
15             <input type="submit" value="Submit"/>
16         </form>
17         
18         <br><br>
19     
20     <c:if test="${requestScope.user!=null}">
21         ${requestScope.user.userName}的权限是:
22         <br>
23         <form action="AuthorityServlet?method=updateAuthorities" method="post">
24             <input type="hidden" name="userName" value="${requestScope.user.userName}"/>
25             <c:forEach items="${authorities}" var="auth">
26                 <c:set var="flag" value="false"></c:set>
27                 <c:forEach items="${user.authorities}" var="ua">
28                     <c:if test="${ua.url== auth.url}">
29                         <c:set var="flag" value="true"></c:set>
30                     </c:if>        
31                 </c:forEach>
32                 <c:if test="${flag}">
33                     <input type="checkbox" name="authoritiy" value="${auth.url}" checked="checked">${auth.displayName}<br>
34                 </c:if>
35                 <c:if test="${!flag}">
36                     <input type="checkbox" name="authoritiy" value="${auth.url}" >${auth.displayName}<br>
37                 </c:if>
38             </c:forEach>
39             <input type="submit" value="Update"/> 
40         </form>
41     </c:if>
42     
43     </center>
44 </body>
45 </html>

 

9.效果

  

 

二:需求二

1.需求二

  对访问权限的控制

  使用Filter进行权限的过滤,检验用户是否有权限,有,则直接响应目标页面,若没有则重定向到403.jsp

 

2.程序目录(添加主要修改的程序)

  

 

3.Authority.java

 1 package com.web;
 2 
 3 public class Authority {
 4     private String displayName;
 5     private String url;
 6     public void Authority() {
 7         
 8     }
 9     public Authority(String displayName, String url) {
10         this.displayName = displayName;
11         this.url = url;
12     }
13     public String getDisplayName() {
14         return displayName;
15     }
16     public void setDisplayName(String displayName) {
17         this.displayName = displayName;
18     }
19     public String getUrl() {
20         return url;
21     }
22     public void setUrl(String url) {
23         this.url = url;
24     }
25     //用于判断两个权限是否相等
26     @Override
27     public int hashCode() {
28         final int prime = 31;
29         int result = 1;
30         result = prime * result + ((url == null) ? 0 : url.hashCode());
31         return result;
32     }
33     @Override
34     public boolean equals(Object obj) {
35         if (this == obj)
36             return true;
37         if (obj == null)
38             return false;
39         if (getClass() != obj.getClass())
40             return false;
41         Authority other = (Authority) obj;
42         if (url == null) {
43             if (other.url != null)
44                 return false;
45         } else if (!url.equals(other.url))
46             return false;
47         return true;
48     }
49     
50 }

 

4.AuthorityFilter.java

 1 package com.web;
 2 
 3 import java.io.IOException;
 4 import java.util.Arrays;
 5 import java.util.List;
 6 
 7 import javax.servlet.Filter;
 8 import javax.servlet.FilterChain;
 9 import javax.servlet.FilterConfig;
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.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 
17 /**
18  * Servlet Filter implementation class AuthorityFilter
19  */
20 @WebFilter("*.jsp")
21 public class AuthorityFilter extends HttpFilter {
22 
23     @Override
24     public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
25             throws IOException, ServletException {
26         String servletPath=request.getServletPath();
27         List<String> uncheckedUrls=Arrays.asList("/403.jsp","/article.jsp",
28                 "/authority-manager.jsp","/login.jsp","/logout.jsp");
29         if(uncheckedUrls.contains(servletPath)) {
30             filterChain.doFilter(request, response);
31             return;
32         }
33         User user=(User) request.getSession().getAttribute("user");
34         System.out.println("============="+user.getUserName());
35         if(user==null) {
36             response.sendRedirect(request.getContextPath()+"/login.jsp");
37             return;
38         }
39         List<Authority> authorities=user.getAuthorities();
40         Authority authority=new Authority(null, servletPath);
41         if(authorities.contains(authority)) {
42             filterChain.doFilter(request, response);
43             return;
44         }
45         response.sendRedirect(request.getContextPath()+"/403.jsp");
46     }
47 
48    
49 }

 

5.HttpFilter.java

 1 package com.web;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 
14 /**
15  * 自定义的 HttpFilter, 实现自 Filter 接口
16  *
17  */
18 public abstract class HttpFilter implements Filter {
19 
20     /**
21      * 用于保存 FilterConfig 对象. 
22      */
23     private FilterConfig filterConfig;
24     
25     /**
26      * 不建议子类直接覆盖. 若直接覆盖, 将可能会导致 filterConfig 成员变量初始化失败
27      */
28     @Override
29     public void init(FilterConfig filterConfig) throws ServletException {
30         this.filterConfig = filterConfig;
31         init();
32     }
33 
34     /**
35      * 供子类继承的初始化方法. 可以通过 getFilterConfig() 获取 FilterConfig 对象. 
36      */
37     protected void init() {}
38 
39     /**
40      * 直接返回 init(ServletConfig) 的 FilterConfig 对象
41      */
42     public FilterConfig getFilterConfig() {
43         return filterConfig;
44     }
45     
46     /**
47      * 原生的 doFilter 方法, 在方法内部把 ServletRequest 和 ServletResponse 
48      * 转为了 HttpServletRequest 和 HttpServletResponse, 并调用了 
49      * doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
50      * 
51      * 若编写 Filter 的过滤方法不建议直接继承该方法. 而建议继承
52      * doFilter(HttpServletRequest request, HttpServletResponse response, 
53      *        FilterChain filterChain) 方法
54      */
55     @Override
56     public void doFilter(ServletRequest req, ServletResponse resp,
57             FilterChain chain) throws IOException, ServletException {
58         HttpServletRequest request = (HttpServletRequest) req;
59         HttpServletResponse response = (HttpServletResponse) resp;
60         
61         doFilter(request, response, chain);
62     }
63     
64     /**
65      * 抽象方法, 为 Http 请求定制. 必须实现的方法. 
66      * @param request
67      * @param response
68      * @param filterChain
69      * @throws IOException
70      * @throws ServletException
71      */
72     public abstract void doFilter(HttpServletRequest request, HttpServletResponse response, 
73             FilterChain filterChain) throws IOException, ServletException;
74 
75     /**
76      * 空的 destroy 方法。 
77      */
78     @Override
79     public void destroy() {}
80 
81 }

 

6.LoginServlet.java

 1 package com.web;
 2 
 3 import java.io.IOException;
 4 import java.lang.reflect.Method;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 import com.dao.UserDao;
13 
14 /**
15  * Servlet implementation class LoginServlet
16  */
17 @WebServlet("/loginServlet")
18 public class LoginServlet extends HttpServlet {
19     private static final long serialVersionUID = 1L;
20     
21     protected void doGet(HttpServletRequest request, HttpServletResponse response) 
22             throws ServletException, IOException {
23         doPost(request,response);
24     }
25     
26     protected void doPost(HttpServletRequest request, HttpServletResponse response) 
27             throws ServletException, IOException {
28         String methodName=request.getParameter("method");
29         try {
30             Method method=getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
31             method.invoke(this, request,response);
32         } catch (Exception e) {
33             e.printStackTrace();
34         } 
35     }
36     
37     UserDao userDao=new UserDao();
38     
39     public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
40         String name=request.getParameter("name");
41         User user=userDao.get(name);
42         request.getSession().setAttribute("user", user);
43         //重定向到article.jsp
44         response.sendRedirect(request.getContextPath()+"/article.jsp");
45     }
46     public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
47         request.getSession().invalidate();
48         response.sendRedirect(request.getContextPath()+"/login.jsp");
49     }
50 
51 }

 

7.403.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     <h2>没有权限</h2>
11     <a href="${pageContext.request.contextPath}/article.jsp">返回</a>
12 </body>
13 </html>

 

8.article-1.jsp

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="ISO-8859-1"%>
 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=ISO-8859-1">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <h1>1</h1>
11 </body>
12 </html>

 

9.article.jsp

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="ISO-8859-1"%>
 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=ISO-8859-1">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 
11     <a href="article-1.jsp"> Article1 page</a><br><br>
12     <a href="article-2.jsp"> Article2 page</a><br><br>
13     <a href="article-3.jsp"> Article3 page</a><br><br>
14     <a href="article-4.jsp"> Article4 page</a><br><br>
15     <a href="loginServlet?method=logout">Logout</a>
16     
17 </body>
18 </html>

 

10.login.jsp\

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 2     pageEncoding="ISO-8859-1"%>
 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=ISO-8859-1">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form action="loginServlet?method=login" method="post">
11         name:<input type="text" name="name">
12         <input type="submit" value="Submit">
13     </form>
14 </body>
15 </html>

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Filter的应用--权限过滤 的相关文章

随机推荐

  • 2021 10-24

    let person name 张三 age 23 let p new Proxy person set target prpoName value Reflect set target prpoName value get target
  • 在物联网中应用机器学习

    欢迎大家前往腾讯云 社区 获取更多腾讯海量技术实践干货哦 本文由未来守护者发表于云 社区专栏 本项目探讨如何将机器学习 Machine learning 应用到物联网 IoT Internet of Things 中 我们将使用 Andro
  • 如何在windows下使用vscode畅快的调试bash shell

    前言 在linux随然有很多的可以调试的bash的工具 但是如果不用ubuntu或者其它linux系的桌面系统 只有命令行的情况下 还是很吃力的 当然了 大神级别可以畅快的书写并调试 但是对于我等小白 空格多一个少一个 只能望尘莫及了 所以
  • Python 安装dlib解决办法

    pypi python org pypi dlib 19 6 0 下载 dlib 19 6 0 cp36 cp36m win amd64 whl 成功安装 dlib 但是import 时候失败 尝试 pip install dlib 19
  • matlab实现神经网络算法,人工神经网络matlab代码

    求一段神经网络MATLAB代码 50 function presim ss net simnonlin y d n y 时间序列数据 列向量 d 时间延迟参数 正整数 n 用于训练的点的个数 正整数trainset gettrain y d
  • 新手学习python语言基础知识第四天

    语言基础 day4 循环 01 for循环 循环 让代码重复执行 代码写一遍 运行的时候可以执行多次 1 for循环 for循环如图 语法 for 变量 in 序列 循环体 说明 for in 关键字 固定写法 变量 写一个变量名 可以是已
  • JAVA ~ FFmpegFrameRecorder用H264编码封装mp4 有声音无图像

    1问题描述 最近公司做的关于摄像机录制视频保存的问题 发送录制了视频上传至服务器中在浏览器上播放有声音无图像 因为自己是这方面的小白 在自己也在前面博客中也分享了rtsp流媒体如何播放及在H5中嵌入vlc 帧抓取图片及录制视频等文章 希望对
  • 使用ai实现后端端口的调用

    一 创建flask框架 1 创建框架提示词 我需要一个flask框架的demo 把端口号改为8080 需要热加载功能 支持在线更改 请给我代码 导入一些依赖库 from flask import Flask render template
  • 视频播放设计测试用例

    功能测试 1 视频资源能否正常获取 无论从服务器后台或者客户端添加 播放是否正常 2 存在多个视频时 能否上下滑动 无论看完未看完 3 如果一个视频涉及另外一个 切换到相应视频能否正常播放 4 视频音量测试 在无声音播放是否 正常声音是否正
  • vue项目 代码中代理 部署后nginx请求代理

    vue项目 代码中代理 vue2 0 文件地址 config index js module exports dev Paths assetsSubDirectory static assetsPublicPath proxyTable 设
  • 金融时间序列分析:Python基于garch模型预测上证指数波动率、计算var和var穿透率、双尾检验

    目录 一 收益率波动效应的分析 1 1 收益率序列平稳性检验 1 2 建立AR p 模型 1 3 Ljung Box混成检验残差序列的相关性 判断是否有ARCH效应 1 4 建立ARCH模型 二 GARCH模型与波动率预测 2 1 建立GA
  • 后端Springboot框架搭建APi接口开发(第一章)

    本文章以IDEA为开发工具 使用SSM框架进行项目编写 第一节 设计并创建数据库 我们用一个简单的用户表进行操作演示 首先创建Data数据库 create database data 创建User数据表 表中包含用户邮箱 用户姓名 用户密码
  • C++ placement new使用

    placement new重载来原来的operator new 且placement new不能被即需重载 placement new是在原有的一块地址上继续创建一个对象 注意对象类型要一致 这样的操作的优势有两个 1 不用花时间在找合适的
  • Anchor DETR

    Anchor DETR Query Design for Transformer Based Detector 2021 9 1 DETR的object query是学习的 没有物理意义也不能解释每个query注意哪 作者认为学习出来的ob
  • 用十条命令在一分钟内检查Linux服务器性能[转]

    概述 通过执行以下命令 可以在1分钟内对系统资源使用情况有个大致的了解 uptime dmesg tail vmstat 1 mpstat P ALL 1 pidstat 1 iostat xz 1 free m sar n DEV 1 s
  • 关于C++中的随机数生成器

    关于C 中的随机数生成器 今天需要生成随机序列来测试代码 记录一下C 中随机数生成器的使用方法 C 中使用random库生成随机数 主要使用两个类 随机数引擎类 调用这个类会生成一个调用运算符 该运算符不接受任何参数 并返回一个随机的uns
  • 你知道两台Linux之间如何传输文件吗?

    你知道两台Linux之间如何传输文件吗 不同的Linux主机之间想要实现文件相互拷贝的方法有三种 第一种 ftp 也就是其中一台Linux安装ftpServer 这样可以另外一台使用ftp的client程序来进行文件的copy 第二种 采用
  • 转载:Java学习路线(完整详细版)超详细

    Java学习路线 第一阶段 Java基础 一 介绍 二 Java开发介绍 三 Java数组 四 Java面向对象 五 异常 六 集合 七 IO流 八 多线程 第二阶段 JavaWeb 一 介绍 二 HTML5 三 CSS3 四 JavaSc
  • 用Java写数据到POST请求

    用Java写数据到POST请求 HTTP POST请求最常见的用途是发送表单参数到服务器 除了发送表单数据 还可以使用POST的消息Body体发送各种数据 如纯文本 XML文档等 本文讲述如何用Java将数据写入POST请求的Body体 j
  • Filter的应用--权限过滤

    因为项目比较长 需要一步步进行实现 所以分解成一个一个需求 一 需求一 1 需求一 可以看某人的权限 同时 可以对这个用户进行权限的修改 2 程序实现 3 程序目录 4 User java 1 package com web 2 3 imp