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

一:需求一

1.需求一

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

2.程序实现

3.程序目录

  

4.User.java

 package com.web;

 import java.util.List;

 public class User {
private String userName;
private List<Authority> authorities;
public void User(){ }
public User(String userName, List<Authority> authorities) {
this.userName = userName;
this.authorities = authorities;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public List<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
} }

5.Authority.java

 package com.web;

 public class Authority {
private String displayName;
private String url;
public void Authority() { }
public Authority(String displayName, String url) {
this.displayName = displayName;
this.url = url;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
} }

6.UserDao.java

 package com.dao;

 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import com.web.Authority;
import com.web.User; public class UserDao {
//初始化
private static Map<String,User> users;
private static List<Authority> authorities=null;
static {
users=new HashMap<String,User>();
authorities=new ArrayList<>(); authorities.add(new Authority("Article-1", "/article-1.jsp"));
authorities.add(new Authority("Article-2", "/article-2.jsp"));
authorities.add(new Authority("Article-3", "/article-3.jsp"));
authorities.add(new Authority("Article-4", "/article-4.jsp")); User user1=new User("AAA", authorities.subList(0, 2));
users.put("AAA", user1); User user2=new User("BBB", authorities.subList(2, 4));
users.put("BBB", user2);
} /**
* 得到用戶User(String,List<Authority>)
* @param userName
* @return
*/
public User get(String userName) {
return users.get(userName);
} /**
* 进行更新用户权限
* 方法是得到用户,然后对这个用户进行赋权限
* @param userName
* @param authorities
*/
public void update(String userName,List<Authority> authorities) {
users.get(userName).setAuthorities(authorities);
} /**
* 获取权限,这个是所有的权限
*/
public List<Authority> getAuthorities(){
return authorities;
} /**
*
* @param authorities2
* @return
*/
public List<Authority> getAuthorities(String[] urls) {
List<Authority> authorities2=new ArrayList<Authority>();
for(Authority authority:authorities) {
if(urls!=null) {
for(String url : urls) {
if(url.equals(authority.getUrl())) {
authorities2.add(authority);
}
}
}
} return authorities2;
} }

7.AuthorityServlet.java

 package com.web;

 import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.dao.UserDao;
public class AuthorityServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String methodName=request.getParameter("method");
try {
Method method=getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
method.invoke(this, request,response);
} catch (Exception e) {
e.printStackTrace();
}
} private UserDao userDao=new UserDao(); public void getAuthorities(HttpServletRequest request, HttpServletResponse response) throws Exception{
String userName=request.getParameter("userName");
User user=userDao.get(userName);
request.setAttribute("user", user);
request.setAttribute("authorities", userDao.getAuthorities());
request.getRequestDispatcher("/authority-manager.jsp").forward(request, response);
}
public void updateAuthorities(HttpServletRequest request, HttpServletResponse response) throws IOException {
String userName=request.getParameter("userName");
String[] authorities=request.getParameterValues("authoritiy");
List<Authority> authoritiesList=userDao.getAuthorities(authorities);
userDao.update(userName, authoritiesList);
response.sendRedirect(request.getContextPath()+"/authority-manager.jsp");
} }

8.authority-manager.jsp

 <%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<br><br>
<form action="AuthorityServlet?method=getAuthorities" method="post">
name:<input type="text" name="userName"/>
<input type="submit" value="Submit"/>
</form> <br><br> <c:if test="${requestScope.user!=null}">
${requestScope.user.userName}的权限是:
<br>
<form action="AuthorityServlet?method=updateAuthorities" method="post">
<input type="hidden" name="userName" value="${requestScope.user.userName}"/>
<c:forEach items="${authorities}" var="auth">
<c:set var="flag" value="false"></c:set>
<c:forEach items="${user.authorities}" var="ua">
<c:if test="${ua.url== auth.url}">
<c:set var="flag" value="true"></c:set>
</c:if>
</c:forEach>
<c:if test="${flag}">
<input type="checkbox" name="authoritiy" value="${auth.url}" checked="checked">${auth.displayName}<br>
</c:if>
<c:if test="${!flag}">
<input type="checkbox" name="authoritiy" value="${auth.url}" >${auth.displayName}<br>
</c:if>
</c:forEach>
<input type="submit" value="Update"/>
</form>
</c:if> </center>
</body>
</html>

9.效果

  

二:需求二

1.需求二

  对访问权限的控制

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

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

  

