Spring Boot basic study notes 11: Spring MVC integration support in Spring Boot

Article Directory

Zero, learning goals

  1. Understand Spring MVC automatic configuration in Spring Boot
  2. Master Spring MVC function extension and customization in Spring Boot

In Web development, functions such as access support for static resources, configuration of view parsers, customization of converters and formatters, file upload and download, etc. are involved, and even the customization of Servlet-related components associated with the Web server needs to be considered. , Spring Boot framework supports the integration of some commonly used web frameworks to realize web development, and supports some common functions in web development by default.

One, Spring MVC automatic configuration

(1) Overview of automatic configuration

In the Spring Boot project, once the Web dependency starter is introduced spring-boot-starter-web, some XxxAutoConfigurationautomatic configuration classes implemented by Spring Boot integrated by the Spring MVC framework will automatically take effect, and Web development can be carried out almost without any additional configuration.

(2) Spring Boot integrates the automatic configuration features of Spring MVC

  1. Built-in two view resolvers: ContentNegotiatingViewResolverand BeanNameViewResolver;
  2. Support static resources and WebJars;
  3. The converter and formatter are automatically registered;
  4. Support Http message converter;
  5. The message code parser is automatically registered;
  6. Support static project homepage index.html;
  7. Support custom application icons favicon.ico;
  8. Automatically initialize the web data binder ConfigurableWebBindingInitializer.

Second, the implementation of Spring MVC function expansion

Insert picture description here

(1) Create a Spring Boot project-SpringMvcDemo2021

  • Use the Spring Initializr method to create a Spring Boot project, and select the Web dependency starter and Thymeleaf dependency starter in the Dependencies dependency selection
    Insert picture description here
    Insert picture description here
    Insert picture description here
    Insert picture description here

(2) Transform the current project-transplant the content of the previous project

  • Copy the html template file, international configuration file, global configuration file and related Java files (except entry files) of the 10th lecture case [Thymeleaf18N] to the corresponding location of the current project
    Insert picture description here
  • Start the application and check if it is successful
    Insert picture description here
  • Visit the login page-http://localhost:8080/toLoginPage
    Insert picture description here
  • Visit the show all users page-http://localhost:8080/allUsers
    Insert picture description here

(3) Write the MVC configuration file and define the view jump

1. Comment out the comment on the toLoginPage() method of the controller LoginController

Insert picture description here

2. Implement the interface WebMvcConfigurer and rewrite the addViewControllers method

Insert picture description here

package net.hw.lesson11.config;

import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import sun.misc.Contended;

/**
 * 功能:自定义MVC配置
 * 作者:华卫
 * 日期:2021年02月27日
 */
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    
    
     /**
     * 添加视图控制器
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    
        // 当通过login.html访问时,直接跳转到login视图对应的页面,即login.html页面
        registry.addViewController("login.html").setViewName("login");
        // 通过toLoginPage访问时,也直接跳转到视图名login对应的页面,login.html页面
        registry.addViewController("toLoginPage").setViewName("login");
    }
}
  • Note: The custom MVC configuration class must be annotated@Configuration
  • Note: In the toLoginPage() method, the attributes are set through the model currentYear, which will be passed to the front end when jumping to the login page, but directly through the view controller defined just now, there is no data transfer, therefore, the login page code must be modified , Do not display the year for the time being, so as not to report an error.

3. Modify the login page and comment out the code showing the year

Insert picture description here

3. Start the application and test the effect

  • accesshttp://localhost:8080/toLoginPage
    Insert picture description here
  • accesshttp://localhost:8080/login.html
    Insert picture description here
  • Both methods can jump to the login.html page, of course, the year is not displayed at this time.

(4) Write an interceptor to display the year on the login page

The role of the interceptor is to perform related processing before or after the access request, such as judging whether the user is logged in before accessing the resource, if it is logged in, it can be accessed, otherwise it cannot be accessed. In this case, the year data of the current year is obtained after the access request and brought to the login page to display it.

1. Implement the interface HandlerInterceptor and implement the postHandle() method

Insert picture description here
Insert picture description here

  • Note: The preHandle() method must be rewritten before the request is processed, the postHandle() method must be rewritten to process the request, and the afterCompletion() method must be rewritten after the request is completed.
package net.hw.lesson11.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;

/**
 * 功能:自定义拦截器
 * 作者:华卫
 * 日期:2021年02月27日
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
    
    
        request.setAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
    }
}

2. Rewrite the addInterceptors() method in MyMvcConfig to load a custom interceptor

Insert picture description here

3. Modify the login page and cancel the comment showing the year

Insert picture description here

  • Compilation will report an error, saying that it cannot be parsed currentYear, don't care about it, because the data does not come from the controller, but from the interceptor. The data can only be obtained after the runtime request, so the compilation will report an error.

4. Start the application and test the effect

  • accesshttp://localhost:8080/toLoginPage
    Insert picture description here
  • accesshttp://localhost:8080/login.html
    Insert picture description here
  • The year can be displayed in both ways, indicating that the postHandle() in the custom interceptor has taken effect.

(5) Write a login blocker to prevent non-login users from viewing all user information

  • It is required that users who are not logged in cannot view user information, but before defining the interceptor, http://localhost:8080/allUsersall user information can be seen through the path .
    Insert picture description here

1. Restore the annotations of the toLoginPage method in the login controller

Insert picture description here

2. Comment out the corresponding view controller in the custom MVC configuration

Insert picture description here

3. Modify the login() method in the login control

Insert picture description here

4. Rewrite the preHandle() method in the custom interceptor

Insert picture description here

  • Block non-login users, redirect them directly to the login page, and force them to log in

5. Exclude paths that cannot be intercepted in the custom MVC configuration file

Insert picture description here

6. Start the application and test the effect

Insert picture description here

  • Before http://localhost:8080/allUserslogging in , visit and jump directly to the login page. After logging in successfully, you can view all user information.

3. After-class development exercises

1. Modify the user entity class and add the password field

2. Transform the user string stored in the session into a user object

3. Use JPA and other methods to save the user in the database, and use the database to query user information and then log in to judge

Guess you like

Origin blog.csdn.net/howard2005/article/details/114162744