Spring MVC Annotation验证的方法
简介说明
使用Spring MVC的Annotation验证可以直接对view model的简单数据验证,注意,这里是简单的,如果model的数据验证需要有一些比较复杂的业务逻辑性在里头,只是使用annotation做验证是比较难的。
以下是使用Spring MVC自带的annotation验证,加上自定义的一个@Tel的annotation验证例子,此例子具有:
1、支持多语言(国际化)
2、对默认数据先进行转化,比如int、date类型如果传入空值时,会抛异常,默认给定值
先看配置:
1、web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>Test Spring MVC - 1</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value></param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
这里没什么好说的,只是把spring.xml配置加入到contextConfigLocation中
2、spring.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:tx="http://www.springframework.org/schema/tx" 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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!--注解说明 --> <context:annotation-config /> <!-- 默认的注解映射的支持 --> <mvc:annotation-driven validator="validator" conversion-service="conversionService" /> <!-- 把标记了@Controller注解的类转换为bean --> <context:component-scan base-package="com.my" /> <!-- 视图解释类 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!-- 资源文件:messages.properties --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>messages</value> </list> </property> </bean> <!-- 验证器 --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="validationMessageSource" ref="messageSource"/> </bean> <!-- 自定义数据类型转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.my.controller.converter.IntConverter" /> <bean class="com.my.controller.converter.DateConverter" /> </list> </property> </bean> </beans>
在<mvc:annotation-driven/>中加入conversion-service,然后在conversion-service中加入系统默认的转换器,如上有IntConverter和DateConverter,当然,也可以是自定的别的类型,这是全局的。
在validator验证器中加入了支持多语言的properties,当然,spring的多语言是基于http header的accept-language。
3、Controller
package com.my.controller; import java.util.List; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.my.controller.bean.User4; @Controller @RequestMapping(value="av") public class TestAnnotationValidController { @RequestMapping public ModelAndView index() { ModelAndView view = new ModelAndView("/TestAnnotationValid/index", "user4", new User4()); return view; } @RequestMapping(value="/add", method=RequestMethod.POST) public ModelAndView add(@ModelAttribute @Valid User4 user, BindingResult result) { ModelAndView view = new ModelAndView("/TestAnnotationValid/index"); view.addObject("user4", user); if(result.hasErrors()) { List<FieldError> errors = result.getFieldErrors(); for(FieldError err : errors) { System.out.println("ObjectName:" + err.getObjectName() + "\tFieldName:" + err.getField() + "\tFieldValue:" + err.getRejectedValue() + "\tMessage:" + err.getDefaultMessage() + "\tCode:"); } } return view; } }
这是一个简单的controller,在add中,有一个@Valid的annotation,这是必需的,不加这个,annotation验证将不起作用
4、User4.java model实体类
package com.my.controller.bean; import java.util.Date; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; public class User4 { private long id; @NotBlank(message="{valid.name}") private String name; @Length(min=4, max=20, message="{valid.password}") private String password; @NotBlank(message="{valid.required}") @Email(message="{valid.email}") private String email; @NotNull(message="{valid.required}") private boolean married; @Min(value=18, message="{valid.ageMin}") @Max(value=100, message="{valid.ageMax}") private int age; @NotNull(message="{valid.required}") @Past(message="{valid.birthday}") private Date birthday; @Pattern(regexp="^[a-zA-Z]{2,}$", message="{valid.address}") private String address; @Size(min=1, message="{valid.likesMin}") private String[] likes; @com.my.controller.validator.Tel(message="{valid.tel}", min=3) private String tel; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean isMarried() { return married; } public void setMarried(boolean married) { this.married = married; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String[] getLikes() { return likes; } public void setLikes(String[] likes) { this.likes = likes; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } }
除了@Tel之外,其它都是spring自带的annotation,当然还有别的,自行搜索下
5、message.properties
valid.required=字段值不能为空 valid.name=用户名不能为空 valid.password=密码最小4位 valid.ageMin=年龄不能小于{1}岁 valid.ageMax=年龄不能大于{1}岁 valid.email=邮箱格式不正确 valid.address=联系地址不正确 valid.birthday=生日不能大于今天 valid.likesMin=喜好最小不能小于1个 valid.tel=手机号码不能小于{min}位
对应的是User4 model的annotation的message值。如果需要国际化的多语言,只需要加入多一个messages_en_US.properties这样名字的文件即可。
6、@Tel
package com.my.controller.validator; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy=TelValidator.class) public @interface Tel { int min() default 0; String message(); Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
新建一个interface,注意,annotation的interface java是这样写的:@interface
TelValidator:
package com.my.controller.validator; import javax.annotation.Resource; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.context.support.ResourceBundleMessageSource; public class TelValidator implements ConstraintValidator<Tel, String> { @Resource private ResourceBundleMessageSource messageSource; private Tel tel; @Override public void initialize(Tel tel) { this.tel = tel; } @Override public boolean isValid(String value, ConstraintValidatorContext constraintContext) { boolean isValid; if(value != null && value.length() >= tel.min()) { isValid = true; } else { isValid = false; } if(!isValid) { constraintContext.disableDefaultConstraintViolation(); constraintContext.buildConstraintViolationWithTemplate(tel.message()).addConstraintViolation(); } return isValid; } }
这是@Tel的验证实现方法。
7、Converter
package com.my.controller.converter; import org.springframework.core.convert.converter.Converter; public class IntConverter implements Converter<String, Integer> { @Override public Integer convert(String text) { if (text == null || "".equals(text)) { return 0; } else { try { Integer value = Integer.parseInt(text); return value; } catch (Exception e) { return 0; } } } }
package com.my.controller.converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.core.convert.converter.Converter; public class DateConverter implements Converter<String, Date> { @Override public Date convert(String text) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); try { return dateFormat.parse(text); } catch (ParseException e) { e.printStackTrace(); } return null; } }
这两个是全局的类型默认转换器。
8、测试JSP
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <%@ taglib prefix="st" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Index</title> </head> <body> <sf:form action="${pageContext.request.contextPath}/av/add" method="post" modelAttribute="user4"> User name:<sf:input path="name"/><sf:errors path="name" /><br/> Password:<sf:input path="password"/><sf:errors path="password" /><br/> E-mail:<sf:input path="email"/><sf:errors path="email" /><br/> Age:<sf:input path="age"/><sf:errors path="age" /><br/> Birthday:<sf:input path="birthday"/><sf:errors path="birthday" /><br/> Address:<sf:input path="address"/><sf:errors path="address" /><br/> Married: <sf:radiobutton path="married" label="Yes" value="true"/> <sf:radiobutton path="married" label="No" value="false"/> <sf:errors path="married" /><br/> Likes: <sf:checkbox path="likes" label="Football" value="Football"/> <sf:checkbox path="likes" label="Badminton" value="Badminton"/> <sf:checkbox path="likes" label="Pingpong" value="Pingpong"/> <sf:errors path="likes" /><br/> Tel:<sf:input path="tel"/><sf:errors path="tel" /><br/> <input type="submit" value="Add" /> <hr/> Errors:<br/><sf:errors path="*"></sf:errors> <hr/> Likes:<c:forEach items="${user4.likes}" var="item">${item},</c:forEach> </sf:form> </body> </html>
注意,在form中的modelAttribute属性值,它对应的是User4类名,小写开头,否则会出错
9、页面UI结果:
点击Add button后:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
您可能感兴趣的文章:
- SpringMVC实现表单验证功能详解
- SpringMVC下获取验证码实例详解
- springmvc拦截器登录验证示例
- 详解SpringMVC验证框架Validation特殊用法
- springmvc下实现登录验证码功能示例
- SpringMVC拦截器——实现登录验证拦截器的示例代码
- SpringMVC使用@Valid注解进行数据验证的方法
- SpringMVC实现注解式权限验证的实例
- SpringMVC Validator验证示例