User Management System

1) User management project: basic function introduction

1) Login function: Only super administrators can log in, ordinary users cannot log in

2) User list pages: list pages for common users and list pages for super administrators

3) Conditional query: combined conditional query, query with indeterminate rules, specified name, specified place of origin, and specified email address for query

4) Paging function: front-end display paging function

5) Add users: ordinary administrators cannot operate super administrators (modify, delete), but can add ordinary administrators

6) Single entry delete function, multiple entry delete function (select multiple entries to delete), the super administrator cannot be deleted

7) Modify user: the login name cannot be modified, if the login name is different from the user name, the super administrator information cannot be modified

8) Delete a single user, and delete multiple users in batches (use the dynamic label to determine whether there is a super administrator in it, if there is a super administrator, it cannot be deleted)

2) Design database:

Technology used: SpringBoot+Mybatis+SpringMVC+Interceptor+Return of unified data format

user table:

UserID User's unique ID int

Name Varchar(50)

sex varchar(10)

age int

native place varchar(50)

QQ varchar(15)

Mailbox varchar(50) Whether it is a super administrator, int

Login name varchar(50)-----Chinese is not allowed

Password varchar(100)

User creation time varchar(50)

Database insert operation:
the

drop database if exists Java100;
create database if not Java100 character set utf8;
use Java100;
create table User(
userID int primary key auto_increment,
userName varchar(50) unique not null,
loginName varchar(60) unique not null,
passWord varchar(90) unique not null,
sex varchar(30) default "male",
address varchar(60),
qq varchar(60),
email varchar(40),
isAdmin int default 0,
createTime datetime default Now(),
updateTime datetime default Now()
);

Import dependencies:

1)SpringBootDevTools

2)Lombok

3)SpringWeb

4)MyBatisFrameWork

5)MySQL Dirver

6) Interceptor

3) Configure the configuration file:

#The following is the basic information to configure the database connection
spring.datasource.username=root
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/Java100?characterEncoding=utf-8&useSSL=true
spring.datasource.password=12503487
#The following is the save path of the configuration database XML file
mybatis.mapper-locations=classpath: mapper/**.Mapper.xml
#Configure the SQL printed by MyBatis
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
logging.level.com.example.demo=debug


We specified the path of mapper's xml file in the configuration file, and in our xml, we specified the path of the interface modified by mapper through namespace

4) To handle the same exception, we can put it in the Configuration file for a unified file that is globally effective

/Handle unified exceptions
@ControllerAdvice
public class ProcessException {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public HashMap<String,Object> Start(Exception e){
        //What we return this time is data in JSON format
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("status",200);
        hashMap.put("data","");
        hashMap.put("state",-1);
        hashMap.put("message",e.getMessage());
        return hashMap;
    }
}

5) Return principle: All interfaces must have a unified data format to return

If we want to return a unified data format, there are two methods:

1) Define a global return object, which is called when each interface returns

2) The Advice interface is enhanced to achieve unified data encapsulation

return JSON formatted data:
{
status:status code
data:The data returned by the backend
state:-1/1
message:is true status A corresponding statement of the return status, such as login failure, wrong username and password, and empty username and password
}

6) Configure the interceptor

public class ProcessLogin implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //If the return value of this method is true, it means that the current user has logged in, so you can directly access the target method
        //If the return value of this method is false, it means that the current user has not logged in, then it will directly jump to the login interface
        HttpSession httpSession= request.getSession(false);
        if(httpSession==null||httpSession.equals("")||httpSession.getAttribute("user")==null||httpSession.getAttribute("user").equals("")){
           response.sendRedirect("login.html");
            return false;
        }
        return true;
    }
}
//Register this in Spring
@Configuration
class InsertSpringBoot implements WebMvcConfigurer{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ProcessLogin())
                .addPathPatterns("/**")
                .excludePathPatterns("/css/**")
                .excludePathPatterns("/fonts/**")
                .excludePathPatterns("/images/**")
                .excludePathPatterns("/js/**")
                .excludePathPatterns("/css/**")
                .excludePathPatterns("/**/login.html");
    }
}

7) Put all the front-end files under the static directory

8) Create entity classes based on database tables

@Data
public class User {
    private int userID;
    private String userName;
    private String loginName;
    private String passWord;
    private String sex;
    private String address;
    private String qq;
    private String email;
    private String isAdmin;
    private Timestamp createTime;
    private Timestamp updateTime;

}

 

In addition, we have to insert a record into the database

1. Realize the login function: we need to perform it according to the user name and password passed by the front end

2. Realize adding functions: There are two interfaces for interacting with the backend

1) The interface to obtain the login authority of the current user (whether it is a super administrator or an ordinary administrator) (unified login interception will be done later)

2) Click Add to realize the add function

In our adding function, ordinary administrators can add ordinary administrators, but super administrators cannot be added, but our super administrators can add anything;

Display the login screen according to the user's identity:

3) In our front-end button, there is an option displayed to our super administrator. When performing the add operation, the super administrator clicks Yes or No. The content of this part is a div tag, so when the user logs in Afterwards, when loading our added page, our front end needs to send an Http request to the back end, the back end needs to obtain the User object according to the HttpSession object, the back end returns the IsAdmin field in the User object, and then the front end gets the back end again The returned parameter determines whether to display the div tag according to the value of IsAdmin

4) Our front-end directly uses the Jquery("#adminDiv").show() method to decide whether to display this part of the content, and we want to hide the call to the hide() method

Perform an insert operation:

1) On our front end, we directly obtain the login name, user name, password, confirmation password, age, QQ, email address, determine whether they are empty, and check whether the password and confirmation password are consistent

2) Pass these parameters to our backend. If the addition operation is successful, we will return a 1, and if it fails, we will return a number 0

3) Here we still have to pay attention, we have several controls

1. For example, we want to get controls such as gender

<input id="man" type="radio" name="sex" value="male" checked="checked">male
<input id="women" type="radio" name="sex" value="Female">Female
 When our radio button name when the attributes are the same,we can select

How should we implement it?  

For the above controls:

jQuery("input[name=sex]:checked").val();
1)pass first name to obtain radio control
2)checked get the selected control
3)val()The method can get gender information because input have inside value Attributes

2. We also need to get the native place control:

<select name="address" id="address" class="form-control">
    <option value="Beijing">Beijing</option>
    <option value="Shanghai">Shanghai</option>
    <option value="Guangzhou">Guangzhou</option>
</select>
jQuery("#address").val
 according to id to get the value

 When our user performs the adding operation, when the backend continues to insert, if the parameter User object requested by the front end, when the IdAdmin of the User object is 1, it indicates that the current user is an administrator, and he wants to add an administrator Operation, we want to verify that the currently logged in user is an administrator! ! ! ! We judge by the Session object in HttpSession:

Implement the modification operation:

At present, our project cannot modify the super administrator, and our login name cannot be modified

1) Obtain UserID from our url (front end)

2) Display information (display user information)

3) The user edits the information and then submits the information

Security issues involved:

When displaying the page again, it is necessary to obtain the verification of the user's login permission and the verification of the viewing permission. Ordinary administrators cannot view the super administrator's information (backend), and ordinary users cannot edit the super administrator. of information

When we edit and submit information, we also need to verify the above two steps

Tags: MySQL Database Mybatis

Posted by keithschm on Wed, 16 Nov 2022 08:31:57 +1030