MVC设计模式实现权限管理登录,超详细

2018-11-20 03:21:46来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

功能实现:在页面输入给定的用户名之一,可以显示当前用户的权限,也可以在页面更改该用户的权限,更新之后保存。像下面这样。

填写用户名提交:

显示用户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;
	}
}
	

在web.xml中进行配置:

  <servlet>
    <servlet-name>AuthorityServlet</servlet-name>
    <servlet-class>javaweb.com.anthorityManage.AuthorityServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AuthorityServlet</servlet-name>
    <url-pattern>/AuthorityServlet</url-pattern>
  </servlet-mapping>

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(){}
}

AuthorityServlet.jsp中的form表单:

<form action="AuthorityServlet?method=getAuthorities" method="post">
    name:<input type="text" name="username"/>
    <input type="submit" value="Submit"/>
</form>

1.form表单提交到Servlet的映射地址AuthorityServlet中,在web.xml中可以读取到相应的Servlet为javaweb.com.anthorityManage.AuthorityServlet;

2.AuthorityServlet.java调用doPost()方法处理请求,String methodName=request.getParameter("method");从请求域request中读取到method的参数为getAuthorities,Method method=getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);访问指定名称和参数类型的方法,即开始执行AuthorityServlet类中的getAuthorities(HttpServletRequest request, HttpServletResponse response)方法;

3.AuthorityServlet类中的getAuthorities(HttpServletRequest request, HttpServletResponse response)方法实现的功能是:

String username=request.getParameter("username");从请求域中获取参数,得到请求域中用户提交的用户名。User user=userDao.get(username);根据得到的用户名username在userDao中获取数据库中存取的用户名。之后将userDao中获取的用户名及对应的权限信息提交给request,并且转发到相应的权限管理界面authority-manager.jsp。

4.在权限管理界面authority-manager.jsp,重复执行1,2步,在第2步中访问到的方法为AuthorityServlet类中的updateAuthorities(HttpServletRequest request, HttpServletResponse response)。

5.在updateAuthorities(HttpServletRequest request, HttpServletResponse response)方法中先从请求域中获得用户名及相应的权限信息,List<Authority> authorityList=userDao.getAuthorities(authorities);调用userDao中的getAuthorities(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中成为某个用户名的权限
					//由URL识别代表权限
					if(url.equals(authority.getUrl())){
						authorities2.add(authority);
					}
				}
			}
		}
		return authorities2;
	}

上述代码实现的功能是根据Url识别权限,如果url(请求域的)==权限中存储的url,则将请求域的权限添加到authorities2中成为某个用户名的权限。

6.userDao.update(username, authorityList);更新用户的权限信息。

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:java反射知识相关的文章

下一篇:我的第一个Java程序-HelloWorld