【SpringBoot】| SpringBoot and web components

Table of contents

One: SpringBoot and web components

1. Use interceptor Interceptor in SpringBoot (emphasis)

2. Using Servlet in SpringBoot

3. Use Filter in SpringBoot (emphasis)

4. Application of character set filter

 Book recommendation: "Silicon-Based Story·I am a Soul Painter"


One: SpringBoot and web components

1. Use interceptor Interceptor in SpringBoot (emphasis)

An interceptor is an object in SpringMVC that can intercept requests to the Controller!

There are systematic interceptors in the interceptor framework, and interceptors can also be customized to achieve pre-processing of requests!

Implement a custom interceptor:

Step 1: Create a class that implements the HandlerInterceptor interface of the SpringMVC framework and override the method.

There are three default methods in the HandlerInterceptor interface source code, which are commonly used to intercept in the preHandle method:

package org.springframework.web.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;

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 {
    }
}

Write the LoginInterceptor class to implement the HandlerInterceptor interface, and rewrite the preHandler method

package com.zl.web;

import org.springframework.web.servlet.HandlerInterceptor;

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

// 自定义拦截器
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * @param request
     * @param response
     * @param handler 被拦截的控制器对象
     * @return boolean,true:表示请求能被Controller处理,false:表示被截断
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception { // handler是被拦截的控制器对象

        System.out.println("请求拦截器执行了");
        return true;
    }
}

Step 2: Register the statement interceptor in SpringBoot

Register statement interceptor in SpringMVC framework

<mvc:interceptors>
	<mvc:interceptor>
    	<mvc:path="url" />
        <bean class="拦截器类全限定名称"/>
    </mvc:interceptor>
</mvc:interceptors>

Register statement interceptor in SpringBoot framework

(1) Use the method of class + annotation to write a class to implement the WebMvcConfigurer interface ( this interface is very important, many functions related to SpringMVC are here ) , and add @Configuration annotations , all functions related to SpringMVC are implemented in the WebMvcConfigurer interface up!

(2) Rewrite the addInterceptors method , add the interceptor object in the method, and inject it into the container; then call addPathPatterns to add the intercepted request, and then call excludePathPatterns to exclude the intercepted request.

package com.zl.config;

import com.zl.web.LoginInterceptor;
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;

@Configuration // 这个类当做配置文件使用
public class MyAppConfigurer implements WebMvcConfigurer {
    // 添加拦截器对象,注入到容器中
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 创建拦截器对象
        HandlerInterceptor interceptor = new LoginInterceptor();
        // 调用addInterceptor方法表示注入到容器中
        // 调用addPathPatterns方法表示可以拦截的请求
        // 调用excludePathPatterns方法表示通过的请求
        registry.addInterceptor(interceptor)
                .addPathPatterns("/user/**")
                .excludePathPatterns("/user/login");
    }
}

Step 3: Write a controller for access

package com.zl.controller;

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 "访问user/account地址";
    }

    @RequestMapping("/user/login")
    @ResponseBody
    public String userLogin(){
        return "访问user/login地址"; // 会被通过
}

2. Using Servlet in SpringBoot

Use Servlet objects in the SpringBoot framework!

Steps for usage:

② Create a Servlet class that inherits from the HttpServlet class .

Register the Servlet so that the framework can find the Servlet.

Step 1: Create a Servlet class that inherits from HttpServlet

Rewrite the doGet and doPost methods, and call the doPost method in doGet, so that there is no problem whether it is a post request or a get request!

package com.zl.web;

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 request, HttpServletResponse response)
            throws ServletException, IOException {
        // 调用doPost方法
       doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 使用HttpServletResponse输出数据,应答结果
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("执行的是Servlet");
        out.flush();
        out.close();
    }
}

Step 2: Register the Servlet so that the framework can find the Servlet

(1) ServletRegistrationBean is used to register servlets in servlet 3.0+ containers , but it is more SpringBean-friendly.

(2) First write a class with a random class name and @Configuration annotation to indicate that this class is a class of configuration information; then write a servletRegistrationBean() method in the class , and the return value is a ServletRegistrationBean object

