SpringMVC基于注解使用:类型转换&数据格式化&数据验证

类型转换器

在日常的企业开发需求中,我们输入文本框的内容全部都是字符串类型,但是在后端处理的时候我们可以用其他基本类型来接受数据,也可以使用实体类来接受参数,这个是怎么完成的呢?就是通过SpringMVC提供的类型转换器,SpringMVC内部提供了非常丰富的类型转换器的支持,但是有些情况下有可能难以满足我们的需求,因此需要我们自己实现,如下:

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

自定义类型转换器

User.java

package com.example.bean;
​
public class User {
​
   private Integer id;
   private String name;
   private Integer age;
   private String gender;
​
   public User() {
  }
​
   public Integer getId() {
       return id;
  }
​
   public void setId(Integer id) {
       this.id = id;
  }
​
   public String getName() {
       return name;
  }
​
   public void setName(String name) {
       this.name = name;
  }
​
   public Integer getAge() {
       return age;
  }
​
   public void setAge(Integer age) {
       this.age = age;
  }
​
   public String getGender() {
       return gender;
  }
​
   public void setGender(String gender) {
       this.gender = gender;
  }
​
   @Override
   public String toString() {
       return "User{" +
               "id=" + id +
               ", name='" + name + '\'' +
               ", age=" + age +
               ", gender='" + gender + '\'' +
               '}';
  }
}

MyConverter.java

package com.example.converter;

import com.example.bean.User;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

@Component
public class MyConverter implements Converter<String, User> {
    public User convert(String source) {
        User user = null;
        String[] split = source.split("-");
        if (source!=null && split.length==4){
            user = new User();
            user.setId(Integer.parseInt(split[0]));
            user.setName(split[1]);
            user.setAge(Integer.parseInt(split[2]));
            user.setGender(split[3]);
        }
        return user;
    }
}

UserController.java

package com.example.controller;

import com.example.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserController {

    @RequestMapping("/user")
    public String add(User user, Model model){
        System.out.println(user);
        model.addAttribute("user","user");
        return "success";
    }
}

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
    ${requestScope.user}
</body>
</html>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
​
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
​
   <context:component-scan base-package="com.example"></context:component-scan>
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/page/"></property>
       <property name="suffix" value=".jsp"></property>
   </bean>
   <bean class="com.example.view.MyViewResolver">
       <property name="order" value="1"></property>
   </bean>
   <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
   <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
       <property name="converters">
           <set>
               <ref bean="myConverter"></ref>
           </set>
       </property>
   </bean>
</beans>

数据格式化

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 货币类型

数据校验

一般情况下我们会在前端页面实现数据的校验,但是大家需要注意的是前端校验会存在数据的不安全问题,因此一般情况下我们都会使用前端校验+后端校验的方式,这样的话既能够满足用户的体验度,同时也能保证数据的安全,下面来说一下在springmvc中如何进行后端数据校验。

JSR303是 Java 为 Bean 数据合法性校验提供的标准,它已经包含在 JavaEE 6.0 中 。JSR 303 (Java Specification Requests意思是Java 规范提案)通过在 Bean 属性上标注类似于 @NotNull、@Max 等标准的注解指定校验规则,并通 j过标准的验证接口对 Bean 进行验证。

Hibernate Validator 实现了JSR349验证注解规范的技术

JSR303:

Hibernate Validator 扩展注解:

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>com.example</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>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
 </head>
 <body>
<form action="dataValidate" method="post">
编号:<input type="text" name="id"><br>
姓名:<input type="text" name="name"><br>
年龄:<input type="text" name="age"><br>
性别:<input type="text" name="gender"><br>
日期:<input type="text" name="birth"><br>
邮箱:<input type="text" name="email"><br>
 <input type="submit" value="提交">
</form>
 </body>
</html>

DataValidateController.java

package com.example.controller;

import com.example.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;

@Controller
public class DataValidateController {
    @RequestMapping("/dataValidate")
    public String validate(@Valid User user, BindingResult bindingResult) {
        System.out.println(user);
        if (bindingResult.hasErrors()) {
            System.out.println("验证失败");
            return "redirect:/index.jsp";
        } else {
            System.out.println("验证成功");
            return "hello";
        }
    }
}

User.java

package com.example.bean;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import java.util.Date;

public class User {

