Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of entering parameters in SpringBoot Date

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to solve the problem of SpringBoot Date entry. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The problem of SpringBoot Date input parameters

Springboot project encountered pit-use @ ResponseBody @ RequestBody, object Date type input parameter, return json format

1. The Date type time in the transmission is not accurate

There will be an eight-hour deviation in the time zone.

Cause analysis

SpringBoot defaults to Jackson frame conversion, while Jackson defaults to GMT, which is 8 hours less for China.

Solution

Add this comment to the transferred Date property field

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

Define a long member variable in the transport entity class to store the timestamp. In the process of transmission, only the timestamp is passed, and the background converts it to Date and then assigns a value.

Class Test {private Date time; private Long timeLong;} @ PostMapping ("/ test") public Test test (@ RequestBody Test test) {test.setTime (new Date (test.getTimeLone ()); return test;} 2. Json data returned by backend

Where the Date type receives timestamps that are automatically converted to the Long type

Cause analysis:

The default json processing for the springboot1.x version is that jackson returns the date field to the timestamp

Solution:

Global configuration

Spring: jackson: time-zone: GMT+8 date-format: yyyy-MM-dd HH:mm:ss

If individual entities need to use other formats of pattern, you can add comments to the entities.

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

Some problems in input parameters of springboot Interface

Recently, I encountered a problem that the type conversion error of interface input parameters was not handled, so I sorted out some questions about springmvc input parameters.

Input parameter binding

1. The most common input parameter is the parameter conversion of date type, which can be converted through annotations. You only need to add the annotation @ DateTimeFormat (pattern= "yyyy-MM-dd") above the attribute of the bean object, and pattern is the formatting of the time object.

2. Define a data binding class in the controller class

/ * * add a piece of data binding code to the controller layer * @ param webDataBinder * / @ InitBinder public void initBinder (WebDataBinder webDataBinder) throws Exception {SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd"); simpleDateFormat.setLenient (false); webDataBinder.registerCustomEditor (Date.class, new CustomDateEditor (simpleDateFormat, true));}

3. Define a global parameter type converter

First set up a converter to implement Converter

Public class DateConverter implements Converter {private SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss"); @ Override public Date convert (String s) {if (".equals (s) | | s = = null) {return null;} try {return simpleDateFormat.parse (s);} catch (ParseException e) {e.printStackTrace () } return null;}}

Then bind the parameter converter to the configuration of springmvc

@ Configurationpublic class WebConfigBeans {@ Autowired private RequestMappingHandlerAdapter handlerAdapter; / * add string to date function * / @ PostConstruct public void initEditableAvlidation () {ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer (); if (initializer.getConversionService ()! = null) {GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService (); genericConversionService.addConverter (new StringToDateConverter ()) Global exception handling of input parameter error

In springmvc's model, if there is an exception in parameter conversion, it will jump directly to the default error 400. if what we are doing is an interface and we need to return a json object representing the error, we can use a global exception handling class. Add the annotation @ RestControllerAdvice to the class to return the rest-style object after exception handling, and use @ ControllerAdvice to return to the page.

@ RestControllerAdvicepublic class ControllerAdvice {@ ExceptionHandler (value = {org.springframework.validation.BindException.class}) public BaseResp dealDateFarmatException (Throwable exception) {BaseResp resp = new BaseResp (); resp.setCode ("400"); resp.setStatus (false); resp.setMsg ("parameter type error"); return resp;}} Thank you for reading! This is the end of the article on "how to solve the problem of entering SpringBoot Date". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report