current position:Home>Springboot summary on date and time formatting processing

Springboot summary on date and time formatting processing

2022-05-15 05:22:07Migrant worker brother

Click below “Java Programming duck ” Follow and mark the stars

More exciting First time direct

source :juejin.im/post/5e62817fe51d4526d05962a2

Project use LocalDateTime Series as DTO Data type of time in , however SpringMVC Error is always reported after receiving parameters , To configure the global time type conversion , The following processing methods have been tried .

notes : This article is based on Springboot2.x test , If it doesn't work, it may be spring Caused by lower version .

If your Controller Medium LocalDate Type Parameter annotation (RequestParam、PathVariable etc. ) None , It can go wrong , Because by default , This parameter is parsed using ModelAttributeMethodProcessor To deal with , The processor instantiates an object through reflection , Then, the parameters in the object are convert, however LocalDate Class has no constructor , Unable to reflect instantiation, so an error will be reported !!!

Achieve the goal

  • The request for admission is String( Specify the format ) turn Date, Support get、post(content-type=application/json)

  • The returned data is Date Type to the specified date time format character

  • Support Java8 date API, Such as :LocalTime、localDate and LocalDateTime

GET Requests and POST Form date time string format conversion

This situation should be related to time Json Treat strings differently , Because the front json To back end pojo The bottom layer uses Json serialize Jackson Tools (HttpMessgeConverter); When the time string is passed in as a normal request parameter , The conversion uses Converter, There is a difference in the way the two are handled .

Use custom parameter converter (Converter) Realization org.springframework.core.convert.converter.Converter, Custom parameter Converter , as follows :

@Configuration
public class DateConverterConfig {
    @Bean
    public Converter<String, LocalDate> localDateConverter() {
       return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String source) {
                return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }
        };
    }

    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        };
    }
}

comment : The above two bean It will pour into spring mvc The parameter parser of ( It seems to be called ParameterConversionService), When the incoming string is converted to LocalDateTime Class time ,spring Will call the Converter Convert this input parameter .

Be careful : About custom parameter Converter Converter, Here I met a pit , I'll record it in detail here , Originally, my idea was to simplify the code , Reduce the writing of the anonymous inner class above to lambda How expressions work :

@Bean
@ConditionalOnBean(name = "requestMappingHandlerAdapter")
public Converter<String, LocalDate> localDateConverter() {
    return source -> LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
}

When I started the project again, there was an exception :

Caused by: java.lang.IllegalArgumentException: Unable to determine source type <S> and target type <T> for your Converter [com.example.demo126.config.MappingConverterAdapter$$Lambda$522/817994751]; does the class parameterize those types?

puzzled , After consulting the information, I learned that one or two :

web Project start registration requestMappingHandlerAdapter It will initialize WebBindingInitializer

adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer());

and ConfigurableWebBindingInitializer need FormattingConversionService, and FormattingConversionService All of them Converter added , You need to get generic information when adding :

@Override
public void addFormatters(FormatterRegistry registry) {
    for (Converter<?, ?> converter : getBeansOfType(Converter.class)) {
       registry.addConverter(converter);
    }
    for (GenericConverter converter : getBeansOfType(GenericConverter.class)) {
       registry.addConverter(converter);
    }
    for (Formatter<?> formatter : getBeansOfType(Formatter.class)) {
       registry.addFormatter(formatter);
    }
}

add to Converter.class Generally, the specific types of two generic types are obtained through the interface

public ResolvableType as(Class<?> type) {
    if (this == NONE) {
      return NONE;
    }
    Class<?> resolved = resolve();
    if (resolved == null || resolved == type) {
      return this;
    }
    for (ResolvableType interfaceType : getInterfaces()) {
      ResolvableType interfaceAsType = interfaceType.as(type);
      if (interfaceAsType != NONE) {
        return interfaceAsType;
      }
    }
    return getSuperType().as(type);
}

Lambda The interface of the expression is Converter, You can't get a specific type , I'm snooping SpringMVC After the source code, I learned that it was so , Now that you have the reason , The solution :

The simplest way is not to apply Lambda expression , Or honestly use anonymous inner classes , In this way, the above problems will not exist

Or just wait requestMappingHandlerAdapterbean Add your own after registration converter You won't register with FormattingConversionService in

@Bean
@ConditionalOnBean(name = "requestMappingHandlerAdapter")
public Converter<String, LocalDateTime> localDateTimeConverter() {
  return source -> LocalDateTime.parse(source, DateTimeUtils.DEFAULT_FORMATTER);
}

