因为项目比较长,需要一步步进行实现,所以分解成一个一个需求。
一:需求一
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>