(3) Add the @Bean annotation . @Bean is used to store objects in the spring ioc container. It is the same as @controller, @Service, @Component, @Configuration, @Repository and other annotations, and is responsible for storing objects in the container. It’s just that the method is different. The four annotations are used on the class, and then the current class is created through the no-argument constructor and then put into the container; while @Bean is used on the method , the return value object of the current method is placed in In the container ! It can be understood that the former is automatically created by spring, while @Bean creates objects to be controlled by ourselves.

package com.zl.config;

import com.zl.web.MyServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServlet;

@Configuration
public class WebAppConfig {
    // 定义方法,注册Servlet对象
    @Bean // 把ServletRegistrationBean对象放到容器当中
    public ServletRegistrationBean servletRegistrationBean(){
        // 创建ServletRegistrationBean对象,有两个参数:
        // 一个参数是servlet,一个参数是url地址
        HttpServlet servlet = new MyServlet();
        ServletRegistrationBean bean = new ServletRegistrationBean(servlet,"/myservlet");
        return bean;
    }
}

Of course, you can also use the parameterless construction method, call the reference.set method for assignment, and you can also assign multiple paths

ServletRegistrationBean bean = new ServletRegistrationBean();
bean.setServlet(servlet);
bean.addUrlMappings("/login","/test"); // 多个路径都可以访问

3. Use Filter in SpringBoot (emphasis)

Filter is a filter in the Servlet specification, which can process requests and adjust the parameters and attributes of requests;  character encoding is often processed in filters .

Steps for usage:

①Create a custom filter class;

② Register the Filter object;

Note: Simple understanding of filters and interceptors

(1) Filters are used to filter request or response parameters (for example: add some garbled characters), focusing on data filtering;

(2) The interceptor is used to verify the request and can truncate the request!

Step 1: Create a custom filter class

Create the MyFilter class to implement the Filter interface , rewrite the doFilter method , and process it; after processing, call the doFilter method of the filterChain parameter , pass the request , and continue to the next step.

package com.zl.web;

import javax.servlet.*;
import java.io.IOException;
// 自定义过滤器类
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, 
                         ServletResponse response, 
                         FilterChain filterChain) throws IOException, ServletException {
       // 处理字符集编码
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("Filter过滤器执行了");
        // 把请求转发出去
        filterChain.doFilter(request,response);
    }
}

Step 2: Register the filter object

Write a configuration class with a random class name and @Configuration annotation to indicate that this class is a configuration information class; write a filterRegistrationBean () method in the class , the return value is a FilterRegistrationBean object, and add @Bean annotation to the method , and hand over the returned object to the Spring container for management.

package com.zl.config;

import com.zl.web.MyFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.FilterRegistration;

@Configuration
public class WebApplicationConfig {
    @Bean
    public FilterRegistrationBean filterRegistrationBean (){
        // 调用无参数构造方法
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new MyFilter()); // 指定过滤器对象
        bean.addUrlPatterns("/user/*"); // 指定过滤的地址
        return bean;
    }
}

Write a controller for access

package com.zl.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CustomerFilterController {
    @RequestMapping("/user/account")
    @ResponseBody
    public String userAccount(){
        return "user/account执行了";
    }
}

4. Application of character set filter

CharacterEncodingFilter: Solve the problem of garbled characters in post requests; in the SpringMVC framework, register filters in web.xml, configure its properties, and solve the problem of garbled characters!

Create a Servlet

package com.zl.servlet;

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 request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("在Servlet中使用中文");
        out.flush();
        out.close();
    }
}

Register Servlet

package com.zl.web;

import com.zl.servlet.MyServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;

@Controller
public class WebAppConfig {
    // 注册Servlet
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        MyServlet myServlet = new MyServlet();
        ServletRegistrationBean bean = new ServletRegistrationBean(myServlet, "/myservlet");
        return bean;
    }
}

Make a visit: Found Chinese garbled characters

F12, refresh the request and open it, and found that the default encoding method is: ISO-8859-1

The first solution: custom filter, more troublesome, not recommended

① Add a filter to the registered Servlet

package com.zl.web;

import com.zl.servlet.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.filter.CharacterEncodingFilter;