It can also be used for the string Regular matching , Such as yyyy-MM-dd HH:mm:ss、yyyy-MM-dd、 HH:mm:ss etc. , Match . To adapt to a variety of scenarios .

@Component
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String value) {
        /**
         *  But for value Regular matching , Support date 、 Time and other types of conversion 
         *  Here I steal a lazy , It's matching Date Date format directly uses  hutool  For the parsing tool class we have written , There's no need to make wheels again 
         * cn.hutool.core.date.DateUtil
         * @param value
         * @return
         */
        return DateUtil.parse(value.trim());
    }
}

notes : Here I steal a lazy , It's matching Date Date format directly uses hutool For the parsing tool class we have written , There's no need to make wheels again , The following method also uses this tool class , It's also easy to use this tool class in your own project , In the project pom Introduce in the file hutool We can rely on , as follows :

<!--hu tool  Tool class -->
<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.1.3</version>
</dependency>

Use Spring annotation

Use spring Bring your own notes @DateTimeFormat(pattern = "yyyy-MM-dd"), as follows :

@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date startDate;

If custom parameters are used ,Spring This method will be used preferentially , namely Spring The note does not take effect .

Use ControllerAdvice coordination initBinder

@ControllerAdvice
public class GlobalExceptionHandler {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            }
        });
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
        });
        binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss")));
            }
        });
    }
}

It can be seen from the name , This is controller Do circular cutting ( You can also catch global exceptions ), Enter in the parameter handler Convert before ; Convert to our corresponding object .

JSON Global processing of input and return values

The request type is :post,content-type=application/json, Backstage use @RequestBody receive , The default format of received and returned values is :yyyy-MM-dd HH:mm:ss

modify application.yml file

stay application.propertities Add the following to the file :

spring:
	jackson:
		date-format: yyyy-MM-dd HH:mm:ss
		time-zone: GMT+8
  • Support (content-type=application/json) The format in the request is yyyy-MM-dd HH:mm:ss String , Backstage use @RequestBody receive , And the return value date To yyyy-MM-dd HH:mm:ss Format string;

  • I won't support it (content-type=application/json) In request yyyy-MM-dd And so on date;

  • I won't support it java8 date api;

utilize Jackson Of JSON Serialization and deserialization

@Configuration
public class JacksonConfig {

    /**  Default date time format  */
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /**  Default date format  */
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    /**  Default time format  */
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();

        //  Ignore json Unrecognized attribute in string 
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //  Ignore objects that cannot be converted  
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // PrettyPrinter  Format output 
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        // NULL Does not participate in serialization 
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        //  Designated time zone 
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        //  Date type string processing 
        objectMapper.setDateFormat(new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT));

        // java8 Date processing 
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        objectMapper.registerModule(javaTimeModule);

        converter.setObjectMapper(objectMapper);
        return converter;
    }
}

summary :

  • Support (content-type=application/json) The format in the request is yyyy-MM-dd HH:mm:ss String , Backstage use @RequestBody receive , And the return value Date To yyyy-MM-dd HH:mm:ss Format String;

  • Support java8 date api;

  • I won't support it (content-type=application/json) In request yyyy-MM-dd And so on Date;

The above two methods are as follows JSON Global processing of input parameters , Recommended mode 2 , It is especially suitable for large projects to set globally in the basic package .

JSON Local differentiation of input and return values

scene : If the global date and time processing format is :yyyy-MM-dd HH:mm:ss, But a field requires a received or returned date yyyy-MM-dd.

Mode one Use springboot A self explanatory note @JsonFormat(pattern = "yyyy-MM-dd"), As shown below :

@JsonFormat(pattern = "yyyy-MM-dd", timezone="GMT+8")
private Date releaseDate;

comment :springboot Provided by default , Powerful , Meet common scenarios , And you can specify the time zone .

Mode two

Custom date serialization and deserialization , As shown below :

/**
 *  Date serialization 
 */
public class DateJsonSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        jsonGenerator.writeString(dateFormat.format(date));
    }
}

/**
 *  Date deserialization 
 */
public class DateJsonDeserializer extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return dateFormat.parse(jsonParser.getText());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}

/**
 *  Usage mode 
 */
@JsonSerialize(using = DateJsonSerializer.class)
@JsonDeserialize(using = DateJsonDeserializer.class)
private Date releaseDate;
 Copy code date time format processing method complete configuration 
@Configuration
public class DateHandlerConfig {

