springboot Computer Shop Project 3. User Login

When a user enters a username and password to submit data to the background database for query, if there is a corresponding username and password, the login is successful. After successful login, the user jumps to the homepage index of the system. HTML page. Jump is done on the front end using jquery

1. Logon-Persistence Layer

1.1 Planning sql statements to execute

select queries based on user name and password submitted by the user. Password comparisons are performed at the business level.

select * from t_user where username = ?

Note: If a module is found to have been developed during the analysis, the current development steps can be omitted. This analysis process cannot be omitted.

1.2 Interface Design and Abstract Methods

There is no need for redevelopment. Unit tests do not need to be executed separately

2. Login-Business Tier

2.1 Planning Exceptions

  1. PasswordNotMatchExecution exception, runtime exception, business exception.
  2. The user name was not found and an exception was thrown: UsernameNotFountException
  3. Exception writing:
    • Business-tier exceptions need to inherit the ServiceException exception class
    • Define construction methods in specific exception classes (five construction methods can be generated using shortcuts).

2.2 Design business-tier interfaces and abstract methods

1. Write an abstract method, login(String username,String password) directly in the IUserService interface. Returns the currently logged-in successful user data as the current user object. State management: You can save data in a cookie or session to avoid frequent database operations (user name, user id-stored in session, user avatar-cookie).

2. The abstract method in the parent interface needs to be implemented in the implementation class.

3. Test in the test class whether the business-tier login method can be executed and passed.

2.3 Implementation of abstract methods

public User login(String username, String password) {
        //Query for existence of data based on user name, throw exception if not
        User result = userMapper.findByUsername(username);
        if (result == null){
            throw new UserNotFoundException("User data does not exist");
        }

        //Detect if the user's password matches
        //1. Get the encrypted password in the database first
        String oldPassword = result.getPassword();
        //2. Compare with the password passed by the user
        //2.1 Get the salt value first, which was automatically generated the last time you registered
        String salt = result.getSalt();
        //2.2 Encrypt the user's password according to the same md5 algorithm rules
        String newMd5Password = getMD5Password(password, salt);
        if (!oldPassword.equals(newMd5Password)){
            throw new PasswordNotMatchExecption("Password error");
        }

        //Judging is_ Whether the delete field has a value of 1 or not indicates that it is marked for deletion
        if (result.getIsDelete() == 1){
            throw new UserNotFoundException("User data does not exist");
        }

        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar());
        return user;
    }

3. Login-Control Layer

3.1 Handling Exceptions

What exceptions thrown by the business layer need to be captured and handled uniformly in the uniform exception handling class. If the type of exceptions thrown has already been handled in the exception handling class, there is no need to add them again

else if (e instanceof UserNotFoundException){
    result.setState(5001);
    result.setMessage("No exceptions exist for user data");
} else if (e instanceof PasswordNotMatchExecption){
    result.setState(5002);
    result.setMessage("User name password error");
}

3.2 Design Request

 Request path:/user/login
 Request Method:POST
 Request data:String username,String password,HttpSession session
 Response results:JsonResult<User>

3.3 Processing Requests

Write methods to handle requests in the UserController class.

@RequestMapping("login")
public JsonResult<User> login(String username,String password){
    User data = iUserService.login(username, password);
    return new JsonResult<User>(OK,data);
}

4. Login-Front End

1. In login. An ajax request is sent from an HTML page based on the request you set up earlier.

2. Access the page for user login

User logon session

The session object is mainly stored on the server side and can be used to store temporary data of the server. The stored data can be accessed throughout the project, and the session data can be viewed as a shared data. User data obtained during the first logon can be transferred to the session object. session.getAttrbute("key") encapsulates the behavior of getting data from a session and encapsulates it in the BaseController class.

1. Data acquisition in session object (encapsulated in parent class), data settings (data settings after successful user login, global session object settings)

2. Encapsulate two data in the parent class: uid and username. The two methods obtain two data corresponding to each other. User avatars are temporarily ignored and will be encapsulated for use in cookie s in the future.

