preface

The previous small projects were all one table, and the business code was relatively simple. Now let’s make a permission management system to experience the business logic of multiple tables and consolidate our knowledge of filters. !


purpose

I now have a page to manage items and orders. When a user clicks on a hyperlink, the filter detects whether the user has permissions!


Demand analysis

In object-oriented thinking, we should have at least Privilege and User entities. Are two entities enough? Think about it, if we have multiple users, multiple users also have multiple permissions, when it comes to user authorization, this can be very troublesome! So we should introduce the Role entity!

Where is it convenient to introduce the Role entity? Assign the permission to a role (for example, give the permission to delete or modify the role to the administrator), and then assign the permission to the user. Then the user has the permission to modify or delete the role.

Permissions and roles are many-to-many relationships, and roles and users are many-to-many relationships.


Development of the entity

The user entity


public class User {

    private String id;
    private String username;
    private String password;

    // Remember the roles
    private Set<Role> roles = new HashSet<>();

    // Various getters and setters.....


}

Copy the code

Character entities


public class Role {
    private String id;
    private String name;
    private String description;

    // Remember all users
    private Set<User> users = new HashSet<>();

    // Remember all permissions
    private Set<Privilege> privileges = new HashSet<>();

    // Various getters and setters.....
}

Copy the code

Permissions on the entity


public class Privilege {

    private String id;
    private String name;
    private String description;

    // Remember all the characters
    private Set<Role> roles = new HashSet<>();

    // Various getters and setters.....

}

Copy the code

improved

** Users and roles, and roles and permissions are many-to-many relationships, that’s for sure! ** We also designed it in an object-oriented way, using collections to remember the other side’s data!

But let’s think about this:

  • In the Dao of permissions, when viewing permissions, is it necessary to list the corresponding roles?
  • In the Dao of a role, is it necessary to list the corresponding users when viewing the role?

The answer is no, we don’t usually show it. So, permissions entities don’t need to use Set sets to remember roles, role entities don’t need to use Set sets to remember users!

Improved authority entity



public class Privilege {

    private String id;
    private String name;
    private String description;

	// Various setter and getter methods
    
}

Copy the code

Improved character entities



public class Role {
    private String id;
    private String name;
    private String description;
    
    // Remember all permissions
    private Set<Privilege> privileges = new HashSet<>();

	// Various setter and getter methods


}


Copy the code

Create tables in the database

The user table



	CREATE TABLE user (
	  id       VARCHAR(20) PRIMARY KEY,
	  username VARCHAR(20) NOT NULL.password VARCHAR(20) NOT NULL
	
	
	);



Copy the code

Role table



	CREATE TABLE role (
	  id          VARCHAR(20) PRIMARY KEY,
	  name        VARCHAR(20) NOT NULL,
	  description VARCHAR(255)
	
	);


Copy the code

Privilege table

	CREATE TABLE privilege (
	
	  id          VARCHAR(20) PRIMARY KEY.name        VARCHAR(20) NOT NULL,
	  description VARCHAR(255));Copy the code

A relational table of users and roles


	CREATE TABLE user_role (
	
	  user_id VARCHAR(20),
	  role_id VARCHAR(20),
	  PRIMARY KEY (user_id, role_id),
	  CONSTRAINT user_id_FK FOREIGN KEY (user_id) REFERENCES user (id),
	  CONSTRAINT role_id_FK FOREIGN KEY (role_id) REFERENCES role (id));Copy the code

Table of relationships between roles and privileges


	CREATE TABLE role_privilege (
	
	  role_id      VARCHAR(20),
	  privilege_id VARCHAR(20),
	  PRIMARY KEY (role_id, privilege_id),
	
	  CONSTRAINT role_id_FK1 FOREIGN KEY (role_id) REFERENCES role (id),
	  CONSTRAINT privilege_id_FK FOREIGN KEY (privilege_id) REFERENCES privilege (id));Copy the code

Role_id = role_id = role_id = role_id = role_id = role_id = role_id = role_id


The development of DAO

PrivilegeDao

/** * Permission management should have the following functions: * 1. Add permission * 2. View all permissions * 3. Search for a permission * * */
public class PrivilegeDao {

