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

一:需求一

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. Git记录-Git版本控制介绍

    git config命令用于获取并设置存储库或全局选项.这些变量可以控制Git的外观和操作的各个方面. 如果在使用Git时需要帮助,有三种方法可以获得任何git命令的手册页(manpage)帮助信息: ...

  2. Machine Learning Trick of the Day (2): Gaussian Integral Trick

    Machine Learning Trick of the Day (2): Gaussian Integral Trick Today's trick, the Gaussian integral ...

  3. Python入门系列教程(三)列表和元组

    增 1.insert A = ['] A.insert(0,0) print A 2.append A = ['] A.append(7) print A 3.extend A = ['] B = [ ...

  4. 20155315 2016-2017-2 《Java程序设计》第六周学习总结

    教材学习内容总结 第10章 输入与输出 1.串流设计的概念 从应用程序角度看,将数据从来源取出,可以使用输入串流,将数据写入目的地,可以使用输出串流:在Java中,输入串流代表对象为java.io.I ...

  5. 20155214 2016-2017-2 《Java程序设计》第7周学习总结

    20155214 2016-2017-2 <Java程序设计>第7周学习总结 教材学习内容总结 UTC时间以Unix元年(1970年)为起点经过的秒数. ISO 8601并非年历系统,大部 ...

  6. 用threading和Queue模块实现多线程的端口扫描器

    一.Queue模块基础 q = Queue.Queue()    q.qsize()           返回队列的大小  q.empty()         如果队列为空,返回True,反之Fals ...

  7. 关于Java的“找不到或无法加载主类”

    Java编程思想4th第六章的关于访问权限和包的笔记总结时遇到了一个关于package命名及导入的问题. 环境:Ubuntu 16.04.3 LTS x86_64 首先,我要安装部署Java的开发环境 ...

  8. [转]CMake快速入门教程:实战

    转自http://blog.csdn.net/ljt20061908/article/details/11736713 0. 前言    一个多月前,由于工程项目的需要,匆匆的学习了一下cmake的使 ...

  9. 《廖雪峰Git教程》学习笔记

    原文链接 一.创建版本库 ①初始化一个Git仓库:git init ②添加文件到Git仓库:1.git add<file> ;  2.git commit 二.时光机穿梭 ①查看工作区状态 ...

  10. ubuntu复制文件或目录

    转自http://www.linuxidc.com/Linux/2008-11/17179.htm cp(copy)命令 该命令的功能是将给出的文件或目录拷贝到另一文件或目录中. 语法: cp [选项 ...