3.Authority.java

 package com.web;

 public class Authority {
private String displayName;
private String url;
public void Authority() { }
public Authority(String displayName, String url) {
this.displayName = displayName;
this.url = url;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
//用于判断两个权限是否相等
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Authority other = (Authority) obj;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
} }

4.AuthorityFilter.java

 package com.web;

 import java.io.IOException;
import java.util.Arrays;
import java.util.List; 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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet Filter implementation class AuthorityFilter
*/
@WebFilter("*.jsp")
public class AuthorityFilter extends HttpFilter { @Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
String servletPath=request.getServletPath();
List<String> uncheckedUrls=Arrays.asList("/403.jsp","/article.jsp",
"/authority-manager.jsp","/login.jsp","/logout.jsp");
if(uncheckedUrls.contains(servletPath)) {
filterChain.doFilter(request, response);
return;
}
User user=(User) request.getSession().getAttribute("user");
System.out.println("============="+user.getUserName());
if(user==null) {
response.sendRedirect(request.getContextPath()+"/login.jsp");
return;
}
List<Authority> authorities=user.getAuthorities();
Authority authority=new Authority(null, servletPath);
if(authorities.contains(authority)) {
filterChain.doFilter(request, response);
return;
}
response.sendRedirect(request.getContextPath()+"/403.jsp");
} }

5.HttpFilter.java

 package com.web;

 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; /**
* 自定义的 HttpFilter, 实现自 Filter 接口
*
*/
public abstract class HttpFilter implements Filter { /**
* 用于保存 FilterConfig 对象.
*/
private FilterConfig filterConfig; /**
* 不建议子类直接覆盖. 若直接覆盖, 将可能会导致 filterConfig 成员变量初始化失败
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
init();
} /**
* 供子类继承的初始化方法. 可以通过 getFilterConfig() 获取 FilterConfig 对象.
*/
protected void init() {} /**
* 直接返回 init(ServletConfig) 的 FilterConfig 对象
*/
public FilterConfig getFilterConfig() {
return filterConfig;
} /**
* 原生的 doFilter 方法, 在方法内部把 ServletRequest 和 ServletResponse
* 转为了 HttpServletRequest 和 HttpServletResponse, 并调用了
* doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
*
* 若编写 Filter 的过滤方法不建议直接继承该方法. 而建议继承
* doFilter(HttpServletRequest request, HttpServletResponse response,
* FilterChain filterChain) 方法
*/
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp; doFilter(request, response, chain);
} /**
* 抽象方法, 为 Http 请求定制. 必须实现的方法.
* @param request
* @param response
* @param filterChain
* @throws IOException
* @throws ServletException
*/
public abstract void doFilter(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws IOException, ServletException; /**
* 空的 destroy 方法。
*/
@Override
public void destroy() {} }

6.LoginServlet.java

 package com.web;

 import java.io.IOException;
import java.lang.reflect.Method; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.dao.UserDao; /**
* Servlet implementation class LoginServlet
*/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
} protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String methodName=request.getParameter("method");
try {
Method method=getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
method.invoke(this, request,response);
} catch (Exception e) {
e.printStackTrace();
}
} UserDao userDao=new UserDao(); public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
String name=request.getParameter("name");
User user=userDao.get(name);
request.getSession().setAttribute("user", user);
//重定向到article.jsp
response.sendRedirect(request.getContextPath()+"/article.jsp");
}
public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.getSession().invalidate();
response.sendRedirect(request.getContextPath()+"/login.jsp");
} }

7.403.jsp

 <%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h2>没有权限</h2>
<a href="${pageContext.request.contextPath}/article.jsp">返回</a>
</body>
</html>

8.article-1.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>1</h1>
</body>
</html>

9.article.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body> <a href="article-1.jsp"> Article1 page</a><br><br>
<a href="article-2.jsp"> Article2 page</a><br><br>
<a href="article-3.jsp"> Article3 page</a><br><br>
<a href="article-4.jsp"> Article4 page</a><br><br>
<a href="loginServlet?method=logout">Logout</a> </body>
</html>