/**
     * Gets the value of the user in the session object
     * @param httpSession session object
     * @return  Value of user uid currently logged in
     */
protected final Integer getUidFromSession(HttpSession httpSession){
    return Integer.valueOf(httpSession.getAttribute("uid").toString());
}

/**
     * Get the username of the currently logged in user
     * @param httpSession session object
     * @return User name of the currently logged in user
     * Override toString in parent class in implementation class, not handle information output
     */
protected final String getUsernameFormSession(HttpSession httpSession){
    return httpSession.getAttribute("username").toString();
}

3. Encapsulate the data in the session object in the login method. The server itself automatically creates a session object, which is already a global session object. springboot uses session objects directly and directly takes Httpsession type objects as parameters of request handling methods, automatically injecting global session objects into session parameters of request handling methods

@RequestMapping("login")
public JsonResult<User> login(String username, String password, HttpSession session){
    User data = iUserService.login(username, password);

    // Complete data binding to session object (session global)
    session.setAttribute("uid",data.getUid());
    session.setAttribute("username",data.getUsername());

    //Get data bound in session
    System.out.println(getUidFromSession(session));
    System.out.println(getUsernameFormSession(session));

    return new JsonResult<User>(OK,data);
}

Interceptor

Interceptor: First all requests are intercepted uniformly in the interceptor, in which filtering rules are defined. If this is not worth filtering rules for the system, uniform processing is to reopen login. For HTML pages (redirection and forwarding), redirection is recommended.

Definition and use of interceptors in the SpringBoot project. SpringBoot is implemented by springMvc, which provides a Handler Interceptor interface to represent an interceptor. First customize a class, then let the class implement the interface

1. First customize a class in which the HanderInterceptor interface is implemented.

public class LoginInterceptor implements HandlerInterceptor {
    //Prior to calling the method DispatherServlet before calling all requested methods
    //Only the first common use
    /**
     * Detects if uid data exists in the global session object, releases it if it does not redirect to the landing page
     * @param request Request Object
     * @param response Response Object
     * @param handler Processor: url + Controller: Mapping
     * @return If the return value is true, the current request will be released, and if false, the current request will be intercepted.
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //HttpServletRequest object to get session
        Object obj = request.getSession().getAttribute("uid");
        if (obj == null){
            //Indicates that the user has not logged on to the system, then redirects back to login.html page
            response.sendRedirect("/web/login.html");
            //Continued calls after completion
            return false;
        }

        //Request release
        return true;
    }
    //Method called after the ModelAndView object returns
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    //Method executed at the end of the entire request when all associated resources have been executed
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

Source Parsing

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

2. Registration filter: add blacklists (page resources that can be accessed when a user logs in) and whitelists (which resources can be accessed without logging in: login).

3. Techniques for registering filters: User-defined interceptors can be registered with the WebMvcConfoigure interface. Registration is required to ensure the effectiveness and use of the interceptor. Define a class and let it implement the WebMvcConfigurer interface. Configuration information is recommended to be stored under the config package structure of the project.

@Configuration//Load current interceptor and register
public class LoginInterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //Create custom interceptor object
        HandlerInterceptor interceptor = new LoginInterceptor();
        //Configure whitelist to be stored in a List collection
        List<String> patterns = new ArrayList<>();
        patterns.add("/bootstrap3/**");
        patterns.add("/css/**");
        patterns.add("/images/**");
        patterns.add("/js/**");
        patterns.add("/web/register.html");
        patterns.add("/web/index.html");
        patterns.add("/web/product.html");
        patterns.add("/web/login.html");
        patterns.add("/users/reg");
        patterns.add("/users/login");

        //Complete Interceptor Registration
        registry.addInterceptor(interceptor).
                addPathPatterns("/**").//Blacklist
                excludePathPatterns(patterns);//Set the Whitelist List collection into the interceptor.
    }
}

4. Too many prompt redirections, login. The HTML page will not open. Delete cookies from the browser and set the browser to initialize

Keywords: Spring Boot

Added by ant peacocke on Wed, 02 Feb 2022 20:43:33 +0200