“Offer comes, ask friends to take it! I am participating in the 2022 Spring Recruit Punch card campaign. Click here for more details.”

Third, login function development

The login page and Dashboard page can be obtained from the Bootstrap official website

Create a LoginController and add the login method to process login requests. In the login method, only the user name lilith and password pc12138 are required to return to the Dashboard page

@Controller
public class LoginController {

    @PostMapping("/user/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                        Map<String, Object> map){
        if ("lilith".equals(username) && "pc12138".equals(password)){
            // The login succeeds with the user name lilith and password pc12138
            return "dashboard";
        } else {
            // Login failed
            map.put("msg"."Username and password error");
            return "index"; }}}Copy the code

When validation fails, put the error message in the map and render the error message using the Thymeleaf template engine.

Change the login form submission address to /user/login and method to POST on the index. HTML page. Restart the application, go to localhost:8080, and enter the correct user name and password in the login form. Click login

Error 404, server error username does not exist

This is because there is no name attribute in the username and password input fields, and the body of the request does not have the username and password keys, so Spring MVC cannot get these two parameters.

The modification of THE HTML page may not take effect due to the Thymeleaf cache. You can enable the thymeleaf cache to be disabled

# disable thymeleaf cache
spring.thymeleaf.cache=false
Copy the code

The page needs to be recompiled after it has been modified.

Restart the application, enter the correct user name and password, and click Login

The dashboard page is displayed.

Return to the login page, enter the wrong username and password, and click Login

The login page is displayed again, and the error message defined in the login method is not displayed. To display error messages on the page, use the Thymeleaf template engine; You can refer to the official Thymeleaf documentation7.1 Simple Conditionals: “If” and “Unless”.

Please sign in Add the P label

<! Mysql > select * from user where username/password is not null
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
Copy the code

Restart the application, enter the wrong user name and password, and click LoginThe Thymeleaf template engine has successfully obtained the error message in the map and displayed it on the page.

Solve the problem of duplicate form submission

After a successful login, the page can be redirected to the Dashboard page, but the URL of the browser is still user/login, which is the address for submitting the form. If you refresh the home page, you will be prompted to submit the form again.

The best way to solve this problem is to redirect to the Dashboard page instead of returning directly to the Dashboard page, first adding a view map

public void addViewControllers(ViewControllerRegistry registry) {
    // The browser sends /lilith to the SUCCESS page
    registry.addViewController("/lilith").setViewName("success");
    registry.addViewController("/").setViewName("index");
    registry.addViewController("/index.html").setViewName("index");
    registry.addViewController("/dashboard").setViewName("dashboard");
}
Copy the code

Change the login method to redirect to Dashboard

@PostMapping("/user/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                    Map<String, Object> map){
    if ("lilith".equals(username) && "pc12138".equals(password)){
        // The login succeeds with the user name lilith and password pc12138
        // To prevent form submission, redirect to dabshboard
        return "redirect:/dashboard";
        
    } else {
        // Login failed
        map.put("msg"."Username and password error");
        return "index"; }}Copy the code

After restarting the application and testing again, the browser’s address is no longer the address for the form submission, the form submission problem does not occur, and the resource loading problem is resolved.

But there is still a problem, that is, the page does not do permission control, that is to say, in the browser to enter this address can directly enter the page without login, not to mention there is no login prompt; At this point, you can use the interceptor to check for login, and only after login can you enter the page.

Before doing this, you need to modify the login method to save the login user information in the session

@PostMapping("/user/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                    Map<String, Object> map, HttpSession session){
    if ("lilith".equals(username) && "pc12138".equals(password)){
        // The login succeeds with the user name lilith and password pc12138
        // To prevent form submission, redirect to dabshboard
        session.setAttribute("currentUser",username);
        return "redirect:/dashboard";

    } else {
        // Login failed
        map.put("msg"."Username and password error");
        return "index"; }}Copy the code

Next, create a new login interceptor under the Config package

public class LilithHandlerInterceptor implements HandlerInterceptor {
    // Before the target method is executed
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Get the login user in session
        Object currentUser = request.getSession().getAttribute("currentUser");
        if (currentUser == null) {// No login, intercept
            request.setAttribute("msg"."Please log in first.");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        } else {
            // The user has logged in
            return true; }}}Copy the code

Register interceptors in the LilithMvcCofnig configuration class in the config package

// Register interceptors
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LilithHandlerInterceptor())
            .addPathPatterns("/ * *")
            .excludePathPatterns("/index.html"."/"."/user/login");
}
Copy the code

Restart the application, enter http://localhost:8080/dashboard in the firefox browser

If the login page is displayed, the interceptor takes effect, but the page style is lost. In this case, static resources are also blocked, and you need to permit static resources

Modify the registered interceptor

// Register interceptors
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LilithHandlerInterceptor())
            .addPathPatterns("/ * *")
            .excludePathPatterns("/index.html"."/"."/user/login"."/asserts/**"."/webjars/**");
}
Copy the code

Restart the application, the browser to enter http://localhost:8080/dashboard again

The page style is normal

Rest-style URL definitions

REST is a software architectural style, or specification, that emphasizes that HTTP should be resource-centric and regulates URI styles; The HTTP request action (GET/PUT/POST/DELETE/HEAD/OPTIONS), the use of corresponding semantic.

Define THE URL of THE CRUD according to the REST style

operation URI Method
Query all list GET
Query a single employee/{id} GET
Enter the Add page. employee GET
Add operation empployee POST
Enter the Modify page. employee/{id} GET
Modify the operating employee PUT
Delete operation employee/{id} DELETE