SpringBoot and web components

Posted by vbracknell on Wed, 08 Dec 2021 22:33:40 +0100

SpringBoot and web components

This chapter explains three contents: interceptor, servlet and filter

Interceptor

Interceptor is an object in spring MVC, which can intercept requests to Controller
There are system interceptors in the framework. You can also customize the interceptors to realize the pre-processing of requests

Implementing custom interceptors in spring MVC

  1. Create a class to implement the HandlerInterceptor interface of the spring MVC framework
    The interface information is as follows:
public interface HandlerInterceptor {
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

There are three methods, the most commonly used is the first method, preHandle
The preHandle method can intercept and preprocess the request and return a Boolean value. If true, it means that it can be processed after passing the verification of the interceptor. Otherwise, the request ends here

  1. The interceptor needs to be declared in the configuration file of spring MVC
<mvc:interceptors>
	<mvc:interceptor>
		<mvc:path="url">
		<bean class="Fully qualified name of interceptor class">
	</mvc:interceptor>
</mvc:interceptors>

The above code indicates that when the user accesses the url, he will first go to the interceptor to determine whether to intercept. The class of the interceptor class needs to be provided

Using interceptors in SpringBoot can turn the configuration information of the above xml file into a class
Look at the file structure first

  1. Custom interceptor object
    LoginInterceptor, which implements the interface HandlerInterceptor, indicating that the object is an interceptor, and the preHandle method needs to be rewritten to represent the interception logic
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * custom interceptor 
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     *
     * @param request
     * @param response
     * @param handler   Intercepted controller object
     * @return  Boolean
     *      true : The request can be processed by the Controller
     *      false : Request stage
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("The interceptor's judgment was performed");
        return true;
    }
}
  1. Write a configuration object that configures the interceptor, the url that needs to be intercepted, and the url that does not need to be intercepted
    @The Configuration annotation indicates that this object is a Configuration object and must be added
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.zjb.web.LoginInterceptor;

@Configuration
public class MyAppConfig implements WebMvcConfigurer {

    // This method is used to add interceptor objects and inject them into the container
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // Create interceptor object
        HandlerInterceptor interceptor = new LoginInterceptor();

        // Specify the url address of the intercepted request
        String[] path = {"/user/**"};
        // Specify the url address of the request that is not intercepted
        String[] excludePath = {"/user/login"};
        registry.addInterceptor(interceptor).
                addPathPatterns(path).
                excludePathPatterns(excludePath);
    }
}
  1. View layer
    There are two methods in this class, which access different URLs respectively. According to the interception logic in the configuration object, / user/account is intercepted and / user/login is not intercepted
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BootController {

    @RequestMapping("/user/account")
    @ResponseBody
    public String userAccount() {
        return "visit user/account address";
    }

    @RequestMapping("/user/login")
    @ResponseBody
    public String userLogin() {
        return "visit user/login address";
    }
}
  1. test
    When accessing / user/account, the preHandle() method in the interceptor always returns true and is not blocked


    Access to user/login is not blocked

servlet

Using Servlet objects in the springBoot framework
The previous steps are:

  1. Create a Servlet class that inherits HttpServlet
  2. Register the Servlet implementation class and inject the container so that the framework can find it

The steps of using servlet in SpringBoot are as follows:
The document structure is as follows:

  1. Create a Servlet implementation class, inherit HttpServlet, and implement doGet or doPost methods
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Use httpServletResponse to output data and response results
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("The implementation is Servlet");
        out.flush();
        out.close();
    }
}
  1. Create configuration class
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zjb.web.MyServlet;

@Configuration
public class webApplicationConfig {

    @Bean
    // Define methods and register Servlet objects
    public ServletRegistrationBean servletRegistrationBean() {

        // ServletRegistrationBean(T servlet, String... urlMappings)
        // The first parameter is the servlet object, and the second parameter is the url address
        ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(),
                "/myservlet");

        return bean;
    }
}
  • This class is decorated by @ Configuration, which means that this class is equivalent to a Configuration file
  • The servletRegistrationBean() method returns a bean object, which is a servlet
  • The servletRegistrationBean() method needs to be modified by @ Bean, indicating that the object needs to be created automatically
  • The ServletRegistrationBean(T servlet, String... urlMappings) method has two parameters. The first is the servlet entity class object, and the second is the collection of paths corresponding to the servlet (the second parameter is a variable length parameter, equivalent to an array)
    You can also use parameterless construction instead of two parameter construction
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new MyServlet());
        bean.addUrlMappings("/login", "/login1");
  1. Result display

filter

Filter is a filter that can process requests and jump the parameter attributes of requests. We often deal with character encoding in the filter
The creation method is very similar to Servlet
Also, first create a Filter object, and then register the Filter object through the FilterRegistrationBean
The document structure is as follows:

The steps are as follows:

  1. First create the filter object MyFilter class
import javax.servlet.*;
import java.io.IOException;

// Custom filter
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Yes MyFilter, doFilter");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
  1. Register the filter, that is, write the class WebApplicationConfig corresponding to the configuration file
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zjb.web.MyFilter;

@Configuration
public class WebApplicationConfig {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new MyFilter());
        bean.addUrlPatterns("/user/*");
        return bean;
    }
}
  1. Authoring view layers
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CustomFilterController {

    @RequestMapping("/user/account")
    @ResponseBody
    public String userAccount() {
        return "user/account";
    }


    @RequestMapping("/query")
    @ResponseBody
    public String queryAccount() {
        return "query";
    }
}
  1. detection result
    Access / user/account


    Access / query

Character set filter

Characterencoding filter: it is used to solve the problem of garbled code in post requests
In the spring MVC framework, register the filter in web.xml and configure its properties

Or just give an example:
The file structure is:

  1. Write a servlet first
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.println("stay Servlet Output Chinese in,Check for garbled code");
        out.flush();
        out.close();
    }
}
  1. Write configuration classes, register servlet s and character set filters
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.zjb.web.MyServlet;

@Configuration
public class WebConfig {

    // Register Servlet
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        MyServlet myServlet = new MyServlet();
        ServletRegistrationBean reg = new ServletRegistrationBean(myServlet, "/myservlet");
        return reg;
    }

    // Register Filter
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean reg = new FilterRegistrationBean();

        // Use the pre-existing character set filter class in the framework
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        // Specify encoding method
        filter.setEncoding("utf-8");
        // Specify the value of encoding for both request and response
        filter.setForceEncoding(true);

        reg.setFilter(filter);
        // Specify the url address of the filter
        reg.addUrlPatterns("/*");
        
        return reg;
    }
}
  1. Turn off the default filter in the application.properties file
server.port=8081

#By default, the character set filter has been configured in springboot. The default is ISO-8859-1
#Set to false to turn off the default filter
server.servlet.encoding.enabled=false
  1. View results

    No garbled code, very nice

In addition to the above methods, there is another method. As we said in step 3 above, there is a default character encoding set filter in SpringBoot. In fact, we can directly modify the default filter to complete this operation
You only need to configure it in the application.properties file

#Use the system's own filter. It is true by default and can be omitted
server.servlet.encoding.enabled=true
#Specifies the encoding used
server.servlet.encoding.charset=utf-8
#Force request.response to use the value of charset property
server.servlet.encoding.force=true

After this operation, you don't need to register the Filter

Topics: Java Front-end Spring Spring Boot SSM