10.login.jsp\

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="loginServlet?method=login" method="post">
name:<input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>

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

  1. Asp.Net MVC Filter权限过滤使用说明

    相信对权限过滤大家都不陌生,用户要访问一个页面时,先对其权限进行判断并进行相应的处理动作. mvc中是如何实现权限验证的? mvc中是根据路由配置来请求控制器类中的一个方法 在mvc框架中为程序员提供 ...

  2. Asp.Net Core 2.0 项目实战(11) 基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级

    1.权限管理 权限管理的基本定义:百度百科. 基于<Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员.后台管理员同时登录>我们做过了登录认证, ...

  3. net core体系-web应用程序-4asp.net core2.0 项目实战(1)-13基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级

    1.权限管理 权限管理的基本定义:百度百科. 基于<Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员.后台管理员同时登录>我们做过了登录认证, ...

  4. ASP.NET MVC学习---(九)权限过滤机制(完结篇)

    相信对权限过滤大家伙都不陌生 用户要访问一个页面时 先对其权限进行判断并进行相应的处理动作 在webform中 最直接也是最原始的办法就是 在page_load事件中所有代码之前 先执行一个权限判断的 ...

  5. Windows 反调试技术——OpenProcess 权限过滤 - ObRegisterCallback

    转载: https://blog.xpnsec.com/anti-debug-openprocess/ 看雪翻译:https://bbs.pediy.com/thread-223857.htm 本周我 ...

  6. mysql权限过滤

    1.用like做权限过滤 上级部门可以看到下级部门发布的正式文件,下级部门不能看到上级部门发布的正式文件 SELECT*FROM cms_nrgl_st a, mz_xzjg bWHERE a.sys ...

  7. JavaWeb使用Filter进行字符编码过滤 预防web服务中文乱码

    JavaWeb使用Filter进行字符编码过滤 预防web服务中文乱码 准备条件:一个创建好的 JavaWeb 项目 步骤: 1.创建一个类并实现 Filter 接口 import javax.ser ...

  8. Shiro笔记--shiroFilter权限过滤

    1.shiro中shiroFilter中的一些配置页面的过滤权限 <!--名字必须和web.xml里面的filter-name一样--> <bean id="shiroFi ...

  9. .NET MVC5简介(四)Filter和AuthorizeAttribute权限验证

    在webform中,验证的流程大致如下图: 在AOP中: 在Filter中: AuthorizeAttribute权限验证 登录后有权限控制,有的页面是需要用户登录才能访问的,需要在访问页面增加一个验 ...

随机推荐

  1. [JSOI2007]字符加密Cipher

    bzoj 1031:[JSOI2007]字符加密Cipher Time Limit: 10 Sec  Memory Limit: 162 MB Description 喜欢钻研问题的JS同学,最近又迷 ...

  2. .NET 定时器类及使用方法

    Timer类实现定时任务 //2秒后开启该线程,然后每隔4s调用一次 System.Threading.Timer timer = new System.Threading.Timer((n) =&g ...

  3. [整理]C结构实现位段(bit field)

    #include <stdio.h> #include <string.h> typedef struct A{ int a:5; int b:3; unsigned c:8; ...

  4. Ubuntu 13.04 主机名的修改

    由于某些原因,要修改Ubuntu的主机名,晚上Google了一下,要改的地方为/etc/hostname,即将里面的字符串替换为你要起的主机名即可. sudo vi /etc/hostname 修改即 ...

  5. 61.volatile关键字

    volatile作用 volatile的作用是可以保持共享变量的可见性,即一个线程修改一个共享变量后,另一个线程能够读取到这个修改后的值. 先来看一个问题: 定义一个Task类 package com ...

  6. nginx+tomat https ssl 部署 完美解决方案

    关于nginx+tomcat https的部署之前网上一直有2种说法: 1.nginx和tomcat都要部署ssl证书 2.nginx部署ssl证书,tomcat增加ssl支持 在实际的部署过程中ng ...

  7. java 面试算法题

    /** * 设有n个人依围成一圈,从第1个人开始报数,数到第m个人出列,然后从 * 出列的下一个人开始报数,数到第m个人又出列,…,如此反复到所有的人全部出列为 * 止.设n个人的编号分别为1,2,… ...

  8. KL散度(Kullback–Leibler divergence)

    KL散度是度量两个分布之间差异的函数.在各种变分方法中,都有它的身影. 转自:https://zhuanlan.zhihu.com/p/22464760 一维高斯分布的KL散度 多维高斯分布的KL散度 ...

  9. Android Framebuffer介绍及使用【转】

    转自:https://www.jianshu.com/p/df1213e5a0ed 来自: Android技术特工队 作者: Aaron 主页: http://www.wxtlife.com/ 原文连 ...

  10. 从此编写 Bash 脚本不再难【转】

    从此编写 Bash 脚本不再难 原创 Linux技术 2017-05-02 14:30 在这篇文章中,我们会介绍如何通过使用 bash-support vim 插件将 Vim 编辑器安装和配置 为一个 ...