学习笔记

it2024-08-22  31

RBAC ->基于角色的权限控制

l  tb_userl  tb_rolel  tb_userrolel  tb_menu(增、删、改、查)l  tb_rolemenu
1 说明

我们给出三个页面:index.jsp、user.jsp、admin.jsp。

l  index.jsp:谁都可以访问,没有限制;

l  user.jsp:只有登录用户才能访问;

l  admin.jsp:只有管理员才能访问。 

2 分析

设计User类:username、password、grade,其中grade表示用户等级,1表示普通用户,2表示管理员用户。

当用户登录成功后,把user保存到session中。

创建LoginFilter,它有两种过滤方式:

l  如果访问的是user.jsp,查看session中是否存在user;

l  如果访问的是admin.jsp,查看session中是否存在user,并且user的grade等于2。 

3 代码

User.java

public class User {

    private String username;

    private String password;

    private int grade[崔1] ;

}

 

 [崔1]用户等级

 [崔2]所有用户

 [崔3]在Map中保存两个用户,zhangSan的等级为1,liSi的等级为2

 [崔4]登录方法

 [崔5]通过用户名获取用户

 [崔6]如果用户名不存在,返回null

 [崔7]如果密码不对返回null,如果密码正确返回用户

  为了方便,这里就不使用数据库了,所以我们需要在UserService中创建一个Map,用来保存所有用户。Map中的key中用户名,value为User对象。

UserService.java

public class UserService {

    private static Map<String,User> users [崔2] = new HashMap<String,User>();

    static {

       users.put("zhangSan", new User("zhangSan", "123", 1));

       users.put("liSi", new User("liSi", "123", 2));

[崔3]    }

   

    public User login[崔4] (String username, String password) {

       User user = users.get(username);[崔5] 

       if(user == null) return null;[崔6] 

       return user.getPassword().equals(password) ? user : null;[崔7] 

    }

}

 

  login.jsp

  <body>

  <h1>登录</h1>

    <p style="font-weight: 900; color: red">${msg }[崔8] </p>

    <form action="<c:url value='/LoginServlet'/>" method="post">

    用户名:<input type="text" name="username"/><br/>

    密 码:<input type="password" name="password"/><br/>

    <input type="submit" value="登录"/>

    </form>

  </body>

  [崔8]当登录出错时返回到login.jsp页面,显示“用户名或密码错误”

  index.jsp

  <body>

    <h1>主页</h1>

    <h3>${user.username }</h3>

    <hr/>

    <a href="<c:url value='/login.jsp'/>">登录</a><br/>

    <a href="<c:url value='/user/user.jsp'/>">用户页面</a><br/>

    <a href="<c:url value='/admin/admin.jsp'/>">管理员页面</a>

  </body>

 

  /user/user.jsp

<body>

<h1>用户页面</h1>

<h3>${user.username }</h3>

<hr/>

</body>

 

  /admin/admin.jsp

<body>

  <h1>管理员页面</h1>

  <h3>${user.username }</h3>

  <hr/>

</body>

 

  LoginServlet

public class LoginServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

       request.setCharacterEncoding("utf-8");

       response.setContentType("text/html;charset=utf-8");

      

       String username = request.getParameter("username");

       String password = request.getParameter("password");

