首页 技术 正文
技术 2022年11月21日
0 收藏 602 点赞 3,590 浏览 12478 个字

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

一:需求一

1.需求一

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

2.程序实现

3.程序目录

  Filter的应用–权限过滤

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.效果

  Filter的应用–权限过滤

二:需求二

1.需求二

  对访问权限的控制

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

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

  Filter的应用–权限过滤

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" rel="external nofollow" >返回</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" rel="external nofollow" > Article1 page</a><br><br>
<a href="article-2.jsp" rel="external nofollow" > Article2 page</a><br><br>
<a href="article-3.jsp" rel="external nofollow" > Article3 page</a><br><br>
<a href="article-4.jsp" rel="external nofollow" > Article4 page</a><br><br>
<a href="loginServlet?method=logout" rel="external nofollow" >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>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,987
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,503
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,347
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,130
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,765
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,842