    /* Add permission */
    public void addPrivilege(Privilege privilege) {
        try {

            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
            String sql = "INSERT INTO privilege (id, name, description) VALUE (? ,? ,?) ";
            queryRunner.update(sql, new Object[]{privilege.getId(), privilege.getName(), privilege.getDescription()});


        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Adding permissions failed!"); }}/* Find permission */
    public Privilege findPrivilege(String id) {

        try {

            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
            String sql = "SELECT *FROM privilege WHERE id = ?";
            Privilege privilege = (Privilege) queryRunner.query(sql, new BeanHandler(Privilege.class), new Object[]{id});

            return privilege;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Permission search failed!"); }}/* Get all permissions */
    public List<Privilege> getAllPrivileges(a) {

        try {

            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
            String sql = "SELECT * FROM privilege ";

            List<Privilege> privileges = (List<Privilege>) queryRunner.query(sql, new BeanListHandler(Privilege.class));
            
            return privileges;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Permission search failed!"); }}}Copy the code

Test the PrivilegeDao function

Add the parameter constructor to the Privilege object for testing convenience


	public class PrivilegeDaoTest {
	
	    PrivilegeDao privilegeDao = new PrivilegeDao();
	
	    @Test
	    public void add(a) {
	
	        Privilege privilege = new Privilege("2"."Change"."Modify function");
	
	        privilegeDao.addPrivilege(privilege);
	
	    }
	
	    @Test
	    public void getAll(a) {
	        List<Privilege> list = privilegeDao.getAllPrivileges();
	
	        for(Privilege privilege : list) { System.out.println(privilege.getId()); }}@Test
	    public void find(a) {
	        String id = "2"; Privilege privilege = privilegeDao.findPrivilege(id); System.out.println(privilege.getName()); }}Copy the code

UserDao



public class UserDao {

    public void addUser(User user) {

        try {

            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
            String sql = "INSERT INTO user (id,username,password) VALUES(? ,? ,?) ";

            queryRunner.update(sql, new Object[]{user.getId(), user.getUsername(), user.getPassword()});


        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Adding permissions failed!"); }}public User find(String id) {
        try {

            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());

            String sql = "SELECT * FROM user WHERE id=?";
            User user = (User) queryRunner.query(sql, new BeanHandler(User.class), new Object[]{id});

            return user;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Adding permissions failed!"); }}public List<User> getAll(a) {
        try {

            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());

            String sql = "SELECT * FORM user";
            List<User> users = (List<User>) queryRunner.query(sql, new BeanListHandler(User.class));

            return users;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Adding permissions failed!"); }}}Copy the code

Test UserDao




public class UserDaoTest {

    UserDao userDao = new UserDao();

    @Test
    public void add(a) {

        User user = new User();
        user.setId("2");
        user.setUsername("qqq");
        user.setPassword("123");
        userDao.addUser(user);


    }

    @Test
    public void find(a) {

        String id = "1";
        User user = userDao.find(id);

        System.out.println(user.getUsername());
    }

    @Test
    public void findALL(a) {

        List<User> userList = userDao.getAll();

        for(User user : userList) { System.out.println(user.getUsername()); }}}Copy the code

RoleDao


    public void add(Role role){

        try{
            QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
            String sql = "insert into role(id,name,description) values(? ,? ,?) ";
            Object params[] = {role.getId(),role.getName(),role.getDescription()};
            runner.update(sql, params);
        }catch (Exception e) {
            throw newRuntimeException(e); }}public Role find(String id){

        try{
            QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
            String sql = "select * from role where id=?";
            return (Role) runner.query(sql, id, new BeanHandler(Role.class));
        }catch (Exception e) {
            throw newRuntimeException(e); }}// Get all the characters
    public List<Role> getAll(a){
        try{

            QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
            String sql = "select * from role";
            return (List<Role>) runner.query(sql, new BeanListHandler(Role.class));
        }catch (Exception e) {
            throw newRuntimeException(e); }}Copy the code

Test RoleDao


    RoleDao roleDao = new RoleDao();

    @Test
    public void add(a) {

        Role role = new Role();
        role.setId("1");
        role.setName("manager");
        role.setDescription("this is a manager");

        roleDao.add(role);
    }
    @Test
    public void find( ) {

        String id = "1";
        Role role = roleDao.find(id);

        System.out.println(role.getName());

    }

    @Test
    public void getAdd(a) {

        List<Role> roleList = roleDao.getAll();

        for(Role role : roleList) { System.out.println(role.getName()); }}Copy the code

supplement

The above is just the Dao function of a single table. The User and Role tables are many-to-many relationships, and the roles and privileges tables are many-to-many relationships.

That was analyzed earlier

  • In the User object, you need a Set Set to remember the roles relationship. When displaying users, all roles should be displayed.
  • In a Role object, you need a Set to remember the relationship between privileges.

So there should be a way to get all the roles of a user in the UserDao:


    /* Get all the roles of the user */
    public List<Role> getRoles(String user_id) {

        try {

            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());

            // Query all roles by user ID. Then query the user_role table to lock the role corresponding to the user ID!
            String sql = "SELECT r.* FROM role r, user_role ur WHERE ur.user_id = ? AND r.id = ur.role_id ";

            List<Role> roles = (List<Role>) queryRunner.query(sql, new BeanListHandler(Role.class), new Object[]{user_id});

            return roles;
        } catch (Exception e) {

            e.printStackTrace();
            throw new RuntimeException("Failed to get all user roles!"); }}Copy the code

There are methods to obtain all permissions in RoleDao:




    // Get all permissions for a role.
    public List<Privilege> getPrivileges(String role_id) {
        try{

            QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());

            String sql = "SELECT p.* FROM privilege p, role_privilege rp WHERE rp.role_id = ? AND p.id = rp.role_id";

            List<Privilege> privileges = (List<Privilege>) runner.query(sql, new BeanListHandler(Privilege.class), new Object[]{role_id});

            return privileges;


        }catch (Exception e) {
            throw newRuntimeException(e); }}Copy the code

Now that we can get all the roles of the user, we can get all the permissions of the role. Then naturally we should have to modify the user’s role function, modify the role permissions function!

To modify a User’s role, you should know which User to modify, so you need the User’s ID or User object! Modify the Role is what, need Role object or load Role object collection!

In the UserDao, there is a way to modify a user’s role. We want to delete all the roles and then add new roles



    // Update the user's role
    public void updateRole(User user, List<Role> roles) {

        try {

            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());

            // Delete all the roles of the user
            String delete = "DELETE FROM user_role WHERE user_id = ?";
            queryRunner.update(delete, user.getId());


            String add = "INSERT INTO user_role (user_id,role_id) VALUES(? ,?) ";
            for (Role role : roles) {
                queryRunner.update(add, newObject[]{user.getId(), role.getId()}); }}catch (Exception e) {

            e.printStackTrace();
            throw new RuntimeException("Adding permissions failed!"); }}Copy the code

In RoleDao there are methods to modify role permissions, similar to those above.


    // Authorize a role
    public void addPrivilege2Role(Role role, List<Privilege> privileges) {

        try{
            QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());


            // Delete all permissions for this role
            String delete = "DELETE FROM role_privilege WHERE role_id = ?";
            runner.update(delete, new Object[]{role.getId()});

            // Assign new permissions to the role
            String sql = "INSERT INTO role_privilege (role_id, privilege_id) VALUES (? ,?) ";
            for (Privilege privilege : privileges) {
                runner.update(sql, newObject[]{role.getId(), privilege.getId()}); }}catch (Exception e) {
            throw newRuntimeException(e); }}Copy the code

update

Just now I thought again:

  • We don’t need to use collections to maintain roles in the User class, but collections to maintain privileges in roles. As we’ve seen in the original, we don’t need these two variables at all.
  • So, here’s the problem. When do we need to use variables in entities to maintain multi-party relationships? I think it’s like this: when we query one side’s data, the other side’s data also needs to be displayed. At this point we should use collections to maintain the data of multiple parties.
  • Based on the above example, for example: order and order item. When we look at the order, we also make sure to list all the order items.
  • Another example: When we look at the shopping cart, we need to list all the items.
  • When we use display users, we do not need to list the roles in the first time, but check the roles under the user through the hyperlink. Based on this situation, I think we do not need to use set variables to maintain the data of multiple parties.

This is similar to Hibernate lazy loading. Use the relational data only when loaded, not used when the database is not queried.

Ps: I don’t know if I understand right here. I hope I can point out if there is something wrong.


The development of the BusinessService

UserService


	public class UserService {
	
	
	    UserDao userDao = new UserDao();
	
	    // Add a user
	    public void addUser(User user) {
	
	        userDao.addUser(user);
	    }
	
	    // Find the user by id
	    public User findUser(String id) {
	        return userDao.find(id);
	    }
	
	    // Get all the users
	    public List<User> getAllUser(a) {
	        return userDao.getAll();
	    }
	
	    // Get all the roles of the user
	    public List<Role> getUserRole(String user_id) {
	        return userDao.getRoles(user_id);
	    }
	
	    // Change the role of the user
	    public void updateUserRole(User user, List<Role> roles) { userDao.updateRole(user, roles); }}Copy the code

RoleService


	public class RoleService {
	
	    RoleDao roleDao = new RoleDao();
	
	    // Add a role
	    public void addRole(Role role) {
	
	        roleDao.add(role);
	    }
	
	    // Find roles by id
	    public Role findRole(String id) {
	        return roleDao.find(id);
	    }
	
	    // Get all the characters
	    public List<Role> getAllRole(a) {
	        return roleDao.getAll();
	    }
	
	    // Obtain all role permissions
	    public List<Privilege> getRolePrivilege(String role_id) {
	        return roleDao.getPrivileges(role_id);
		}
	
	    // Modify role permissions
	    public void updateRolePrivilege(Role role, List<Privilege> privileges) { roleDao.addPrivilege2Role(role, privileges); }}Copy the code

PrivilegeService


	public class PrivilegeService {
	
	    PrivilegeDao privilegeDao = new PrivilegeDao();
	
	
	    // Add permissions
	    public void addPrivilege(Privilege privilege) {
	        privilegeDao.addPrivilege(privilege);
	    }
	
	    // Obtain permissions based on id
	    public Privilege findPrivilege(String id) {
	        return privilegeDao.findPrivilege(id);
	    }
	
	    // Get all permissions
	    public List<Privilege> getAllPrivileges(a) {
	        returnprivilegeDao.getAllPrivileges(); }}Copy the code

The development of Web

User modules

Add user

  • A Servlet that provides the page interface
        // The page for adding a user is displayed
        request.getRequestDispatcher("/WEB-INF/jsp/addUser.jsp").forward(request, response);

Copy the code
  • The JSP that displays the page

	<form action="AddUserController" method="post">
	    <table>
	        <tr>
	            <td>User name:</td>
	            <td><input type="text" name="username"></td>
	        </tr>
	        <tr>
	            <td>Password:</td>
	            <td><input type="password" name="password"></td>
	        </tr>
	        <tr>
	            <td><input type="submit" value="Add user"></td>
	            <td><input type="reset" value="Reset"></td>
	        </tr>
	    </table>
	</form>


Copy the code
  • A Servlet that processes form data

        // Get the arguments passed in by the client
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();
        user.setId(WebUtils.makeId());
        user.setUsername(username);
        user.setPassword(password);

        try {
            UserService userService = new UserService();
            userService.addUser(user);

            request.setAttribute("message"."User added successfully!");

        } catch (Exception e) {
            request.setAttribute("message"."Add user failed!");
            throw new RuntimeException("Failed to add customer in Controller");
        }
        request.getRequestDispatcher("/message.jsp").forward(request,response);
        
    }

Copy the code
  • Effect:


According to the user

  • A Servlet that provides the page interface

        UserService userService = new UserService();
        List<User> list = userService.getAllUser();
        request.setAttribute("list", list);

        // Jump to the display page
        request.getRequestDispatcher("/WEB-INF/jsp/LookUser.jsp").forward(request, response);


Copy the code
  • Display page JSP
< c: if test = "${empty (list)}" > I'm sorry, temporarily no customers < / c: if > < c: if test = "${! The empty (list)} "> < table border =" 1 px "> < tr > < td > user name < / td > < td > password < / td > < / tr > < c: forEach items =" ${list} "var =" user "> < tr > <td>${user.username}</td> <td>${user.password}</td> </tr> </c:forEach> </table> </c:if>Copy the code
  • Effect:


Add roles for users

In addition to displaying the user, you should add a hyperlink for the user’s authorization role.

< table border = "1 px" > < tr > < td > user name < / td > < td > password < / td > < td > action < / td > < / tr > < c: forEach items = "${list}" var = "user" > < tr > <td>${user.username}</td> <td>${user.password}</td> <td> <a href="${pageContext.request.contextPath}/LookUserRole? User_id = ${user. Id} "> authorization roles for the user < / a > < a href =" # "> modify the user < / a > < a href =" # "> delete user < / a > < / td > < / tr > < / c: forEach > < / table >Copy the code
  • Effect:

  • Handles the Servlet that displays the authorization page


        // Get the user_id passed by the client
        String user_id = request.getParameter("user_id");

        // Get all the roles of the user
        UserService userService = new UserService();
        List<Role> userRoles = userService.getUserRole(user_id);

        // Get all the characters
        RoleService roleService = new RoleService();
        List<Role> allRoles = roleService.getAllRole();

        // The JSP page that authorizes the User should also display the User's information, so pass the User object to the JSP page as well
        User user = userService.findUser(user_id);

        request.setAttribute("user", user);
        request.setAttribute("userRoles", userRoles);
        request.setAttribute("allRoles", allRoles);

        // Jump to the display page
        request.getRequestDispatcher("/WEB-INF/jsp/LookUserRole.jsp").forward(request, response);

Copy the code
  • Authorization Page JSP



<table border="1px">
    <tr>
        <td>Current User name</td>
        <td>${user.username}</td>
    </tr>

    <tr>
        <td>The role owned by the current user</td>
        <td>
            <c:forEach items="${userRoles}" var="userRole">
                ${userRole.name}
            </c:forEach>
        </td>
    </tr>

    <tr>
        <td>The role currently owned by the system</td>
        <td>
            <form method="post" action="${pageContext.request.contextPath}/AddUserRole">

                <%-- To add a role for the user, you need to know which user it is, and pass in the user ID --% by hidden>
                <input type="hidden" name="user_id" value="${user.id}">

                <c:forEach items="${allRoles}" var="roles">
                    <input type="checkbox" name="role_id" value="${roles.id}">${roles.name}
                </c:forEach>

                <input type="submit" value="Add characters!">
            </form>
        </td>
    </tr>

</table>

Copy the code
  • Effect:

  • A Servlet that processes the form data and adds roles to the user


        // Get the role_id passed in
        String[] ids = request.getParameterValues("role_id");

        try {
            // Get the id of the user you want to modify
            String user_id = request.getParameter("user_id");

            // Get the User object by id
            UserService userService = new UserService();
            User user = userService.findUser(user_id);

            // Get the Role object by id and load the object with the List collection
            RoleService roleService = new RoleService();
            List<Role> list = new ArrayList<>();
            for (String id : ids) {
                Role role = roleService.findRole(id);
                list.add(role);
            }

            // Update the role owned by the user
            userService.updateUserRole(user, list);

            request.setAttribute("message"."Character added successfully!");

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message"."Failed to add role!");
        }
        request.getRequestDispatcher("/message.jsp").forward(request,response);

Copy the code
  • Effect:


Role module

Adding roles

  • Provides a Servlet to add a role page

        // Jump directly to the JSP page
        request.getRequestDispatcher("WEB-INF/jsp/AddRole.jsp").forward(request, response);

Copy the code
  • Display page JSP


	<form action="${pageContext.request.contextPath}/AddRoleController" method="post">
	    <table border="1px">
	        <tr>
	            <td>Character name</td>
	            <td><input type="text" name="name"></td>
	        </tr>
	        <tr>
	            <td>A detailed description</td>
	            <td><textarea name="description"  cols="30" rows="10"></textarea></td>
	        </tr>
	
	        <tr>
	            <td>
	                <input type="submit" value="Add a role">
	            </td>
	        </tr>
	    </table>
	
	</form>

Copy the code
  • A Servlet that processes form data and adds roles


        // Get the data from the client
        String name = request.getParameter("name");
        String description = request.getParameter("description");

        try {
            // Create objects and encapsulate data
            Role role = new Role();
            role.setId(WebUtils.makeId());
            role.setName(name);
            role.setDescription(description);

            // Call the Service method to complete the function
            RoleService roleService = new RoleService();
            roleService.addRole(role);

            request.setAttribute("message"."Character added successfully!");
        } catch (Exception e) {
            request.setAttribute("message"."Failed to add role!");
            e.printStackTrace();
        }

        request.getRequestDispatcher("/message.jsp").forward(request, response);
Copy the code
  • Effect:


View all roles

  • Servlets that provide pages


        // Get all the characters
        RoleService roleService = new RoleService();
        List<Role> list = roleService.getAllRole();

        request.setAttribute("list", list);
        request.getRequestDispatcher("/WEB-INF/jsp/LookRoles.jsp").forward(request, response);

Copy the code
  • Display page JSP

	<c:if test="${empty(list)}">You don't have any roles yet, please add them!</c:if>
	
	<c:if test="${! empty(list)}">
	    <table border="1px">
	        <tr>
	            <td>Character name</td>
	            <td>describe</td>
	        </tr>
	
	        <c:forEach items="${list}" var="role">
	            <tr>
	                <td>${role.name}</td>
	                <td>${role.description}</td>
	            </tr>
	        </c:forEach>
	    </table>
	
	
	</c:if>


Copy the code
  • The effect


Authorizing roles

With the above is similar, we want to view the role, add authorization function!


        <c:forEach items="${list}" var="role">
            <tr>
                <td>${role.name}</td>
                <td>${role.description}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/LookRolePrivilege? role_id=${role.id}">Authorizing roles</a>
                    <a href="#">Delete the role</a>
                    <a href="#">Modify the role</a>
                </td>
            </tr>
        </c:forEach>
Copy the code
  • Effect:


  • Provides a Servlet that displays the rights page

        // Get the role ID that the browser wants to view
        String role_id = request.getParameter("role_id");
        RoleService roleService = new RoleService();

        // Get Role object according to id
        Role role = roleService.findRole(role_id);

        // Get all the rights of the current character
        List<Privilege> rolePrivilege = roleService.getRolePrivilege(role_id);

        // Get all rights of the system
        PrivilegeService privilegeService = new PrivilegeService();
        List<Privilege> allPrivilege = privilegeService.getAllPrivileges();

        request.setAttribute("role", role);
        request.setAttribute("rolePrivilege", rolePrivilege);
        request.setAttribute("allPrivilege", allPrivilege);

        // Jump to the display page
        request.getRequestDispatcher("/WEB-INF/jsp/LookRolePrivilege.jsp").forward(request, response);

Copy the code
  • Display page JSP


	<table border="1px">
	    <tr>
	        <td>Character name</td>
	        <td>${role.name}</td>
	    </tr>
	
	    <tr>
	        <td>Rights owned by the current role</td>
	        <td>
	            <c:forEach items="${rolePrivilege}" var="privi">
	                ${privi.name}
	            </c:forEach>
	        </td>
	    </tr>
	
	
	    <tr>
	        <td>All rights owned by the system</td>
	        <td>
	            <form action="${pageContext.request.contextPath}/AddRolePrivilegeController" method="post">
	                <%- lets the server know which user to modify by passing the user ID -%>
	                <input type="hidden" name="role_id" value="${role.id}">
	                
	                <c:forEach items="${allPrivilege}" var="privileges">
	                    <input type="checkbox" name="privilege" value="${privileges.id}">${privileges.name}
	                </c:forEach>
	                <input type="submit" value="Add rights">
	            </form>
	        </td>
	    </tr>
	</table>

Copy the code
  • Effect:


  • A Servlet that processes form data and adds role rights


        // Get the id of the rights that the browser wants to add
        String[] ids = request.getParameterValues("privilege_id");

        // Get the role ID
        String role_id = request.getParameter("role_id");


        try {
            // Get the character you want to add rights to
            RoleService roleService = new RoleService();
            Role role = roleService.findRole(role_id);

            // Get the entitlement object and load it with the List object
            PrivilegeService privilegeService = new PrivilegeService();
            List<Privilege> privileges_list = new ArrayList<>();
            for (String id : ids) {
                Privilege privilege = privilegeService.findPrivilege(id);
                privileges_list.add(privilege);
            }

            roleService.updateRolePrivilege(role, privileges_list);

            request.setAttribute("message"."Adding rights to character succeeded!");

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message"."Failed to add rights to character!");
        }

        request.getRequestDispatcher("/message.jsp").forward(request, response);
Copy the code
  • Effect:


Permissions module

Add permissions

  • Provides a Servlet to add a permission page

        // Jump directly to the JSP page
        request.getRequestDispatcher("/WEB-INF/jsp/AddPrivilege.jsp").forward(request, response);

Copy the code
  • Display page JSP


	<form action="${pageContext.request.contextPath}/AddPrivilegeController" method="post">
	
	    <table border="1px">
	        <tr>
	            <td>Permission to name</td>
	            <td><input type="text" name="name"></td>
	        </tr>
	        <tr>
	            <td>Permissions described</td>
	            <td><textarea name="description" cols="30" rows="10"></textarea></td>
	        </tr>
	
	        <tr>
	            <td><input type="submit" value="Add Permission"></td>
	            <td><input type="reset" value="Reset"></td>
	        </tr>
	
	    </table>
	</form>

Copy the code
  • Effect:


  • Servlet to process form data and add permissions

        // Get the data from the browser
        String name = request.getParameter("name");
        String description = request.getParameter("description");

        // Encapsulate data to the Privilege object
        Privilege privilege = new Privilege();
        privilege.setId(WebUtils.makeId().substring(3.10));
        privilege.setName(name);
        privilege.setDescription(name);


        try {
            PrivilegeService privilegeService = new PrivilegeService();
            privilegeService.addPrivilege(privilege);

            request.setAttribute("message"."Permission added successfully!");

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message"."Add permission failed!");
        }

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


Copy the code
  • Effect:


View All Permissions

  • Servlets that provide pages



        // Get all permissions
        PrivilegeService privilegeService = new PrivilegeService();
        List<Privilege> list = privilegeService.getAllPrivileges();

        request.setAttribute("list", list);
        request.getRequestDispatcher("/WEB-INF/jsp/LookPrivileges.jsp").forward(request, response);

Copy the code
  • A JSP that displays the permissions page


	<c:if test="${empty(list)}">You have not added any permissions</c:if>
	
	<c:if test="${! empty(list)}">
	    <table border="1px">
	        <tr>
	            <td>Permission to name</td>
	            <td>describe</td>
	            <td>operation</td>
	        </tr>
	
	        <c:forEach items="${list}" var="privilege">
	            <tr>
	                <td>${privilege.name}</td>
	                <td>${privilege.description}</td>
	                <td>
	                    <a href="#">Remove permissions</a>
	                    <a href="#">Modify the permissions</a>
	                </td>
	
	            </tr>
	
	        </c:forEach>
	    </table>
	    
	</c:if>

Copy the code
  • Effect:


Splicing together functions with frames

  • The head page

	<body style="text-align: center">
	
	<h1>XX Management System</h1>
	</body>


Copy the code
  • The left page

	
	<body>
	<a href="${pageContext.request.contextPath}/LookUserUI" target="body">User management</a><br><br><br><br>
	<a href="${pageContext.request.contextPath}/LookRolesUI" target="body">Role management</a><br><br><br><br>
	<a href="${pageContext.request.contextPath}/LookPrivileges" target="body">Rights management</a><br><br><br><br>
	
	</body>
Copy the code
  • The body page is blank!

  • The index page:



	<% @ page contentType="text/html; charset=UTF-8" language="java"% >
	<html>
	  <head>
	    <title>$Title$</title>
	  </head>
	<frameset rows="25%, *">
	  <frame src="head.jsp" name="head">
	    <frameset cols="15%, *">
	      <frame src="left.jsp" name="left">
	      <frame src="body.jsp" name="body">
	    </frameset>
	</frameset>
	</html>

Copy the code
  • Effect:


The filter

The main job of the filter is: when a hyperlink is clicked, the filter will check whether the clicker has permission to enter the page for action (CURD).

Here we do it this way: URIs as keys and permissions as values form a Map set. When the user requests the resource, determine whether the resource needs permission, if need permission, judge whether the user logged in, if logged in, judge whether the user has permission to access the resource!

  • Add the login method to the UserDao and UserService:

Supplementary code



    public User login(String username, String password) {

        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());

            String sql = "SELECT * FROM user WHERE username=? AND password=?";
            User user = (User) queryRunner.query(sql, new BeanHandler(User.class), new Object[]{username, password});

            return user;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Login failed!!"); }}Copy the code
  • Login interface JSP


	<form action="${pageContext.request.contextPath}/LoginController" method="post">User name:<input type="text" name="username"><br>Password:<input type="password" name="password"><br>
	    <input type="submit" value="Login"><br>
	</form>

Copy the code
  • The Servlet that handles the login


        // Get form data
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserService userService = new UserService();
        User user = userService.login(username, password);

        if(user ! =null) {
            request.setAttribute("message"."Congratulations, you logged in successfully!");
            request.getSession().setAttribute("user", user);
        } else {
            request.setAttribute("message"."Wrong username or password!!");
        }

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

Copy the code

The Filter code

  • Complete code:

    private Map<String, Privilege> map = new HashMap<>();
    public void init(FilterConfig config) throws ServletException {

        map.put("/addServlet".new Privilege("Add"));
        map.put("/deleteServlet".new Privilege("Delete"));
        map.put("/updateServlet".new Privilege("Change"));
        map.put("/findServlet".new Privilege("Check the bill"));

    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // Get the resource address requested by the user
        String uri = request.getRequestURI();
        System.out.println(uri);

        // Select * from key; // select * from key;
        if (map.get(uri) == null) {
            chain.doFilter(request, response);
            System.out.println("Let go.");
            return ;
        }
        // If not empty, permissions are required. If you need permission, determine if the requester is logged in!
        if (request.getSession().getAttribute("user") = =null) {
            request.setAttribute("message"."You login again to operate!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
        }

        // If logged in, check to see if the user's permissions match those of the resource
        User user = (User) request.getSession().getAttribute("user");
        UserService userService = new UserService();
        RoleService roleService = new RoleService();

        // Get all of the user's roles
        List<Role> roles = userService.getUserRole(user.getId());

        // Get all permissions for a role.
        // Now we need to load the permissions of each role with collections again!
        Set privileges = new HashSet();
        for (Role role : roles) {
            List<Privilege> list = roleService.getRolePrivilege(role.getId());
            privileges.addAll(list);
        }

        // The resulting Set is the user's full permissions !!!!!
        // The contains method of the collection compares the default object, and we want to compare string names, so we override equals and hashCode in the Privilege object!
        if(! privileges.contains(map.get(uri))) { request.setAttribute("message"."You don't have clearance.");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return ;
        }

        // If you want to use this command, you can use this command
        chain.doFilter(request, response);
    }


    public void destroy(a) {}Copy the code

test


Summarizes the main points

① : The relationship between users and permissions, because of the lack of adding user permissions and modifying user permissions [in the case of a lot of permissions, this situation is difficult to deal with], so we introduced the concept of role

② The relationship between users and roles and roles and permissions is many-to-many

③ : According to the database paradigm, we will create 5 real tables, two of which represent: user and role, role and permission relationship table. Role this field in the foreign key, cannot have the same name!

④ : Whether role, user, permission have these three methods: get all the permission (role, user), add permission (role, user), permission ID get permission (role, user) object

In the Web display layer, the object can only be identified by its ID, while in the back end, objects are often used, so this method comes into being.

⑥ : The relationship between many and many, in the program does not have to define a set on its class to remember each other. When displaying users, you need to display roles, but when displaying roles, you generally do not need to display user information. Therefore, in terms of roles, there is no need to maintain a collection to remember all users

⑦ : Get all roles of the user: the passed parameter must have a specific user or role, so the ID must be passed in from the outside. The same goes for getting all permissions for a role.

⑧ : Modify the user’s role: we first delete all the user’s role, and then add the role selected by the outside (this is a compromise)

⑨ : When adding a user role, the user ID must be passed to the server through the hidden domain, otherwise the server will not know which user role to change. The same is true for modifying roles.

⑩ Frameset and frame are used for foreground framing. Target specifies where to display specific data

①① : Use a Map set in the init() method with the URI as the key and the specific permission as the value to filter

① and ② : If the URI does not require permission, permit the URI. If permission is required, determine whether the user is logged in. Let the user log in without logging in

①③ : If you log in, you get all permissions of the user, permissions are loaded with a Set, traversing the Set, using the contains() method you can check whether there are corresponding permissions.

①④ : Using the contains() method requires overriding the hashCode() and equals() methods on the permission class. Because we’re comparing strings.


If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public number :Java3y