1.类型转换器
在日常的企业开发需求中,我们输入文本框的内容全部都是字符串类型,但是在后端处理的时候我们可以用其他基本类型来接受数据,也可以使用实体类来接受参数,这个是怎么完成的呢?就是通过SpringMVC提供的类型转换器,SpringMVC内部提供了非常丰富的类型转换器的支持,但是有些情况下有可能难以满足我们的需求,因此需要我们自己实现,如下:<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/23066524/1637063726704-a49bf789-af70-454e-8735-a369db2c2cf1.png#clientId=u28569ed8-9554-4&from=paste&height=623&id=uea3811e9&margin=%5Bobject%20Object%5D&name=image.png&originHeight=1246&originWidth=914&originalType=binary&ratio=1&size=369710&status=done&style=none&taskId=u6b2cc037-94b9-448f-b596-bf12d9250e4&width=457)
ConversionService converters =
@org.springframework.format.annotation.DateTimeFormat java.lang.Long -> java.lang.String: org.springframework.format.datetime.DateTimeFormatAnnotationFormatterFactory@4ec4ca46,@org.springframework.format.annotation.NumberFormat java.lang.Long -> java.lang.String: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
@org.springframework.format.annotation.DateTimeFormat java.time.LocalDate -> java.lang.String: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.time.LocalDate -> java.lang.String : org.springframework.format.datetime.standard.TemporalAccessorPrinter@6b2739e8
@org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime -> java.lang.String: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.time.LocalDateTime -> java.lang.String : org.springframework.format.datetime.standard.TemporalAccessorPrinter@515e3e2b
@org.springframework.format.annotation.DateTimeFormat java.time.LocalTime -> java.lang.String: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.time.LocalTime -> java.lang.String : org.springframework.format.datetime.standard.TemporalAccessorPrinter@e5802af
@org.springframework.format.annotation.DateTimeFormat java.time.OffsetDateTime -> java.lang.String: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.time.OffsetDateTime -> java.lang.String : org.springframework.format.datetime.standard.TemporalAccessorPrinter@8547711
@org.springframework.format.annotation.DateTimeFormat java.time.OffsetTime -> java.lang.String: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.time.OffsetTime -> java.lang.String : org.springframework.format.datetime.standard.TemporalAccessorPrinter@5f7ef1af
@org.springframework.format.annotation.DateTimeFormat java.time.ZonedDateTime -> java.lang.String: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.time.ZonedDateTime -> java.lang.String : org.springframework.format.datetime.standard.TemporalAccessorPrinter@e673fc2
@org.springframework.format.annotation.DateTimeFormat java.util.Calendar -> java.lang.String: org.springframework.format.datetime.DateTimeFormatAnnotationFormatterFactory@4ec4ca46
@org.springframework.format.annotation.DateTimeFormat java.util.Date -> java.lang.String: org.springframework.format.datetime.DateTimeFormatAnnotationFormatterFactory@4ec4ca46
@org.springframework.format.annotation.NumberFormat java.lang.Byte -> java.lang.String: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
@org.springframework.format.annotation.NumberFormat java.lang.Double -> java.lang.String: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
@org.springframework.format.annotation.NumberFormat java.lang.Float -> java.lang.String: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
@org.springframework.format.annotation.NumberFormat java.lang.Integer -> java.lang.String: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
@org.springframework.format.annotation.NumberFormat java.lang.Short -> java.lang.String: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
@org.springframework.format.annotation.NumberFormat java.math.BigDecimal -> java.lang.String: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
@org.springframework.format.annotation.NumberFormat java.math.BigInteger -> java.lang.String: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
java.lang.Boolean -> java.lang.String : org.springframework.core.convert.support.ObjectToStringConverter@430fd9a0
java.lang.Character -> java.lang.Number : org.springframework.core.convert.support.CharacterToNumberFactory@39560299
java.lang.Character -> java.lang.String : org.springframework.core.convert.support.ObjectToStringConverter@7ffc5a86
java.lang.Enum -> java.lang.Integer : org.springframework.core.convert.support.EnumToIntegerConverter@7f642c95
java.lang.Enum -> java.lang.String : org.springframework.core.convert.support.EnumToStringConverter@48af5069
java.lang.Integer -> java.lang.Enum : org.springframework.core.convert.support.IntegerToEnumConverterFactory@421b3faf
java.lang.Long -> java.time.Instant : org.springframework.format.datetime.standard.DateTimeConverters$LongToInstantConverter@7676b8a0
java.lang.Long -> java.util.Calendar : org.springframework.format.datetime.DateFormatterRegistrar$LongToCalendarConverter@41b2ab4c,java.lang.Long -> java.util.Calendar : org.springframework.format.datetime.DateFormatterRegistrar$LongToCalendarConverter@51c90511
java.lang.Long -> java.util.Date : org.springframework.format.datetime.DateFormatterRegistrar$LongToDateConverter@16ccf62,java.lang.Long -> java.util.Date : org.springframework.format.datetime.DateFormatterRegistrar$LongToDateConverter@601fac14
java.lang.Number -> java.lang.Character : org.springframework.core.convert.support.NumberToCharacterConverter@4668902f
java.lang.Number -> java.lang.Number : org.springframework.core.convert.support.NumberToNumberConverterFactory@6ca039f6
java.lang.Number -> java.lang.String : org.springframework.core.convert.support.ObjectToStringConverter@3d185b20
java.lang.String -> @org.springframework.format.annotation.DateTimeFormat java.lang.Long: org.springframework.format.datetime.DateTimeFormatAnnotationFormatterFactory@4ec4ca46,java.lang.String -> @org.springframework.format.annotation.NumberFormat java.lang.Long: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
java.lang.String -> @org.springframework.format.annotation.DateTimeFormat java.time.LocalDate: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.lang.String -> java.time.LocalDate: org.springframework.format.datetime.standard.TemporalAccessorParser@28573f94
java.lang.String -> @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.lang.String -> java.time.LocalDateTime: org.springframework.format.datetime.standard.TemporalAccessorParser@40e4100b
java.lang.String -> @org.springframework.format.annotation.DateTimeFormat java.time.LocalTime: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.lang.String -> java.time.LocalTime: org.springframework.format.datetime.standard.TemporalAccessorParser@3e4bfc6
java.lang.String -> @org.springframework.format.annotation.DateTimeFormat java.time.OffsetDateTime: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.lang.String -> java.time.OffsetDateTime: org.springframework.format.datetime.standard.TemporalAccessorParser@68d04a58
java.lang.String -> @org.springframework.format.annotation.DateTimeFormat java.time.OffsetTime: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.lang.String -> java.time.OffsetTime: org.springframework.format.datetime.standard.TemporalAccessorParser@2a8ae894
java.lang.String -> @org.springframework.format.annotation.DateTimeFormat java.time.ZonedDateTime: org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory@4a98f52f,java.lang.String -> java.time.ZonedDateTime: org.springframework.format.datetime.standard.TemporalAccessorParser@28dbab47
java.lang.String -> @org.springframework.format.annotation.DateTimeFormat java.util.Calendar: org.springframework.format.datetime.DateTimeFormatAnnotationFormatterFactory@4ec4ca46
java.lang.String -> @org.springframework.format.annotation.DateTimeFormat java.util.Date: org.springframework.format.datetime.DateTimeFormatAnnotationFormatterFactory@4ec4ca46
java.lang.String -> @org.springframework.format.annotation.NumberFormat java.lang.Byte: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
java.lang.String -> @org.springframework.format.annotation.NumberFormat java.lang.Double: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
java.lang.String -> @org.springframework.format.annotation.NumberFormat java.lang.Float: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
java.lang.String -> @org.springframework.format.annotation.NumberFormat java.lang.Integer: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
java.lang.String -> @org.springframework.format.annotation.NumberFormat java.lang.Short: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
java.lang.String -> @org.springframework.format.annotation.NumberFormat java.math.BigDecimal: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
java.lang.String -> @org.springframework.format.annotation.NumberFormat java.math.BigInteger: org.springframework.format.number.NumberFormatAnnotationFormatterFactory@1628f3df
java.lang.String -> java.lang.Boolean : org.springframework.core.convert.support.StringToBooleanConverter@5eba909b
java.lang.String -> java.lang.Character : org.springframework.core.convert.support.StringToCharacterConverter@12febea6
java.lang.String -> java.lang.Enum : org.springframework.core.convert.support.StringToEnumConverterFactory@41e4c006
java.lang.String -> java.lang.Number : org.springframework.core.convert.support.StringToNumberConverterFactory@5d6c983e
java.lang.String -> java.nio.charset.Charset : org.springframework.core.convert.support.StringToCharsetConverter@3184a445
java.lang.String -> java.time.Duration: org.springframework.format.datetime.standard.DurationFormatter@437e9192
java.lang.String -> java.time.Instant: org.springframework.format.datetime.standard.InstantFormatter@14dfe2b
java.lang.String -> java.time.Month: org.springframework.format.datetime.standard.MonthFormatter@501f0275
java.lang.String -> java.time.MonthDay: org.springframework.format.datetime.standard.MonthDayFormatter@230d0cca
java.lang.String -> java.time.Period: org.springframework.format.datetime.standard.PeriodFormatter@6b25f6d0
java.lang.String -> java.time.Year: org.springframework.format.datetime.standard.YearFormatter@3ecd1f21
java.lang.String -> java.time.YearMonth: org.springframework.format.datetime.standard.YearMonthFormatter@1448edd0
java.lang.String -> java.util.Currency : org.springframework.core.convert.support.StringToCurrencyConverter@4e203f5f
java.lang.String -> java.util.Locale : org.springframework.core.convert.support.StringToLocaleConverter@1867278f
java.lang.String -> java.util.Properties : org.springframework.core.convert.support.StringToPropertiesConverter@388ee7a7
java.lang.String -> java.util.TimeZone : org.springframework.core.convert.support.StringToTimeZoneConverter@663f1943
java.lang.String -> java.util.UUID : org.springframework.core.convert.support.StringToUUIDConverter@49cc9297
java.nio.charset.Charset -> java.lang.String : org.springframework.core.convert.support.ObjectToStringConverter@6f5a2664
java.time.Duration -> java.lang.String : org.springframework.format.datetime.standard.DurationFormatter@437e9192
java.time.Instant -> java.lang.Long : org.springframework.format.datetime.standard.DateTimeConverters$InstantToLongConverter@6a401b0
java.time.Instant -> java.lang.String : org.springframework.format.datetime.standard.InstantFormatter@14dfe2b
java.time.LocalDateTime -> java.time.LocalDate : org.springframework.format.datetime.standard.DateTimeConverters$LocalDateTimeToLocalDateConverter@3639d795
java.time.LocalDateTime -> java.time.LocalTime : org.springframework.format.datetime.standard.DateTimeConverters$LocalDateTimeToLocalTimeConverter@2bdba24a
java.time.Month -> java.lang.String : org.springframework.format.datetime.standard.MonthFormatter@501f0275
java.time.MonthDay -> java.lang.String : org.springframework.format.datetime.standard.MonthDayFormatter@230d0cca
java.time.OffsetDateTime -> java.time.Instant : org.springframework.format.datetime.standard.DateTimeConverters$OffsetDateTimeToInstantConverter@676ac921
java.time.OffsetDateTime -> java.time.LocalDate : org.springframework.format.datetime.standard.DateTimeConverters$OffsetDateTimeToLocalDateConverter@326421e8
java.time.OffsetDateTime -> java.time.LocalDateTime : org.springframework.format.datetime.standard.DateTimeConverters$OffsetDateTimeToLocalDateTimeConverter@3d974458
java.time.OffsetDateTime -> java.time.LocalTime : org.springframework.format.datetime.standard.DateTimeConverters$OffsetDateTimeToLocalTimeConverter@3c072322
java.time.OffsetDateTime -> java.time.ZonedDateTime : org.springframework.format.datetime.standard.DateTimeConverters$OffsetDateTimeToZonedDateTimeConverter@7412cd2a
java.time.Period -> java.lang.String : org.springframework.format.datetime.standard.PeriodFormatter@6b25f6d0
java.time.Year -> java.lang.String : org.springframework.format.datetime.standard.YearFormatter@3ecd1f21
java.time.YearMonth -> java.lang.String : org.springframework.format.datetime.standard.YearMonthFormatter@1448edd0
java.time.ZoneId -> java.util.TimeZone : org.springframework.core.convert.support.ZoneIdToTimeZoneConverter@5c8ff106
java.time.ZonedDateTime -> java.time.Instant : org.springframework.format.datetime.standard.DateTimeConverters$ZonedDateTimeToInstantConverter@2b5c4212
java.time.ZonedDateTime -> java.time.LocalDate : org.springframework.format.datetime.standard.DateTimeConverters$ZonedDateTimeToLocalDateConverter@7fe794b6
java.time.ZonedDateTime -> java.time.LocalDateTime : org.springframework.format.datetime.standard.DateTimeConverters$ZonedDateTimeToLocalDateTimeConverter@1ee211ef
java.time.ZonedDateTime -> java.time.LocalTime : org.springframework.format.datetime.standard.DateTimeConverters$ZonedDateTimeToLocalTimeConverter@669ff7d6
java.time.ZonedDateTime -> java.time.OffsetDateTime : org.springframework.format.datetime.standard.DateTimeConverters$ZonedDateTimeToOffsetDateTimeConverter@685d298b
java.time.ZonedDateTime -> java.util.Calendar : org.springframework.core.convert.support.ZonedDateTimeToCalendarConverter@6138bd15
java.util.Calendar -> java.lang.Long : org.springframework.format.datetime.DateFormatterRegistrar$CalendarToLongConverter@32b267dc,java.util.Calendar -> java.lang.Long : org.springframework.format.datetime.DateFormatterRegistrar$CalendarToLongConverter@3027d26
java.util.Calendar -> java.time.Instant : org.springframework.format.datetime.standard.DateTimeConverters$CalendarToInstantConverter@208023cf
java.util.Calendar -> java.time.LocalDate : org.springframework.format.datetime.standard.DateTimeConverters$CalendarToLocalDateConverter@75a3f40
java.util.Calendar -> java.time.LocalDateTime : org.springframework.format.datetime.standard.DateTimeConverters$CalendarToLocalDateTimeConverter@5b92ec5f
java.util.Calendar -> java.time.LocalTime : org.springframework.format.datetime.standard.DateTimeConverters$CalendarToLocalTimeConverter@3648cd4b
java.util.Calendar -> java.time.OffsetDateTime : org.springframework.format.datetime.standard.DateTimeConverters$CalendarToOffsetDateTimeConverter@65c3d54f
java.util.Calendar -> java.time.ZonedDateTime : org.springframework.format.datetime.standard.DateTimeConverters$CalendarToZonedDateTimeConverter@6271e8dd
java.util.Calendar -> java.util.Date : org.springframework.format.datetime.DateFormatterRegistrar$CalendarToDateConverter@5e9b9eea,java.util.Calendar -> java.util.Date : org.springframework.format.datetime.DateFormatterRegistrar$CalendarToDateConverter@181f31ba
java.util.Currency -> java.lang.String : org.springframework.core.convert.support.ObjectToStringConverter@2c3cd8e9
java.util.Date -> java.lang.Long : org.springframework.format.datetime.DateFormatterRegistrar$DateToLongConverter@133715f3,java.util.Date -> java.lang.Long : org.springframework.format.datetime.DateFormatterRegistrar$DateToLongConverter@4cb15e75
java.util.Date -> java.util.Calendar : org.springframework.format.datetime.DateFormatterRegistrar$DateToCalendarConverter@1d56ea37,java.util.Date -> java.util.Calendar : org.springframework.format.datetime.DateFormatterRegistrar$DateToCalendarConverter@75a88521
java.util.Locale -> java.lang.String : org.springframework.core.convert.support.ObjectToStringConverter@2af910f2
java.util.Properties -> java.lang.String : org.springframework.core.convert.support.PropertiesToStringConverter@6d99fd4
java.util.UUID -> java.lang.String : org.springframework.core.convert.support.ObjectToStringConverter@37df0d7
org.springframework.core.convert.support.ArrayToArrayConverter@2b19ffdb
org.springframework.core.convert.support.ArrayToCollectionConverter@4c019cc0
org.springframework.core.convert.support.ArrayToObjectConverter@343b143b
org.springframework.core.convert.support.ArrayToStringConverter@654a7e11
org.springframework.core.convert.support.ByteBufferConverter@209ae681
org.springframework.core.convert.support.ByteBufferConverter@209ae681
org.springframework.core.convert.support.ByteBufferConverter@209ae681
org.springframework.core.convert.support.ByteBufferConverter@209ae681
org.springframework.core.convert.support.CollectionToArrayConverter@66c9dab
org.springframework.core.convert.support.CollectionToCollectionConverter@470e5927
org.springframework.core.convert.support.CollectionToObjectConverter@6c6550c9
org.springframework.core.convert.support.CollectionToStringConverter@4c04c66a
org.springframework.core.convert.support.FallbackObjectToStringConverter@2b2ed015
org.springframework.core.convert.support.IdToEntityConverter@1661f15d,org.springframework.core.convert.support.ObjectToObjectConverter@80a17d3
org.springframework.core.convert.support.MapToMapConverter@7292a9a
org.springframework.core.convert.support.ObjectToArrayConverter@7a8895dc
org.springframework.core.convert.support.ObjectToCollectionConverter@52fd0eec
org.springframework.core.convert.support.ObjectToOptionalConverter@f5a1070
org.springframework.core.convert.support.ObjectToOptionalConverter@f5a1070
org.springframework.core.convert.support.ObjectToOptionalConverter@f5a1070
org.springframework.core.convert.support.StreamConverter@3820b54f
org.springframework.core.convert.support.StreamConverter@3820b54f
org.springframework.core.convert.support.StreamConverter@3820b54f
org.springframework.core.convert.support.StreamConverter@3820b54f
org.springframework.core.convert.support.StringToArrayConverter@1c9b244
org.springframework.core.convert.support.StringToCollectionConverter@13163c
2.自定义类型转换器
2.1 xml文件配置
2.2 自定义类型转换器
package com.xixi.converts;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author yangkang
* @version 1.0
* @description: TODO
* @date 2021/11/16 20:04
*/
@Component
public class MyStringToDateConvert implements Converter<String, Date> {
@Override
public Date convert(String source) {
if (!StringUtils.isEmpty(source)) {
try {
if (source.split("-").length == 3) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.parse(source);
} else if (source.split("/").length == 3) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
return dateFormat.parse(source);
} else {
throw new RuntimeException("日期转换错误:" + source);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
3.数据格式
Spring 提供了两个可以用于格式化数字、日期和时间的注解@NumberFormat和@DateTimeFormat,这两个标签可以用于javabean的属性或方法参数上。@NumberFormat可以用来格式化任何的数字的基本类型(如int,long)或java.lang.Number的实例(如 BigDecimal, Integer)。@DateTimeFormat可以用来格式化java.util.Date、java.util.Calendar和 java.util.Long类型.
要指定数字或日期/时间类型的属性,只需要在其上添加 @NumberFormat或@DateTimeFormat注解接可以了。例如下面的代码:
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import org.joda.time.LocalTime;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.format.annotation.NumberFormat.Style;
public class Employee {
private String name;
/**
* numeric fields using @NumberFormat annotation for formatting.
*/
@NumberFormat(style = Style.CURRENCY)
private double salary;
@NumberFormat(style = Style.PERCENT)
private double w4AdditionalWithdraw;
@NumberFormat
private int dependents;
@NumberFormat(pattern = "0.00")
private BigDecimal visualAcuity;
/**
* date and time fields using @DateTimeFormat annotation for formatting.
*/
@DateTimeFormat(style = "M-")
private Date birthDate;
@DateTimeFormat(pattern = "w:yyyy")
private Calendar hireDate;
@DateTimeFormat(style = "-S")
private LocalTime startTime;
@DateTimeFormat(iso = ISO.DATE_TIME)
private long lastTimeEntry;
/**
* initialization block to provide sample data for display
*/
{
this.name = "John Doe";
this.salary = 30100.50;
this.w4AdditionalWithdraw = 0.02;
this.dependents = 5;
this.visualAcuity = new BigDecimal(".1");
Calendar dob = Calendar.getInstance();
dob.set(1964, Calendar.AUGUST, 30);
this.birthDate = dob.getTime();
this.hireDate = Calendar.getInstance();
this.startTime = new LocalTime(8, 0);
this.lastTimeEntry = (new Date()).getTime() - 10000;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getW4AdditionalWithdraw() {
return w4AdditionalWithdraw;
}
public void setW4AdditionalWithdraw(double w4AdditionalWithdraw) {
this.w4AdditionalWithdraw = w4AdditionalWithdraw;
}
public int getDependents() {
return dependents;
}
public void setDependents(int dependents) {
this.dependents = dependents;
}
public BigDecimal getVisualAcuity() {
return visualAcuity;
}
public void setVisualAcuity(BigDecimal visualAcuity) {
this.visualAcuity = visualAcuity;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public LocalTime getStartTime() {
return startTime;
}
public void setStartTime(LocalTime startTime) {
this.startTime = startTime;
}
public Calendar getHireDate() {
return hireDate;
}
public void setHireDate(Calendar hireDate) {
this.hireDate = hireDate;
}
public long getLastTimeEntry() {
return lastTimeEntry;
}
public void setLastTimeEntry(long lastTimeEntry) {
this.lastTimeEntry = lastTimeEntry;
}
}
注解类型
DateTimeFormat,互斥属性:
- iso。类型为DateTimeFormat.ISO
- DateTimeFormat.ISO.DATE: 格式yyyy-MM-dd。
- DateTimeFormat.ISO.DATE_TIME: 格式yyyy-MM-dd HH:mm:ss .SSSZ。
- DateTimeFormat.ISO.TIME: 格式HH:mm:ss .SSSZ。
- DateTimeFormat.ISO.NONE: 表示不使用ISO格式的时间。
- pattern。类型为String,使用自定义的时间格式化字符串。
- style。类型为String,通过样式指定日期时间的格式,由两位字符组成,第1位表示日期的样式,第2位表示时间的格式:
- S: 短日期/时间的样式;
- M: 中日期/时间的样式;
- L: 长日期/时间的样式;
- F: 完整日期/时间的样式;
- -: 忽略日期/时间的样式;
- NumberFormat
- pattern。类型为String,使用自定义的数字格式化字符串,”##,###.##”。
- style。类型为NumberFormat.Style,常用值:
- Style.NUMBER正常数字类型
- Style.PERCENT百分数类型
- Style.CURRENCY 货币类型
3.数据验证
一般情况下我们会在前端页面实现数据的校验,但是大家需要注意的是前端校验会存在数据的不安全问题,因此一般情况下我们都会使用前端校验+后端校验的方式,这样的话既能够满足用户的体验度,同时也能保证数据的安全,下面来说一下在springmvc中如何进行后端数据校验。
JSR303是 Java 为 Bean 数据合法性校验提供的标准,它已经包含在 JavaEE 6.0 中 。JSR 303 (Java Specification Requests意思是Java 规范提案)通过在Bean属性上标注类似于 @NotNull、@Max 等标准的注解指定校验规则,并通 j过标准的验证接口对 Bean 进行验证。
Hibernate Validator 实现了JSR349验证注解规范的技术。
spring中拥有自己的数据校验框架,同时支持JSR303标准的校验框架,可以在通过添加注解的方式进行数据校验。在spring中本身没有提供JSR303的实现,需要导入依赖的包。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.tulingxueyuan</groupId>
<artifactId>springmvc_viewResolver</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.0.Final</version>
</dependency>
</dependencies>
</project>
JavaBean类:
package com.xixi.entity;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import java.util.Arrays;
import java.util.Date;
/**
* @author yangkang
* @version 1.0
* @description: TODO
* @date 2021/11/16 19:13
*/
public class User {
@NotNull
@Min(1)
private Integer id;
@NotEmpty(message = "姓名不能为空哦哦!!!")
@Length(min = 2,max = 8)
private String username;
@Past
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birthday;
@NumberFormat(style = NumberFormat.Style.CURRENCY)
private Double balance;
private String[] hobbies;
private Double salary;//工资
@Range(min = 0,max = 100)
private Double taskCount;//任务完成比
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Double getTaskCount() {
return taskCount;
}
public void setTaskCount(Double taskCount) {
this.taskCount = taskCount;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", balance=" + balance +
", hobbies=" + Arrays.toString(hobbies) +
", salary=" + salary +
", taskCount=" + taskCount +
'}';
}
}
Controller类:
package com.xixi.controller;
import com.xixi.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 实现数据验证的步骤:
* 1.加入hibernate-validator的依赖
* 2.一定要注意,要将新加入的jar包,加入到WEB-INF/lib中
* 3.在需要验证的javabean加上注解
* 4.在验证处理方法对应的javabean参数上加上@Valid
* 5.在需要验证的处理方法参数加上BindingResult,代表自己处理错误,这样就不会显示错误页面
*
*
* 基于原生form表单的实现方式:
* 1。将错误信息循环通过map放入request域
* 2。在jsp页面中通过${errors.id}获取对应的错误信息
*
*/
@Controller
public class UserController {
@PostMapping("/user")
public String add(@Valid User user, BindingResult result, Model model) {
//判断当前是否出现了错误
if (result.hasErrors()) {
//存放错误信息 key 错误信息的属性名 value 错误信息
Map<String, String> errors = new HashMap<>();
//获取所有的错误信息 包含错误的属性,错误信息
List<FieldError> fieldErrors = result.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
errors.put(fieldError.getField(), fieldError.getDefaultMessage());
}
model.addAttribute("errors", errors);
return "user/add";
}
System.out.println(user);
return "user/show";
}
}