1. 程式人生 > >許可權管理登入程式碼實現

許可權管理登入程式碼實現

功能實現:在頁面輸入給定的使用者名稱之一,可以顯示當前使用者的許可權,也可以在頁面更改該使用者的許可權,更新之後儲存。像下面這樣。

填寫使用者名稱提交:

顯示使用者AAA的許可權:

修改許可權(增加article3):

點選Update之後,許可權更新,下次訪問,輸入使用者名稱AAA提交後顯示:

提交使用者名稱,顯示使用者許可權和修改使用者許可權頁面:authority-manager.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'authority-manager.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <center>
    <br><br>
    <form action="AuthorityServlet?method=getAuthorities" method="post">
      name:<input type="text" name="username"/>
      <input type="submit" value="Submit"/>
    </form>
    
    <c:if test="${requestScope.user!=null }">
       <br><br>
       ${requestScope.user.username}的許可權是:
       <br><br>
       
       <form action="AuthorityServlet?method=updateAuthorities" method="post">
         <input type="hidden" name="username" value="${requestScope.user.username}"/>
         <br><br>
         <!-- 兩個迴圈:外層迴圈先將許可權都列出來,內層迴圈用於將對應使用者的對應許可權 -->
         <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==true}">
             <input type="checkbox" name="authority" value="${auth.url}" checked="checked"/>${auth.displayname}
           </c:if>
           <c:if test="${flag==false}">
             <input type="checkbox" name="authority" value="${auth.url}" />${auth.displayname}
           </c:if>
           
           <br><br>
         </c:forEach>
         <input type="submit" value="Update">
       </form>
    </c:if>
    
    </center>
  </body>
</html>

Servlet實現類,AuthorityServlet.java

package javaweb.com.anthorityManage;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthorityServlet extends HttpServlet {
    
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //authority-manager.jsp中的method引數-->getAuthorities
		String methodName=request.getParameter("method");
        try {
        	//getClass-->Class型物件,獲得許可權為public的內部類(即為public class AuthorityServlet)
        	//getMethod返回Method型別的物件,每個Method型別的物件代表一個方法
        	//getMethod(String方法名稱,入口引數型別1.class,入口引數型別2.class)-->訪問指定名稱和引數型別的方法
			Method method=getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//invoke(Object obj,Object...args)-->利用指定引數args執行指定物件obj中的該方法,返回值為Object型
			//利用指定引數request,response執行method方法
			method.invoke(this, request,response);
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	private UserDao userDao=new UserDao();
	public void getAuthorities(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		//從請求引數中獲取使用者名稱
		String username=request.getParameter("username");
	    //從userDao中獲取使用者名稱(帶有使用者的許可權資訊)
		User user=userDao.get(username);
		//將userDao中獲得的使用者名稱傳遞給request請求
		request.setAttribute("user",user);
		//userDao中獲取的許可權資訊新增到request中
		request.setAttribute("authorities", userDao.getAuthorities());
		//按照使用者名稱轉發到相應的許可權管理頁面
		request.getRequestDispatcher("/jspTest/authority-manager.jsp").forward(request, response);
		
	}
	public void updateAuthorities(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		//從請求域獲得使用者名稱和相應的多個許可權
		String username=request.getParameter("username");
		//從客戶端request域獲得的許可權
		String[] authorities=request.getParameterValues("authority");
		List<Authority> authorityList=userDao.getAuthorities(authorities);
		userDao.update(username, authorityList);
		//request.getContextPath()-->返回站點的根路徑
		response.sendRedirect(request.getContextPath()+"/jspTest/authority-manager.jsp");
		
	}
}

UserDao類執行具體的事務操作,UserDao.java

package javaweb.com.anthorityManage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//UserDao類執行具體的事務操作
public class UserDao {

	private static Map<String,User> users;
	private static List<Authority> authorities;
	
	static{
		authorities=new ArrayList<>();
		authorities.add(new Authority("article-1","/jspTest/1.jsp"));
	    authorities.add(new Authority("article-2","/jspTest/2.jsp"));
	    authorities.add(new Authority("article-3","/jspTest/3.jsp"));
	    authorities.add(new Authority("article-4","/jspTest/4.jsp"));
	    
		users=new HashMap<String,User>();
	    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);
	}
	//相當於String m1(){}  獲得users中的使用者姓名
	User get(String username){
		return users.get(username);
	}
	//更新使用者的許可權
	void update(String username,List<Authority> authorities){
		users.get(username).setAuthorities(authorities);
	}
	public List<Authority> getAuthorities(){
		return authorities;
	}
	public List<Authority> getAuthorities(String[] urls){
		List<Authority> authorities2=new ArrayList<>();
		for(Authority authority:authorities){
			if(urls!=null){
				for(String url:urls){
					//遍歷比較,如果url(請求域的)==許可權中儲存的url,則將請求域的許可權新增到authorities2中成為某個使用者名稱的許可權
					if(url.equals(authority.getUrl())){
						authorities2.add(authority);
					}
				}
			}
		}
		return authorities2;
	}
}
	

Authority.java

package javaweb.com.anthorityManage;

public class Authority {

	private String displayname;
	private String 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;
	}
	public Authority(String displayname, String url) {
		super();
		this.displayname = displayname;
		this.url = url;
	}
	public Authority(){}
}

User.java

package javaweb.com.anthorityManage;

import java.util.List;

public class User {

	private String username;
	private List<Authority> 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;
	}
	public User(String username, List<Authority> authorities) {
		super();
		this.username = username;
		this.authorities = authorities;
	}
	public User(){}
}