Spring MVC is an excellent application framework based on MVC thought. It is a sub-framework of Spring. Is the best MVC framework out there.

Spring Boot integration with Spring MVC is only introduced in pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.3.7. RELEASE</version>
</dependency>
Copy the code

Configure Spring MVC

Application. Yml example:

server:
  port: 8080 # Web service port number
  servlet:
    multipart:
      enabled: true # Enable file upload
      location: # Upload file temporary save location
      max-file-size: 50MB # Maximum upload size of a single file
      max-request-size: 100MB Maximum size limit for a single request body
  mvc:
    format:
      date: yyyy-MM-dd # date format
      date-time: yyyy-MM-dd HH:mm:ss # datetime format
      time: HH:mm:ss # time format
    servlet:
      path: / # servlet path
      static-path-pattern: Match static resource paths
    view:
      prefix: # view prefix
      suffix: # view suffixes such as.jsp
Copy the code

These are common Spring MVC configurations. For more information, see Spring Boot Web Properties


In addition to the above configuration of Spring MVC in application.yml, it can also be implemented in Java code. This approach is more flexible.

Configuring Spring MVC in Spring Boot using Java code is simple, simply by implementing the corresponding methods in the WebMvcConfigurer interface.

@Configuration
public class WebConfiguration implements WebMvcConfigurer {}Copy the code

MVC configuration classes and interfaces in Spring Boot:

  1. WebMvcConfigurer interface
  2. WebMvcConfigurerAdapterWebMvcConfigurer implementation class (deprecated)
  3. WebMvcConfigurationSupport basic implementation of the MVC and contains WebMvcConfigurer methods on the interface
  4. The WebMvcAutoConfiguration MVC is automatically installed in the class and partially contains the methods in the WebMvcConfigurer interface

The following lists the common configuration methods for WebMvcConfigurer:

The interceptor

Load blockers are generally used for unified operations such as login verification and permission authentication.

@Override
public void addInterceptors(InterceptorRegistry registry) {registry. AddInterceptor (custom interceptor). AddPathPatterns (blocked paths); }Copy the code

The custom interceptor inherits the HandlerInterceptor interface.

Cross domain set

@Override
public void addCorsMappings(CorsRegistry registry) {
	registry.addMapping("/ * *") // The path to allow cross-domain access
			.allowedOrigins("*")// Allow cross-domain access to the source
			.allowedMethods("POST"."GET"."PUT"."OPTIONS"."DELETE") // allow request methods
			.maxAge(86400) // Precheck interval time
			.allowedHeaders("*") // Allow header setting
			.allowCredentials(true); // Whether to send cookies
}
Copy the code

If you set cross-domain in the interceptor request, this does not take effect.

Mapping static Resources

Used to map resources such as images, JS, CSS files, etc., to access these static resources without going through the interceptor.

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
	registry.addResourceHandler("/ * *").addResourceLocations("classpath:/statics/");
	super.addResourceHandlers(registry);
}
Copy the code

Message converter

Spring MVC when serialization and deserialization, mostly used for parameter conversion. For example, customize the date format and replace the default Jackson with gson for JSON conversion.

@Override
public void configureMessageConverters(List
       
        > converters)
       > {
	MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
	ObjectMapper objectMapper = new ObjectMapper();
	/** * change all longs to string * because numeric types in JS cannot contain all Java long values */
	SimpleModule simpleModule = new SimpleModule();
	simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
	simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
	simpleModule.addSerializer(Date.class, DateSerializer.instance);

	objectMapper.registerModule(simpleModule);

// objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
	objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
	objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

	jackson2HttpMessageConverter.setObjectMapper(objectMapper);
	converters.add(0, jackson2HttpMessageConverter);
}

@Override
public void extendMessageConverters(List
       
        > converters)
       > {}Copy the code

ConfigureMessageConverters will cover system of converter, and extendMessageConverters won’t.

A custom Converter implements the Converter interface.

Formatting data

When you look at this approach, you’ve previously used Converter for date formatting, and you can use it specifically for data formatting. The Formatter interface needs to be implemented.

@Override
public void addFormatters(FormatterRegistry registry) {
	DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
	registrar.setTimeFormatter(DateTimeFormatter.ofPattern(DatePattern.NORM_TIME_PATTERN));
	registrar.setDateFormatter(DateTimeFormatter.ofPattern(DatePattern.NORM_DATE_PATTERN));
	registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
	registrar.registerFormatters(registry);
}
Copy the code

Parameter parser

Spring MVC automatically wraps the parameters when the request enters the Controller method. Parameters can be realized through the interface HandlerMethodArgumentResolver custom packaging. For example, verify signatures through custom annotations.

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
	resolvers.add(new VerifySignatureResolver());
}
Copy the code

View parser

The view parser determines the type and pattern of data returned by the Controller. Multiple values can be configured, with a smaller order value preferred.

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {

	// JSP view parser
	InternalResourceViewResolver jspView = new InternalResourceViewResolver();
	jspView.setOrder(1);
	jspView.setPrefix("/WEB-INFO");
	jspView.setSuffix(".jsp");
	registry.viewResolver(jspView);

	// xml
	XmlViewResolver xmlView = new XmlViewResolver();
	xmlView.setOrder(2);
	registry.viewResolver(xmlView);
}
Copy the code

Simple automatic controller

Some simple page hops, such as the login page. You don’t have to write it in Controller, you can add it here.

@Override
public void addViewControllers(ViewControllerRegistry registry) {
	registry.addViewController("/hello").setViewName("/hello");
	// More can be added
}
Copy the code

More configurations can be found in this document: WebMvcConfigurer


Unless otherwise noted, these are original articles by Siege lion. Link to this article: engr-z.com/88.html