java中的接口是类吗
318
2023-02-13
Spring MVC Annotation验证的方法
简介说明
使用Spring MVC的Annotation验证可以直接对view model的简单数据验证,注意,这里是简单的,如果model的数据验证需要有一些比较复杂的业务逻辑性在里头,只是使用annotation做验证是比较难的。
以下是使用Spring MVC自带的annotation验证,加上自定义的一个@Tel的annotation验证例子,此例子具有:
1、支持多语言(国际化)
2、对默认数据先进行转化,比如int、date类型如果传入空值时,会抛异常,默认给定值
先看配置:
1、web.xml
xmlns:xsi="http://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">
xmlns:xsi="http://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">
这里没什么好说的,只是把spring.xml配置加入到contextConfigLocation中
2、spring.xml
xmlns="http://springframework.org/schema/beans" xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:tx="http://springframework.org/schema/tx" xmlns:context="http://springframework.org/schema/context" xmlns:mvc="http://springframework.org/schema/mvc" xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans-3.0.xsd http://springframework.org/schema/tx http://springframework.org/schema/tx/spring-tx-3.0.xsd http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-3.0.xsd http://springframework.org/schema/mvc http://springframework.org/schema/mvc/spring-mvc-3.0.xsd">
xmlns="http://springframework.org/schema/beans"
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:tx="http://springframework.org/schema/tx"
xmlns:context="http://springframework.org/schema/context"
xmlns:mvc="http://springframework.org/schema/mvc"
xsi:schemaLocation="http://springframework.org/schema/beans
http://springframework.org/schema/beans/spring-beans-3.0.xsd
http://springframework.org/schema/tx
http://springframework.org/schema/tx/spring-tx-3.0.xsd
http://springframework.org/schema/context
http://springframework.org/schema/context/spring-context-3.0.xsd
http://springframework.org/schema/mvc
http://springframework.org/schema/mvc/spring-mvc-3.0.xsd">
在
在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
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)http:// {
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
@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
@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
@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://springframework.org/tags" %>
<%@ taglib prefix="sf" uri="http://springframework.org/tags/form"%>
User name:
Password:
E-mail:
Age:
Birthday:
Address:
Married:
Likes:
Tel:
Errors:
Likes:
注意,在form中的modelAttribute属性值,它对应的是User4类名,小写开头,否则会出错
9、页面UI结果:
点击Add button后:
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~