美文网首页
Shiro+jsp+servlet+jdbc+c3p0

Shiro+jsp+servlet+jdbc+c3p0

作者: 煗NUAN | 来源:发表于2020-04-15 18:24 被阅读0次

    Shiro+jsp+servlet+jdbc+c3p0

    1.构建数据库rbac

    CREATE DATABASE [IF NOT EXISTS] rbac;
    
    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    -- Table structure for permission
    -- ----------------------------
    DROP TABLE IF EXISTS `permission`;
    CREATE TABLE `permission`  (
      `pid` int(0) NOT NULL AUTO_INCREMENT,
      `pname` varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
      `pdesc` varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL,
      PRIMARY KEY (`pid`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of permission
    -- ----------------------------
    INSERT INTO `permission` VALUES (1, 'select', 'select desc');
    INSERT INTO `permission` VALUES (2, 'insert', 'insert desc');
    INSERT INTO `permission` VALUES (3, 'delete', 'delete desc');
    INSERT INTO `permission` VALUES (4, 'update', 'update desc');
    
    -- ----------------------------
    -- Table structure for role
    -- ----------------------------
    DROP TABLE IF EXISTS `role`;
    CREATE TABLE `role`  (
      `rid` int(0) NOT NULL AUTO_INCREMENT,
      `rname` varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
      `rdesc` varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL,
      PRIMARY KEY (`rid`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of role
    -- ----------------------------
    INSERT INTO `role` VALUES (1, 'manager', 'manager desc');
    INSERT INTO `role` VALUES (2, 'guest', 'guest desc');
    
    -- ----------------------------
    -- Table structure for role_perms
    -- ----------------------------
    DROP TABLE IF EXISTS `role_perms`;
    CREATE TABLE `role_perms`  (
      `rid` int(0) NOT NULL,
      `pid` int(0) NOT NULL,
      PRIMARY KEY (`rid`, `pid`) USING BTREE,
      INDEX `FK_Reference_4`(`pid`) USING BTREE,
      CONSTRAINT `FK_Reference_3` FOREIGN KEY (`rid`) REFERENCES `role` (`rid`) ON DELETE RESTRICT ON UPDATE RESTRICT,
      CONSTRAINT `FK_Reference_4` FOREIGN KEY (`pid`) REFERENCES `permission` (`pid`) ON DELETE RESTRICT ON UPDATE RESTRICT
    ) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of role_perms
    -- ----------------------------
    INSERT INTO `role_perms` VALUES (1, 1);
    INSERT INTO `role_perms` VALUES (2, 1);
    INSERT INTO `role_perms` VALUES (1, 2);
    INSERT INTO `role_perms` VALUES (2, 2);
    INSERT INTO `role_perms` VALUES (1, 3);
    INSERT INTO `role_perms` VALUES (1, 4);
    
    -- ----------------------------
    -- Table structure for user
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user`  (
      `uid` int(0) NOT NULL AUTO_INCREMENT,
      `username` varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
      `password` varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
      `tel` varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
      `addr` varchar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL,
      PRIMARY KEY (`uid`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES (1, 'zhenfu', 'zhenfu', '13333333333', 'huaguoshan');
    INSERT INTO `user` VALUES (2, 'caipi', 'caopi', '13333333333', 'gaolaozhuang');
    INSERT INTO `user` VALUES (3, 'luoshen', 'luoshen', '13333333333', 'liushanhe');
    INSERT INTO `user` VALUES (4, 'caozhi', 'caozhi', '13333333333', 'datang');
    INSERT INTO `user` VALUES (5, 'caocao', 'caocao', '1111111111', 'donghailonggong');
    
    -- ----------------------------
    -- Table structure for user_role
    -- ----------------------------
    DROP TABLE IF EXISTS `user_role`;
    CREATE TABLE `user_role`  (
      `uid` int(0) NOT NULL,
      `rid` int(0) NOT NULL,
      PRIMARY KEY (`uid`, `rid`) USING BTREE,
      INDEX `FK_Reference_2`(`rid`) USING BTREE,
      CONSTRAINT `FK_Reference_1` FOREIGN KEY (`uid`) REFERENCES `user` (`uid`) ON DELETE RESTRICT ON UPDATE RESTRICT,
      CONSTRAINT `FK_Reference_2` FOREIGN KEY (`rid`) REFERENCES `role` (`rid`) ON DELETE RESTRICT ON UPDATE RESTRICT
    ) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of user_role
    -- ----------------------------
    INSERT INTO `user_role` VALUES (1, 1);
    INSERT INTO `user_role` VALUES (4, 1);
    INSERT INTO `user_role` VALUES (2, 2);
    INSERT INTO `user_role` VALUES (3, 2);
    
    SET FOREIGN_KEY_CHECKS = 1;
    

    2.添加依赖

    <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-web</artifactId>
                <version>1.3.2</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.19</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.0.1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.6</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>c3p0</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.0.2</version>
            </dependency>
        </dependencies>
    
    • 添加依赖后的pom文件
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.ym</groupId>
        <artifactId>shiroWEB</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <packaging>war</packaging>
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-web</artifactId>
                <version>1.3.2</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.19</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>2.2</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.0.1</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.6</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>c3p0</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.0.2</version>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <!-- define the project compile level -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
    
                <!-- 添加tomcat插件 -->
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <path>/</path>
                        <port>8080</port>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    3.配置web.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
        <listener>
            <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
        </listener>
    
        <filter>
            <filter-name>ShiroFilter</filter-name>
            <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
        </filter>
    
        <filter-mapping>
            <filter-name>ShiroFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    

    4.entity层下的Javabean类

    • User.java 用户表
    package com.ym.entity;
    
    import lombok.Data;
    
    import java.io.Serializable;
    import java.util.Set;
    
    @Data
    public class User implements Serializable {
        private static final long serialVersionUID = 617289138502785533L;
        
        private Integer uid;
        
        private String username;
        
        private String password;
        
        private String tel;
        
        private String addr;
    
        private Set<Role> rs;  //多对多关系
    }
    
    • Role.java 角色表
    package com.ym.entity;
    
    import lombok.Data;
    import java.io.Serializable;
    import java.util.Set;
    
    @Data
    public class Role implements Serializable {
        private static final long serialVersionUID = -74163700661732397L;
        
        private Integer rid;
        
        private String rname;
        
        private String rdesc;
    
        private Set<Permission> ps;  //多对多关心
    }
    
    • Permission.java 权限表
    package com.ym.entity;
    
    import lombok.Data;
    
    import java.io.Serializable;
    
    @Data
    public class Permission implements Serializable {
        private static final long serialVersionUID = 581645870054218482L;
        
        private Integer pid;
        
        private String pname;
        
        private String pdesc;
    }
    

    5.resource下创建shiro.ini文件

    • 自定义MyRealm
    [main]
    myRealm=com.ym.shiro.MyRealm
    
    securityManager.realm=$myRealm
    
    authc=org.apache.shiro.web.filter.authc.FormAuthenticationFilter
    authc.loginUrl=/index.html
    
    [urls]
    /index.html=anon
    /main.jsp=authc
    /manager.jsp=authc,roles[manager]
    /guest.jsp=authc,roles[guest]
    /select.jsp=perms[select]
    /delete.jsp=perms[delete]
    
    • 匿名用户访问index.html
    • 认证之后的用户访问main.jsp
    • 认证角色是manager的用户才可以访问manager.jsp
    • 认证角色是guest的用户才可以访问guest.jsp
    • 权限是select的用户才可以访问select.jsp
    • 权限是delete的用户才可以访问delete.jsp

    6.resource下创建db.properties文件

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3307/rbac?useSSL=true&serverTimezone=UTC&characterEncoding=UTF-8
    uname=root
    upass=root
    

    7.数据库连接的工具类

    • Env.java
    package com.ym.util;
    
    import java.io.IOException;
    import java.util.Properties;
    
    public class Env extends Properties {
    
        private Env(){
            try {
                load(getClass().getResourceAsStream("/db.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        public static Env getInstance(){
            return new Env();
        }
    }
    
    • C3P0Utils.java
    package com.ym.util;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    import java.beans.PropertyVetoException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class C3P0Utils {
    
        private static final String DB_URL= Env.getInstance().getProperty("url");
        private static final String DB_DRIVER= Env.getInstance().getProperty("driver");
        private static final String DB_USERNAME= Env.getInstance().getProperty("uname");
        private static final String DB_PASSWORD= Env.getInstance().getProperty("upass");
    
        public static Connection getConnection(){
            Connection conn = null;
    
            try {
                ComboPooledDataSource ds = new ComboPooledDataSource();
    
                ds.setDriverClass(DB_DRIVER);
                ds.setJdbcUrl(DB_URL);
                ds.setUser(DB_USERNAME);
                ds.setPassword(DB_PASSWORD);
    
                conn = ds.getConnection();
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    
            return conn;
        }
    
        public static void closeAll(Connection conn, PreparedStatement ptst, ResultSet rs){
            try {
                if(rs != null){
                    rs.close();
                    rs = null;
                }
                if(ptst != null){
                    ptst.close();
                    ptst = null;
                }
                if(conn != null){
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    

    8.MyRealm.java

    package com.ym.shiro;
    
    import com.ym.entity.Permission;
    import com.ym.entity.Role;
    import com.ym.entity.User;
    import com.ym.service.IUserService;
    import com.ym.service.impl.UserServiceImpl;
    import org.apache.shiro.authc.*;
    import org.apache.shiro.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    import org.apache.shiro.realm.AuthorizingRealm;
    import org.apache.shiro.subject.PrincipalCollection;
    import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
    
    import java.util.List;
    
    public class MyRealm extends AuthorizingRealm {
    
        FormAuthenticationFilter f;
    
        private IUserService userService = new UserServiceImpl();
    
        //授权
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    
            System.out.println("principals :"+principals);
    
            String username = getAvailablePrincipal(principals).toString();
            List<Role> list=userService.getAllRolesByUsername(username);
    
            for (Role r : list) {
                info.addRole(r.getRname());
            }
    
            List<Permission> permissionList = userService.getAllPermissionsByUsername(username);
    
            for (Permission p : permissionList) {
                info.addStringPermission(p.getPname());
            }
    
            return info;
        }
    
        //认证
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    
            AuthenticationInfo info = null;
    
            UsernamePasswordToken tk = (UsernamePasswordToken) token;
    
            String username = tk.getUsername();
            char[] password = tk.getPassword();
    
            String pass = new String(password);
    
            User u = userService.login(username, pass);
    
            if (u != null && u.getUid() != 0){
                info = new SimpleAuthenticationInfo(username, pass, getName());
            }
    
            return info;
        }
    }
    

    9.dao层接口及实现类

    • IUserDao.java
    package com.ym.dao;
    
    import com.ym.entity.Permission;
    import com.ym.entity.Role;
    import com.ym.entity.User;
    
    import java.util.List;
    
    public interface IUserDao {
        User login(String username, String pass);
    
        List<Role> getAllRolesByUsername(String username);
    
        List<Permission> getAllPermissionsByUsername(String username);
    }
    
    • 接口实现类UserDaoImpl.java
    package com.ym.dao.impl;
    
    import com.ym.dao.IUserDao;
    import com.ym.entity.Permission;
    import com.ym.entity.Role;
    import com.ym.entity.User;
    import com.ym.util.C3P0Utils;
    import org.junit.Test;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class UserDaoImpl implements IUserDao {
    
        private Connection conn = null;
        private PreparedStatement ptst = null;
        private ResultSet rs = null;
    
    
        @Override
        public User login(String username, String pass) {
    
            User u = null;
    
            try {
    
                conn = C3P0Utils.getConnection();
    
                String sql = "select * from user where username = ? and password = ?";
    
                ptst = conn.prepareStatement(sql);
    
                ptst.setString(1, username);
                ptst.setString(2, pass);
    
                rs = ptst.executeQuery();
    
                if(rs.next()){
                    u = new User();
    
                    u.setUid(rs.getInt(1));
                    u.setUsername(rs.getString(2));
                    u.setPassword(rs.getString(3));
                    u.setTel(rs.getString(4));
                    u.setAddr(rs.getString(5));
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
    
                C3P0Utils.closeAll(conn, ptst, rs);
            }
    
            return u;
        }
    
        @Override
        public List<Role> getAllRolesByUsername(String username) {
            List<Role> list = null;
    
            try {
                conn = C3P0Utils.getConnection();
    
                String sql = "SELECT r.*  " +
                        "FROM `user` u " +
                        "INNER JOIN user_role ur on u.uid = ur.uid " +
                        "INNER JOIN role r on ur.rid = r.rid " +
                        "where u.username = ? ";
    
                ptst = conn.prepareStatement(sql);
    
                ptst.setString(1, username);
    
                rs = ptst.executeQuery();
    
                if(rs != null){
                    list = new ArrayList<>();
    
                    Role r = null;
                    while (rs.next()){
                        r = new Role();
    
                        r.setRid(rs.getInt(1));
                        r.setRname(rs.getString(2));
                        r.setRdesc(rs.getString(3));
    
                        list.add(r);
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                C3P0Utils.closeAll(conn, ptst, rs);
            }
    
            return list;
        }
    
        @Override
        public List<Permission> getAllPermissionsByUsername(String username) {
            List<Permission> list = null;
    
            try {
                conn = C3P0Utils.getConnection();
    
                String sql = "SELECT p.*  " +
                        "FROM `user` u " +
                        "INNER JOIN user_role ur on u.uid = ur.uid " +
                        "INNER JOIN role r on ur.rid = r.rid " +
                        "INNER JOIN role_perms rp on r.rid = rp.rid  " +
                        "INNER JOIN permission p on rp.pid = p.pid " +
                        "where u.username = ?";
    
                ptst = conn.prepareStatement(sql);
    
                ptst.setString(1, username);
    
                rs = ptst.executeQuery();
    
                if(rs != null){
                    list = new ArrayList<>();
    
                    Permission r = null;
                    while (rs.next()){
                        r = new Permission();
    
                        r.setPid(rs.getInt(1));
                        r.setPname(rs.getString(2));
                        r.setPdesc(rs.getString(3));
    
                        list.add(r);
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                C3P0Utils.closeAll(conn, ptst, rs);
            }
    
            return list;
        }
    
        @Test
        public void testlogin(){
            System.out.println(new UserDaoImpl().login("caocao", "caocao"));
        }
    
        @Test
        public void testGetRoles(){
            System.out.println(new UserDaoImpl().getAllRolesByUsername("zhenfu"));
        }
    }
    

    10.service层接口及实现类

    • IUserService.java
    package com.ym.service;
    
    import com.ym.entity.Permission;
    import com.ym.entity.Role;
    import com.ym.entity.User;
    
    import java.util.List;
    
    public interface IUserService {
    
        User login(String username, String pass);
    
        List<Role> getAllRolesByUsername(String username);
    
        List<Permission> getAllPermissionsByUsername(String username);
    }
    
    • 实现类UserServiceImpl.java
    package com.ym.service.impl;
    
    import com.ym.dao.IUserDao;
    import com.ym.dao.impl.UserDaoImpl;
    import com.ym.entity.Permission;
    import com.ym.entity.Role;
    import com.ym.entity.User;
    import com.ym.service.IUserService;
    
    import java.util.List;
    
    public class UserServiceImpl implements IUserService {
    
        private IUserDao userDao = new UserDaoImpl();
    
        @Override
        public User login(String username, String pass) {
            return userDao.login(username,pass);
        }
    
        @Override
        public List<Role> getAllRolesByUsername(String username) {
            return userDao.getAllRolesByUsername(username);
        }
    
        @Override
        public List<Permission> getAllPermissionsByUsername(String username) {
            return userDao.getAllPermissionsByUsername(username);
        }
    }
    

    11.controller层UserServlet.java

    package com.ym.controller;
    
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.AuthenticationException;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.config.IniSecurityManagerFactory;
    import org.apache.shiro.mgt.SecurityManager;
    import org.apache.shiro.subject.Subject;
    
    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 java.io.IOException;
    
    @WebServlet (urlPatterns = "/UserServlet")
    public class UserServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
    
            // 构建SecurityManager工厂,IniSecurityManagerFactory可以从ini文件中初始化SecurityManager环境
            IniSecurityManagerFactory factory = new IniSecurityManagerFactory();
    
            // 通过工厂创建SecurityManager
            SecurityManager manager = factory.getInstance();
    
            // 将SecurityManager设置到运行环境中
            SecurityUtils.setSecurityManager(manager);
    
            //创建一个Subject实例,该实例认证需要使用上面创建的SecurityManager
            Subject subject = SecurityUtils.getSubject();
    
            //创建token令牌,账号和密码是ini文件中配置的
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    
            try {
                //用户登录
                subject.login(token);
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
    
            System.out.println(subject.hasRole("manager"));
            System.out.println(subject.hasRole("guest"));
    
            System.out.println(subject.isPermitted("select"));
            System.out.println(subject.isPermitted("delete"));
    
            if(subject.isAuthenticated()){
                response.sendRedirect("main.jsp");
            }
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    

    12.前端页面

    • 登陆成功之后,看是否拥有访问delete.jsp ; select.jsp ; manager.jsp ; guest.jsp的权限

    • index.html : 匿名用户访问

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>index</title>
    </head>
    <body>
        <h1>this is index page.</h1>
    
        <form action="UserServlet" method="post">
            username:<input type="text" name="username" /><p />
            password:<input type="text" name="password" /><p />
            <input type="submit" value="submit" /><p />
        </form>
    </body>
    </html>
    
    • main.jsp : 认证之后的用户才可以访问
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
    <html>
    <head>
        <title>main</title>
    </head>
    <body>
        <h1>this is main page.</h1>
    
        <shiro:authenticated>i am login successfully.</shiro:authenticated><p />
    
        <shiro:hasRole name="manager">i am a manager</shiro:hasRole><p />   <%--manager角色才会显示--%>
        <shiro:hasRole name="guest">i am a guest</shiro:hasRole><p />    <%--guest角色才会显示--%>
    
    
        <shiro:user>
            welcome back zhenfu!
            Not zhenfu? Click <a href="index.html">here</a> to login
        </shiro:user><p />
    
        <shiro:hasPermission name="select">i can select</shiro:hasPermission><p />   <%--select权限才可以显示--%>
        <shiro:hasPermission name="delete">i can delete</shiro:hasPermission><p />    <%--delete权限才可以显示--%>
    </body>
    </html>
    
    • manager.jsp : 用户角色是manager的用户才可以访问
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>manager</title>
    </head>
    <body>
        <h1>i am a manager</h1>
    </body>
    </html>
    
    • guest.jsp : 用户角色是guest的用户才可以访问
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>guest</title>
    </head>
    <body>
        <h1>i am a guest</h1>
    </body>
    </html>
    
    • select.jsp : 拥有select权限的用户才可以访问
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>select</title>
    </head>
    <body>
        <h1>select</h1>
    </body>
    </html>
    
    • delete.jsp : 拥有delete权限的用户才可以访问
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>delete</title>
    </head>
    <body>
        <h1>delete</h1>
    </body>
    </html>
    

    13.目录结构

    目录结构.png

    相关文章

      网友评论

          本文标题:Shiro+jsp+servlet+jdbc+c3p0

          本文链接:https://www.haomeiwen.com/subject/nkrhvhtx.html