Introduction
Annotation verification using Spring MVC can directly verify the simple data of the view model. Note that this is simple. If the data verification of the model requires some more complex business logic, it is difficult to use annotation for verification.
The following is annotation verification using Spring MVC, plus a custom @Tel's annotation verification example, which has:
1. Support multilingual (internationalization)
2. Convert the default data first. For example, if an int and date type is passed in an empty value, an exception will be thrown. The default given value will be given.
Let's look at the configuration first:
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 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>
There is nothing to say here, just add the spring.xml configuration to 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/spring-context-3.0.xsd 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"> <!--Annotation description--> <context:annotation-config /> <!--Default annotation mapping support-> <mvc:annotation-driven validator="validator" conversion-service="conversionService" /> <!--Convert class marked with @Controller annotation to bean --> <context:component-scan base-package="com.my" /> <!-- View Interpretation Class--> <bean> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/><!-- Can be empty, convenient to implement the logic of the view interpretation class based on the extension --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!-- Resource file: messages.properties --> <bean id="messageSource"> <property name="basenames"> <list> <value>messages</value> </list> </property> </bean> <!-- Verifier--> <bean id="validator"> <property name="validationMessageSource" ref="messageSource"/> </bean> <!-- Custom Data Type Converter--> <bean id="conversionService"> <property name="converters"> <list> <bean /> <bean /> </list> </property> </bean> </beans>
Add conversion-service to <mvc:annotation-driven/>, and then add the system default converter to conversion-service. For example, there are IntConverter and DateConverter above. Of course, it can also be customized and other types, which is global.
Multilingual properties are added to the validator validator. Of course, spring's multilingual language is based on the http header's acceptance-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; } }This is a simple controller, in add, there is an annotation of @Valid, which is required, without adding this, annotation verification will not work
4. User4.java model entity class
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; }}Apart from @Tel, the others are all annotations that come with spring. Of course, there are other ones. Search for it yourself.
5. message.properties
valid.required=The field value cannot be empty valid.name=The user name cannot be empty valid.password=The minimum password is valid.ageMin=Age cannot be less than {1} years old valid.ageMax=Age cannot be greater than {1} years old valid.email=The email format is incorrect valid.address=The contact address is incorrect valid.birthday=Birthday cannot be greater than today valid.likesMin=The minimum preference cannot be less than 1 valid.tel=The mobile phone number cannot be less than {min}The corresponding message value of the annotation of the User4 model. If you need an international multilingual, you only need to add an additional file with the name of 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 {};}Create a new interface. Note that the annotation interface java is written like this: @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; }}This is @Tel's verification implementation method.
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; }}These two are global type default converters.
8. Test 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: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>Note that the modelAttribute attribute value in form corresponds to the User4 class name, starting with lowercase, otherwise an error will occur.
9. Page UI results:
After clicking on Add button:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.