    /**  Default date time format  */
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /**  Default date format  */
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    /**  Default time format  */
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    /**
     * LocalDate converter , Used to convert RequestParam and PathVariable Parameters 
     * `@ConditionalOnBean(name = "requestMappingHandlerAdapter")`:  etc. requestMappingHandlerAdapter bean After registration 
     *  Add your own `converter` You won't register with `FormattingConversionService` in 
     */
    @Bean
    @ConditionalOnBean(name = "requestMappingHandlerAdapter")
    public Converter<String, LocalDate> localDateConverter() {
        return source -> LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
    }

    /**
     * LocalDateTime converter , Used to convert RequestParam and PathVariable Parameters 
     */
    @Bean
    @ConditionalOnBean(name = "requestMappingHandlerAdapter")
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return source -> LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
    }

    /**
     * LocalTime converter , Used to convert RequestParam and PathVariable Parameters 
     */
    @Bean
    @ConditionalOnBean(name = "requestMappingHandlerAdapter")
    public Converter<String, LocalTime> localTimeConverter() {
        return source -> LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
    }

    /**
     * Date converter , Used to convert RequestParam and PathVariable Parameters 
     *  Here, the date format for parsing various formats adopts  hutool  Date parsing tool class 
     */
    @Bean
    public Converter<String, Date> dateConverter() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                return DateUtil.parse(source.trim());
            }
        };
    }

    /**
     * Json Serialization and deserialization Converters , Used to convert Post In the body of the request json And serializing our object to return the response json
     */
    @Bean
    public ObjectMapper objectMapper(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

        //LocalDateTime Series serialization and deserialization modules , Inherited from jsr310, We have modified the date format here 
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));


        //Date Serialization and deserialization 
        javaTimeModule.addSerializer(Date.class, new JsonSerializer<>() {
            @Override
            public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
                String formattedDate = formatter.format(date);
                jsonGenerator.writeString(formattedDate);
            }
        });
        javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<>() {
            @Override
            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
                String date = jsonParser.getText();
                try {
                    return format.parse(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }
}

Next into debug Pattern , have a look mvc How will we request The parameters in are bound to us controller Layer method input parameters ;

Write a simple controller, Call a breakpoint on the stack :

@GetMapping("/getDate")
public LocalDateTime getDate(@RequestParam LocalDate date,
                             @RequestParam LocalDateTime dateTime,
                             @RequestParam Date originalDate) {
    System.out.println(date);
    System.out.println(dateTime);
    System.out.println(originalDate);
    return LocalDateTime.now();
}

After calling the interface , Let's look at some key methods in the method call stack :

// Get into DispatcherServlet
doService:942, DispatcherServlet
// Processing requests 
doDispatch:1038, DispatcherServlet
// Generate call chain ( Before processing 、 Actually call the method 、 post-processing )
handle:87, AbstractHandlerMethodAdapter
// Reflection gets the actual calling method , Ready to start calling 
invokeHandlerMethod:895, RequestMappingHandlerAdapter
invokeAndHandle:102, ServletInvocableHandlerMethod
// Here's the key , Parameters are obtained from here 
invokeForRequest:142, InvocableHandlerMethod
doInvoke:215, InvocableHandlerMethod
// This is Java reflect call , So it must be the parameters obtained before 
invoke:566, Method

According to the above analysis , Find out invokeForRequest:142, InvocableHandlerMethod The code here is used to get the actual parameters :

@Nullable
public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
        Object... providedArgs) throws Exception {
    // This method is to get parameters , Here's the next break 
    Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
    if (logger.isTraceEnabled()) {
        logger.trace("Arguments: " + Arrays.toString(args));
    }
    // Here we start calling methods 
    return doInvoke(args);
}

Enter this method to see what operation :

protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {
    // Get the array of method parameters , Contains input parameter information , Such as the type 、 Generics and so on 
    MethodParameter[] parameters = getMethodParameters();
    // This is for storage for a while request parameter Parameters of conversion 
    Object[] args = new Object[parameters.length];
    for (int i = 0; i < parameters.length; i++) {
      MethodParameter parameter = parameters[i];
      parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
      // It doesn't look like much use here (providedArgs It's empty )
      args[i] = resolveProvidedArgument(parameter, providedArgs);
      // Here we start to get the parameters of the actual call of the method , Stepping 
      if (this.argumentResolvers.supportsParameter(parameter)) {
        // From the name : The parameter parser parses parameters 
        args[i] = this.argumentResolvers.resolveArgument(parameter, mavContainer, request, this.dataBinderFactory);
        continue;
      }
    }
    return args;
}