[崔9]        UserService userService = new UserService();

       User user = userService.login(username, password);[崔10] 

       if(user == null[崔11] ) {

           request.setAttribute("msg", "用户名或密码错误");

           request.getRequestDispatcher("/login.jsp").forward(request, response);

[崔12]       } else {

           request.getSession().setAttribute("user", user);

           request.getRequestDispatcher("/index.jsp").forward(request, response);

[崔13]       }

    }

}

 

 [崔9]获取表单数据

 [崔10]调用userService的login()方法完成登录

 [崔11]返回的user为null表示登录失败

 [崔12]在request 中保存错误信息,转发到login.jsp页面显示错误信息

 [崔13]如果登录成功,把user对象保存到session中,并转发到index.jsp页面

  LoginUserFilter.java

  <filter>

    <display-name>LoginUserFilter</display-name>

    <filter-name>LoginUserFilter</filter-name>

    <filter-class>cn.itcast.filter.LoginUserFilter</filter-class>

  </filter>

  <filter-mapping>

    <filter-name>LoginUserFilter</filter-name>

    <url-pattern>/user/*[崔14] </url-pattern>

  </filter-mapping>

public class LoginUserFilter implements Filter {

    public void destroy() {}

    public void init(FilterConfig fConfig) throws ServletException {}

 

    public void doFilter(ServletRequest request, ServletResponse response,

           FilterChain chain) throws IOException, ServletException {

       response.setContentType("text/html;charset=utf-8");

       HttpServletRequest req = (HttpServletRequest) request;

       User user = (User) req.getSession().getAttribute("user");[崔15] 

       if(user == null)[崔16]  {

           response.getWriter().print("您还没有登录");[崔17] 

           return;[崔18] 

       }

       chain.doFilter(request, response);[崔19] 

    }

}

 

[崔14]通过/user下的页面

 [崔15]在session中获取当前user对象

 [崔16]如果session中不存在user,说明当前用户还没有登录

 [崔17]各客户端浏览器打印错误消息

 [崔18]一定要返回,不然会向下执行“放行”的。

 [崔19]如果在session中存在user,那么就放行

  LoginAdminFilter.java

  <filter>

    <display-name>LoginAdminFilter</display-name>

    <filter-name>LoginAdminFilter</filter-name>

    <filter-class>cn.itcast.filter.LoginAdminFilter</filter-class>

  </filter>

  <filter-mapping>

    <filter-name>LoginAdminFilter</filter-name>

    <url-pattern>/admin/*[崔20] </url-pattern>

  </filter-mapping>

public class LoginAdminFilter implements Filter {

    public void destroy() {}

    public void init(FilterConfig fConfig) throws ServletException {}

 

    public void doFilter(ServletRequest request, ServletResponse response,

           FilterChain chain) throws IOException, ServletException {

       response.setContentType("text/html;charset=utf-8");

       HttpServletRequest req = (HttpServletRequest) request;

       User user = (User) req.getSession().getAttribute("user");[崔21] 

       if(user == null) {

           response.getWriter().print("您还没有登录!");

           return;

       }[崔22] 

       if(user.getGrade() < 2) {

           response.getWriter().print("您的等级不够!");

           return;

       }[崔23] 

       chain.doFilter(request, response);[崔24] 

    }

}

 

  禁用资源缓存

  浏览器只是要缓存页面,这对我们在开发时测试很不方便,所以我们可以过滤所有资源,然后添加去除所有缓存!

public class NoCacheFilter extends HttpFilter {

    public void doFilter(HttpServletRequest request,

           HttpServletResponse response, FilterChain chain)

           throws IOException, ServletException {

       response.setHeader("cache-control", "no-cache");

       response.setHeader("pragma", "no-cache");

       response.setHeader("expires", "0");

       chain.doFilter(request, response);

    }

}

 

  但是要注意,有的浏览器可能不会理会你的设置,还是会缓存的!这时就要在页面中使用时间戳来处理了。

 


 [崔20]过滤/admin目录下的页面

 [崔21]获取session中的user

 [崔22]如果user为null,说明用户没有登录

 [崔23]如果用户等级小于2,说明是普通用户,而不是管理员用户

 [崔24]放行

 

 

完整代码

1、index.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 'index.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> <h1>你就是个游客而已</h1> <a href="<c:url value='/index.jsp'/>">游客入口</a><br/> /* 加这么几个超链接*/ <a href="<c:url value='/users/u.jsp'/>">会员入口</a><br/> <a href="<c:url value='/admin/a.jsp'/>">管理员入口</a><br/> </body> </html>

 

2、login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'login.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> <h1>登录</h1> ${msg } <form action="<c:url value='/LoginServlet'/>" method="post"> //获取表单数据,方法为post方法; 用户名:<input type="text" name="username"/> <input type="submit" value="登录"/> </form> </body> </html>

 

 

3、LoginServlet.java

package cn.itcast.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); /* * 1. 获取用户名 * 2. 判断用户名中是否包含itcast * 3. 如果包含,就是管理员 * 4. 如果不包含,就是普通会员 * 5. 要把登录的用户名称保存到session中,一定要保存在session空间 * 6. 转发到index.jsp */ String username = request.getParameter("username"); //得到用户名 if(username.contains("itcast")) { //这里设置只要用户名包含idcast就是管理员; request.getSession().setAttribute("admin", username); //登录数据一定要保存在session空间admin中; } else { request.getSession().setAttribute("username", username); //键有区别;一个是admin,一个是 } request.getRequestDispatcher("/index.jsp").forward(request, response); //跳转下一个 } }

 下面两个保安,两个Filter

4、AdminFilter.java

package cn.itcast.web.filter; 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; /** * Servlet Filter implementation class AdminFilter */ public class AdminFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { /* * 1. 得到session * 2. 判断session域中是否存在admin,如果存在,放行 * 3. 判断session域中是否存在username,如果存在,放行,否则打回到login.jsp,并告诉它不要瞎留达 */ HttpServletRequest req = (HttpServletRequest) request; String name = (String)req.getSession().getAttribute("admin"); if(name != null) { chain.doFilter(request, response); } else { req.setAttribute("msg", "您可能是个啥,但肯定不是管理员!"); req.getRequestDispatcher("/login.jsp").forward(request, response); } } public void init(FilterConfig fConfig) throws ServletException { } }

5、UserFilter.java

package cn.itcast.web.filter; 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; public class UserFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { /* * 1. 得到session * 2. 判断session域中是否存在admin,如果存在,放行 * 3. 判断session域中是否存在username,如果存在,放行,否则打回到login.jsp,并告诉它不要瞎留达 */ HttpServletRequest req = (HttpServletRequest) request; String name = (String)req.getSession().getAttribute("admin"); if(name != null) { chain.doFilter(request, response); return; } name = (String)req.getSession().getAttribute("username"); if(name != null) { chain.doFilter(request, response); } else { req.setAttribute("msg", "您啥都不是,不要瞎溜达!"); req.getRequestDispatcher("/login.jsp").forward(request, response); } } public void init(FilterConfig fConfig) throws ServletException { } }

 

转载于:https://www.cnblogs.com/snowwhite/p/4640895.html

最新回复(0)