@Controller
public class WebAppConfig {
    // 注册Servlet
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        MyServlet myServlet = new MyServlet();
        ServletRegistrationBean bean = new ServletRegistrationBean(myServlet, "/myservlet");
        return bean;
    }

    // 注册Filter
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean bean = new FilterRegistrationBean();

        // 使用框架中的字符过滤器
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        // 指定使用的编码方式
        filter.setEncoding("UTF-8");
        // 指定request,response使用encoding的值
        filter.setForceEncoding(true);
        // 给filter设置参数
        bean.setFilter(filter);
        bean.addUrlPatterns("/*"); // 过滤所有的地址
        
        return bean;

    }
}

② Modify the application.properties file to make the custom filter work

By default, the system configuration is used

Let your configuration take effect 

(1) The CharacterEncodingFilter has been configured and enabled by default in SpringBoot, and the encoding defaults to ISO-8859-1;
(2) The function of setting enabled=false is to close the configured filter in the system and use the custom CharacterEncodingFilter;

server.servlet.encoding.enabled=false

The second way: directly use the filter in the framework, which is relatively simple and recommended

Note: In fact, SpringBoot has automatically included the character encoding filter into container management. Through source code analysis, it can be found that this configuration is bound to the server.servlet.encoding configuration in the configuration file application.properties.

package org.springframework.boot.autoconfigure.web.servlet;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.filter.OrderedCharacterEncodingFilter;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.boot.web.servlet.server.Encoding;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.filter.CharacterEncodingFilter;

@AutoConfiguration
@EnableConfigurationProperties({ServerProperties.class})
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
    prefix = "server.servlet.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
    private final Encoding properties;

    public HttpEncodingAutoConfiguration(ServerProperties properties) {
        this.properties = properties.getServlet().getEncoding();
    }

    // 自动装入了容器中去
    @Bean
    @ConditionalOnMissingBean
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
        return filter;
    }

    @Bean
    public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() {
        return new LocaleCharsetMappingsCustomizer(this.properties);
    }

    static class LocaleCharsetMappingsCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {
        private final Encoding properties;

        LocaleCharsetMappingsCustomizer(Encoding properties) {
            this.properties = properties;
        }

        public void customize(ConfigurableServletWebServerFactory factory) {
            if (this.properties.getMapping() != null) {
                factory.setLocaleCharsetMappings(this.properties.getMapping());
            }

        }

        public int getOrder() {
            return 0;
        }
    }
}

Modify the application.properties file directly to make changes

The first method: use a filter defined by yourself, and then let the system shut down and make your own take effect, which is more troublesome;

The second method: use the system that has been configured, we can directly modify the encoding method of the internal parameters;

#让系统的CharacterEncdoingFilter生效,默认就是开启的,不写也行
server.servlet.encoding.enabled=true
#直接指定使用的编码方式
server.servlet.encoding.charset=utf-8
#直接强制request,response都使用charset属性的值
server.servlet.encoding.force=true

Book recommendation: "Silicon-Based Story·I am a Soul Painter"

When AI meets painting, what kind of wonderful world will it open?

Use ChatGPT+Midjourney to explore human souls and dreams

Use StableDiffusion+D-ID to draw youthful and gorgeous desire

Activate everyone's hidden drawing talent

                                                        Everyone can become a top painting master​​​​​​​​

        If you ask me my attitude towards AI painting, I will tell you: new things are powerful, and they will eventually develop rapidly and replace old things. This is not to say that AI paintings will replace previous human painting achievements and artistic results, but as a "filter" that constantly filters impurities in the field of painting, improves the overall level of human painting, and contributes to human life. occupy an increasingly important position.

        In the future, AI will become the most handy "paintbrush" for human beings, helping people become "magic brush Ma Liang". Even an ordinary person can become a top painter with the help of AI.

brief introduction

        A guide for exploring the secrets of AI painting. Through rich practical case operations, it tells the generation steps of AI painting in an easy-to-understand manner, vividly demonstrating the magical charm of AI painting. From history to the future, spanning a century of time and space, from theory to practice, it tells about case operations: from technology to philosophy, across multiple dimensions, from language to painting, and practical exercises. The birth of AI painting triggered the advent of the singularity, lighting up AGI (General Artificial Intelligence), and involved a series of detailed explanations such as Prompt, style, technical details, multi-modal interaction, and AIGC. Let you easily master the drawing skills, create unique works of art, and write your own art era.

Dangdang link : http://product.dangdang.com/29601870.html

Guess you like

Origin blog.csdn.net/m0_61933976/article/details/129334421