Get into resolveArgument have a look :

public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
                              NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
  // Enter parameters according to the method , Get the corresponding parser 
  HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter);
  // Start parsing parameters ( Put... In the request parameter Turn to the input parameter of the method )
  return resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
}
 Copy the code here to get the corresponding parameter parser according to the parameters , See how to get it internally :
// Traverse , call supportParameter Method , Follow up 
for (HandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) {
  if (methodArgumentResolver.supportsParameter(parameter)) {
    result = methodArgumentResolver;
    this.argumentResolverCache.put(parameter, result);
    break;
  }
}

here , Traversal parameter parser , Find out if there is a suitable parser ! that , What are the parameters of the parser ( When I tested, I had 26 individual )??? Let me list a few important ones , Is it familiar !!!

{[email protected]}
{[email protected]}
{[email protected]}
{[email protected]}

Let's go to one of the most commonly used parsers and see his supportsParameter Method , Discovery is to obtain the corresponding parser through Parameter annotation .

public boolean supportsParameter(MethodParameter parameter) {
    // If the parameter has an annotation @RequestParam, Take this branch ( Know why the above is right RequestParam and Json The two kinds of data are treated differently )
    if (parameter.hasParameterAnnotation(RequestParam.class)) {
        // This seems to be right Optional Parameters of type 
        if (Map.class.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType())) {
            RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
            return (requestParam != null && StringUtils.hasText(requestParam.name()));
        }
        else {
            return true;
        }
    }
    //......
}

in other words , about @RequestParam and @RequestBody as well as @PathVariable Annotated parameters ,SpringMVC Will use different parameter parsers for data binding !

that , What do the three parsers use Converter Parsing parameters ? Let's take a look at the three parsers :

Take a look first RequestParamMethodArgumentResolver Found internal use WebDataBinder Data binding , The bottom layer uses ConversionService ( That's our Converter Where it's injected )

WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);
// adopt DataBinder Data binding 
arg = binder.convertIfNecessary(arg, parameter.getParameterType(), parameter);
// To follow up convertIfNecessary()
public <T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType,
                                @Nullable MethodParameter methodParam) throws TypeMismatchException {

  return getTypeConverter().convertIfNecessary(value, requiredType, methodParam);
}
// Continue to follow up , I see a 
ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
  TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
  if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
    try {
      return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
    }
    catch (ConversionFailedException ex) {
      // fallback to default conversion logic below
      conversionAttemptEx = ex;
    }
  }
}

Then look at it. RequestResponseBodyMethodProcessor It is found that the converter used is HttpMessageConverter Type of :

//resolveArgument The internal call of the method is followed by parameter parsing 
Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());

//step into readWithMessageConverters(), We see here Converter yes HttpMessageConverter
for (HttpMessageConverter<?> converter : this.messageConverters) {
  Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
  GenericHttpMessageConverter<?> genericConverter =
    (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
  if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) :
      (targetClass != null && converter.canRead(targetClass, contentType))) {
    if (message.hasBody()) {
      HttpInputMessage msgToUse =
        getAdvice().beforeBodyRead(message, parameter, targetType, converterType);
      body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) :
              ((HttpMessageConverter<T>) converter).read(targetClass, msgToUse));
      body = getAdvice().afterBodyRead(body, msgToUse, parameter, targetType, converterType);
    }
    else {
      body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType);
    }
    break;
  }
}

The last to see PathVariableMethodArgumentResolver Find out and RequestParam Follow the same execution path ( Both are inherited from AbstractNamedValueMethodArgumentResolver Parser ), So the code is not posted .

summary

If you want to convert request The parameter passed to the type we specified , According to the input annotation, it is necessary to distinguish :

If it is RequestBody, Then configure ObjectMapper( This thing will inject into Jackson Of HttpMessagConverter Inside , namely MappingJackson2HttpMessageConverter in ) To achieve Json Serialization and deserialization of format data ; If it is RequestParam perhaps PathVariable Parameters of type , By configuring Converter Realize parameter conversion ( these Converter It will pour into ConversionService in ).

END

 After reading this article, there are gains ? Please forward to share with more people 
 Focus on 「Java Programming duck 」, promote Java Skill 
 Focus on Java Programming duck WeChat official account , The background to reply : Yard farm gift bag   A copy of the latest technical data can be obtained . cover Java  Frame learning 、 Architect learning, etc !


 If the article helps , Looking at , Forward! .
 Thank you for your support  (*^__^*)

copyright notice
author[Migrant worker brother],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/135/202205142227496173.html

Random recommended