需求:提交一個字符串到后端的java.sql.Time類型,就報錯了:
Failed to convert property value of type [java.lang.String] to required type [java.sql.Time]
正常提交到java.util.Date類型是沒有問題的。
所以這里就需要擴展內置的springmvc的轉換器
代碼如下:
WebConfig : 添加新的類型轉換器
import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import com.csget.web.converter.StringToTimeConverter; @Configuration public class WebConfig { @Autowired private RequestMappingHandlerAdapter requestMappingHandlerAdapter; @PostConstruct public void addConversionConfig() { ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter .getWebBindingInitializer(); if (initializer.getConversionService() != null) { GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService(); genericConversionService.addConverter(new StringToTimeConverter()); } } }
StringToTimeConverter :類型轉換器的具體實現
import java.sql.Time; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang3.StringUtils; import org.springframework.core.convert.converter.Converter; public class StringToTimeConverter implements Converter<String, Time> { public Time convert(String value) { Time time = null; if (StringUtils.isNotBlank(value)) { String strFormat = "HH:mm"; int intMatches = StringUtils.countMatches(value, ":"); if (intMatches == 2) { strFormat = "HH:mm:ss"; } SimpleDateFormat format = new SimpleDateFormat(strFormat); Date date = null; try { date = format.parse(value); } catch (Exception e) { e.printStackTrace(); } time = new Time(date.getTime()); } return time; } }