    private Integer id;
    @NotNull
    @Length(min = 5,max = 10)
    private String name;
    private Integer age;
    private String gender;
    @Past
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birth;
    @Email
    private String email;

    public User() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", birth=" + birth +
                ", email='" + email + '\'' +
                '}';
    }
}

此时大家发现在报错的地方无法出现错误提示:

原生的表单如何获取错误信息

DataValidateController.java

package com.example.controller;

import com.example.bean.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.RequestMapping;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class DataValidateController {
    @RequestMapping("/dataValidate")
    public String validate(@Valid User user, BindingResult bindingResult, Model model) {
        System.out.println(user);
        Map<String,Object> errorsMap = new HashMap<String, Object>();
        if (bindingResult.hasErrors()) {
            System.out.println("验证失败");
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println(fieldError.getDefaultMessage());
                System.out.println(fieldError.getField());
                errorsMap.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("errorInfo",errorsMap);
            return "add";
        } else {
            System.out.println("验证成功");
            return "hello";
        }
    }

    @RequestMapping("add")
    public String add(Model model){
        model.addAttribute("user",new User(1,"zhangsan",12,"女",null,"1234@qq.com"));
        return "add";
    }
}

add.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>$Title$</title>
</head>
<body>
<form action="dataValidate" method="post">
编号:<input type="text" name="id">${errorInfo.id}<br>
姓名:<input type="text" name="name">${errorInfo.name}<br>
年龄:<input type="text" name="age">${errorInfo.age}<br/>
性别:<input type="text" name="gender">${errorInfo.gender}<br/>
日期:<input type="text" name="birth">${errorInfobirth}<br/>
邮箱:<input type="text" name="email">${errorInfo.email}<br/>
 <input type="submit" value="提交">
</form>
</body>
</html>

Springmvc form标签

自动绑定,自动回显数据, 如果是新增的情况下也需要保证有该标签所需的对象

Form标签

        1、支持全部http请求方法  比如method=”put”    put\delete 提交方式

        2、数据自动回显:需要使用modelAttribute指定数据的对象

        3、使用path来双向绑定属性

        4、动态数据绑定:Select 、 checkboxes、 radiobottons、 都可以使用Items 制定数据源  可以是list (当List的泛型是javaBean的时候需要制定itemValue和itemLabel)、map(不需要制定itemValue和itemLabel)

add.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>$Title$</title>
</head>
<body>
    <form:form action="dataValidate"  modelAttribute="user" method="post">
      id:<form:input path="id"></form:input><form:errors path="id"></form:errors> <br/>
      name:<form:input path="name"></form:input><form:errors path="name"></form:errors><br/>
      age:<form:input path="age"></form:input><form:errors path="age"></form:errors><br/>
      gender:<form:input path="gender"></form:input><form:errors path="gender"></form:errors><br/>
      birth:<form:input path="birth"></form:input><form:errors path="birth"></form:errors><br/>
      email:<form:input path="email"></form:input><form:errors path="email"></form:errors><br/>
       <input type="submit" value="submit">
    </form:form>
</body>
</html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
 <body>
    <a href="add">添加用户</a>
 </body>
</html>

DataValidateController.java

package com.example.controller;

import com.example.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;

@Controller
public class DataValidateController {
    @RequestMapping("/dataValidate")
    public String validate(@Valid User user, BindingResult bindingResult, Model model) {
        System.out.println(user);
        if (bindingResult.hasErrors()) {
            System.out.println("验证失败");
            return "add";
        } else {
            System.out.println("验证成功");
            return "hello";
        }
    }

    @RequestMapping("add")
    public String add(Model model){
        model.addAttribute("user",new User(1,"zhangsan",12,"女",null,"1234@qq.com"));
        return "add";
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
        version="4.0"> 
   <servlet>
       <servlet-name>springmvc</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc.xml</param-value>
       </init-param>
       
   </servlet>
   <servlet-mapping>
       <servlet-name>springmvc</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>
   <filter>
       <filter-name>encoding</filter-name>
       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
       <init-param>
           <param-name>encoding</param-name>
           <param-value>UTF-8</param-value>
       </init-param>
       <init-param>
           <param-name>forceEncoding</param-name>
           <param-value>true</param-value>
       </init-param>
   </filter>
   <filter-mapping>
       <filter-name>encoding</filter-name>
       <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值