Springboot custom component

Springboot custom component

Before talking about custom components, we should first understand what each component does and what role it plays in the project operation. In this way, we know when and how to configure components, so we need to understand the running process of spring MVC first


The core of spring MVC lies in its process. It is a Servlet technology. It provides the core controller dispatcher Servlet and related components, and formulates a loose structure; In order to give you a general understanding of spring MVC, first give the flow chart of receiving requests, processing requests, and finally responding to browsers;

  1. Send a request to the front-end controller DispatcherServlet
  2. Find the corresponding processor through processor mapping, generate processor object and processor, and interceptor
  3. To run the processor, you need a corresponding environment (adapter). The adapter will run the corresponding processor (including the content of the controller and other enhanced functions) and interceptor
  4. The processor returns the model and view to the dispatcher servlet after execution
  5. The dispatcher servlet passes the model to the view parser
  6. After parsing, the view parser renders the model to the view
  7. Finally, the view is responded to the user

Try to go through it quickly with your own understanding: the request is mapped to the dispatcherServlet, mapped to the corresponding handler and Interceptor through handlerMapping, executed through HandlerAdapter, returned to the corresponding ModelAndView, parsed with ViewResolver, generated a view and responded to the user;

If you have time, you can see the front-end parser, view parser, context listener and interceptor configured manually in the SSM framework

It's enough to understand several components of spring MVC. The configuration of springmvc-servlet.xml is not written. After all, springboot is automatically configured now.

For spring MVC process and configuration, please refer to this article: https://blog.csdn.net/floating_dreaming/article/details/89089214

SpringBoot interceptor

Configure the custom springmvc component into Springboot:

  1. Customize an interceptor MyInterceptor
    1. Inherits the HandlerInterceptor interface
    2. Implement corresponding methods
    3. Write the conditions that pass through the interceptor in the method
  2. Custom webMvcConfig
    1. Inherit WebMvcConfigurer interface
    2. Implement the addInterceptor method
    3. Define the path to be intercepted and the path not to be intercepted in the method
//Create interceptors and implement interceptor methods.
public class LoginInterceptor implements HandlerInterceptor {
  	//Execute the operation before the request is sent to the controller. If true is returned, it is equal to release.
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //Join logical operations, such as login verification before requesting specified path processing
        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");
        if (username == null || username.equals("")){
            request.setAttribute("msg", "No permission, please log in first");
            request.getRequestDispatcher("/index").forward(request, response);
            return false;
        return true;

  	//Used to perform an action before sending a response to the client.
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

  	//Used to perform actions after requests and responses are completed
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
public class LoginMVCConfig implements WebMvcConfigurer {

  	//Create an interceptor instance bean and add it to the container
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();

    public void addInterceptors(InterceptorRegistry registry) {

        //The interceptor will also intercept static resources by default, so we need to open the relative path of static resources; There must be our login page
                .excludePathPatterns("/","/index","/css/**", "/js/**", "/img/**");

  	//Page Jump. When we request the / index path, it will be automatically mapped to the index view
    public void addViewControllers(ViewControllerRegistry registry) {
      	//On the premise that the index page is placed in the default parsing position of the view parser, the view parsing can be configured in the configuration file. Of course, this annotation can also be used 		 Mode configuration

The above is an example of adding an interceptor. A component is customized on the springboot. In fact, the components in the springboot have a default configuration, which is automatically configured. Only after we understand the role of each component, we can configure and add these components by ourselves and destroy its default configuration. In fact, this is very helpful for us to understand spring boot, write requirements, and solve bug s.

Finally, we need to inherit a WebMvcConfigurer class for any component we add custom in springboot, and then configure our component through the registry parameter in the corresponding method and add it to the container;

There are too many rewritable methods, but you can see that most of them are related components in the spring MVC running process, so as long as you know what each component does, it is actually good to configure the spring boot and add components. In fact, this is also the potential principle of springboot's automatic configuration, that is, encapsulate the components in SSM that need to be configured with xml configuration files, and then we just need to rewrite their methods when we need them.

Here is an article on the detailed explanation of webconfigurator (Rewriting of common methods): https://blog.csdn.net/zhangpower1993/article/details/89016503

Next article: import and export of excel

Tags: Java Spring Boot Spring MVC

Posted on Sun, 21 Nov 2021 15:16:01 -0500 by Hendricus