1SpringMVC
2WebDataBinder
3(conversionService )Stringjava.util.Date
4(Validate)----Validate----Hibernate(JSR303)
5(bindingResult)
1SpringMVC**
1SpringMVC
导入springmvcjar
commons-logging-1.1.3.jar
log4j-1.2.17.jar
spring-aop-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
配置配置文件:
log4j.properties
# Global logging configuration log4j.rootLogger=INFO, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
Springmvc
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <context:component-scan base-package="com.tcent"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:annotation-driven></mvc:annotation-driven> <mvc:default-servlet-handler /> </beans>
web.xml中的配置内容:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>tag</display-name> <!-- 解决中文乱码的filter --> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 支持restful风格的filter --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>springDispatcherServlet</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> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
2Person瀵硅薄
public class Person { private Integer id; private String name; private Date birthDate; private String email; private BigDecimal salary;
3webContentjsp
springMVCformRequestbean瀵硅薄
method="delete" methodcrudrestful
addPerson.jsp:
<body> <!-- springMVC的标签form标签可以关联Request域中bean对象 我们在隐含模型中保存的key值。也一定要跟form:form标签中的modelAttribute值对应上。 --> 这里是添加用户页面 <form:form action="${ pageContext.request.contextPath }/addPerson" method="delete" modelAttribute="person"> name:<form:input path="name"/><br/> <%-- birthDate:<form:input path="birthDate"/><br/> --%> email:<form:input path="email"/><br/> salary:<form:input path="salary"/><br/> <input type="submit" /> </form:form> </body>
4PersonController
formpojo瀵硅薄
@Controller public class PersonController { @RequestMapping(value = "/toAddPerson") public String toAddPerson(Map<String, Object> map) { System.out.println("经过toAddPerson方法"); // 隐含模型中必须要有一个form标签对应的pojo对象 map.put("person", new Person(12, "wzg168", null, "wzg168@qq.com", new BigDecimal(30000))); return "addPerson"; } @RequestMapping(value = "/addPerson") public String addPerson(Person person) { System.out.println("添加用户【" + person + "】到数据库"); return "redirect:/index.jsp"; } }
2WebDataBinder
2.1WebDataBinder
在SpringMVC中有WebDataBinder类。这个类专门用来负责将请求参数。以及请求参数,等功能。
在WebDataBinder类中分别处理三种不同的功能。
(1)conversionService Controller
converters:在ConversionService组件中需要各种类型转换器,在conversionService组件中需要依赖于各种转换器类去实现转换工作。
(2)validators 负责验证传入的参数值是否合法。
(3)bindingResult 负责接收验证后的错误信息。
下图展示了WebDataBinderConversionServiceConverter

如果我们要自定义请求参数的类型转换器。需要实现org.springframework.core.convert.converter.Converter<S,T>接口。
然后注入到ConversionServiceConversionServiceWebDataBinderConversionService
org.springframework.format.support.FormattingConversionServiceFactoryBean对象。
3(conversionService )Stringjava.util.Date
方法一:Stringjava.util.Date
/** * 自定义 String转换成为java.util.Date类 * */ public class MyStringToDateConverter implements Converter<String, Date> { // 字符串和日期类型相互转换的工具类 private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); /** * convert就是转换器工作时调用的转换方法<br/> * 参数source就是客户端传递过来的值。 */ @Override public Date convert(String source) { // 以下情况上null,无法转换 if (source == null) { return null; } if (source != null && "".equals(source.trim())) { return null; } try { // 将日期 字符串转换成为 java.util.Date类型 return sdf.parse(source); } catch (ParseException e) { e.printStackTrace(); throw new IllegalArgumentException("Invalid Date value '" + source + "'"); } } }
springmvc
<!-- 配置FormattingConversionServiceFactoryBean去创建ConversionService组件,用于类型转换 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <!-- 将自己定义的各种Converter转换器。注入到ConversionService中 --> <property name="converters"> <set> <bean class="com.tcent.converter.MyStringToDateConverter" /> </set> </property> </bean> <!-- 静态资源的支持 --> <mvc:default-servlet-handler/> <!-- springmvc注解驱动 --> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
ConversionServiceWebDataBinder:mvc
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
3.1@DateTimeFormat注解类型转换器
方法二:Stringjava.util.Date
DateStringDate
patternyyyy-MM-dd hh:mm:ss
yyyy4位
MM 2位
dd 2位
hh 2位
mm 2位
ss 2位

4(Validate)----Validate----Hibernate
JavaEE6.0JSR303
而这些规范的实现。我们使用现在业内比较认可的Hibernate-Validate验证
@AssertTrue | 用于booleantrue |
@AssertFalse | 该字段的值只能为false |
@CreditCardNumber | 对信用卡号进行一个大致的验证 |
@DecimalMax | 只能小于或等于该值 |
@DecimalMin | 只能大于或等于该值 |
@Digits(integer=,fraction=) | 检查是否是一种数字的整数、分数, |
检查是否是一个有效的email | |
@Future | 检查该字段的日期是否是属于将来的日期 |
@Length(min=,max=) | 检查所属的字段的长度是否在minmax, |
@Max | 该字段的值只能小于或等于该值 |
@Min | 该字段的值只能大于或等于该值 |
@NotNull | 不能为null |
@NotBlank | 不能为空,检查时会将空格忽略 |
@NotEmpty | 不能为空,这里的空是指空字符串 |
@Null | 检查该字段为空 |
@Past | 检查该字段的日期是在过去 |
@Pattern(regex=,flag=) | 被注释的元素必须符合指定的正则表达式 |
@Range(min=,max=,message=) | 被注释的元素必须在合适的范围内 |
@Size(min=, max=) | 检查该字段的sizeminmaxMap |
@URL(protocol=,host,port) | 检查是否是一个有效的URLprotocolhostURL |
Hiberante
1、Hibernatejar
classmate-0.8.0.jar
hibernate-validator-5.0.0.CR2.jar
hibernate-validator-annotation-processor-5.0.0.CR2.jar
jboss-logging-3.1.1.GA.jar
validation-api-1.1.0.CR1.jar
bean
public class Person { private Integer id; /** * @NotNull表示验证当前name属性不能为null值<br/> * @Length(min = 5, max = 12)表示验证name属性最小5位,最大12位 */ @NotNull @Length(min = 5, max = 12) private String name; /** * @Past 表示日期的值必须是过去的时间 */ @Past @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthDate; /** * @Email 表示当前email属性必须是合法的邮箱格式 */ @Email private String email; /** * @Max(value = 100) 表示当前salary的值不能大于100 */ @Max(value = 100) private BigDecimal salary;
3、Controllerbean@Valid,以及在验证对象后跟一个BindingResult 对象用于接收验证的错误信息
/** * @Valid Person person=====@Valid表示要验证当前这个person对象的数据<br/> * BindingResult personBindingResult用来接收前面一个pojo对象验证的错误信息。 */ @RequestMapping(value = "/addPerson") public String addPerson(@Valid Person person, BindingResult personBindingResult) { // 判断输入的数据是否有错误, if (personBindingResult.hasErrors()) { System.out.println("*********************************************"); System.out.println( personBindingResult.getAllErrors() ); System.out.println("*********************************************"); return "addPerson"; } System.out.println("添加用户【" + person + "】到数据库"); return "redirect:/index.jsp"; }
4、SpringMVCform<form:errors path="" />
<body> <!-- springMVC的标签form标签可以关联Request域中bean对象 我们在隐含模型中保存的key值。也一定要跟form:form标签中的modelAttribute值对应上。 --> 这里是添加用户页面 <form:form action="${ pageContext.request.contextPath }/addPerson" method="delete" modelAttribute="person"> name:<form:input path="name"/><form:errors path="name" /><br/> birthDate:<form:input path="birthDate"/><form:errors path="birthDate" /><br/> email:<form:input path="email"/><form:errors path="email" /><br/> salary:<form:input path="salary"/><form:errors path="salary" /><br/> <input type="submit" /> </form:form> </body>
5(bindingResult)
5.1
key
1 Pattern.bean.property
说明: ..
示例:Email.person.email------------personemailEmail
2 Pattern.property
说明: .
示例:Email.email-----------emailEmail
3 Pattern.javaType
说明: .
示例:Email.java.lang.String-----------StringEmail
key4 Pattern
说明: 校验格式
示例:Email-----------Email
key
1 typeMismatch.bean.property
说明: 类型不匹配..
示例:typeMismatch.person.birthDate-----------personbirthDate
2 typeMismatch.property
说明: 类型不匹配.
示例:typeMismach.birthDate-----------任何对象的birthDate属性转换失败
3 typeMismatch.javaType
说明: .
示例:typeMismach.java.util.Date ----------- Java.util.Date
4 typeMismatch
说明: 类型不匹配
示例:typeMismach-----------字段类型转换失败
5.2

validate.properties
Email.person.email=\u81EA\u5B9A\u4E49-\u90AE\u7BB1\u683C\u5F0F\u4E0D\u5408\u6CD5 NotNull=\u81EA\u5B9A\u4E49-\u503C\u4E0D\u80FD\u4E3A\u7A7A Length.name=\u81EA\u5B9A\u4E49-\u957F\u5EA6\u5FC5\u987B\u4E3A 5 \u5230 12 \u4F4D Past=\u81EA\u5B9A\u4E49-\u65F6\u95F4\u5FC5\u987B\u662F\u8FC7\u53BB\u7684\u65F6\u95F4 Max=\u81EA\u5B9A\u4E49-\u503C\u4E0D\u80FD\u5927\u4E8E 100 typeMismatch=\u81EA\u5B9A\u4E49-\u4E0D\u8981\u968F\u4FBF\u8F93\u5165
16(~_`~)
占位符的使用:
{0}表示第一个传入的参数。 {0}
Length.name=\u81EA\u5B9A\u4E49-\u957F\u5EA6\u5FC5\u987B\u4E3A {0} \u5230 12 \u4F4D Max=\u81EA\u5B9A\u4E49-\u503C\u4E0D\u80FD\u5927\u4E8E {0}
5.3Spring
<!-- 告诉Spring容器,去加载自定义的错误信息 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="validate" /> </bean>