Method for Spring MVC Annotation verification, mvcannotation
Introduction
The Annotation verification of 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 complicated business logic, it is difficult to use annotation for verification.
The following is an example of annotation verification using Spring MVC and a custom @ Tel annotation verification:
1. Supports multiple languages (International)
2. Convert the default data first. For example, if the int and date types are null, an exception is thrown. The default value is
First look at the Configuration:
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>
There is nothing to say here, just add 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 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 --> <context: annotation-config/> <! -- Support for default annotation ing --> <mvc: annotation-driven validator = "validator" conversion-service = "conversionService"/> <! -- Convert the class marked with @ Controller annotation to bean --> <context: component-scan base-package = "com. my"/> <! -- View interpretation class --> <bean class = "org. springframework. web. servlet. view. internalResourceViewResolver "> <property name =" prefix "value ="/WEB-INF/views/"/> <property name =" suffix "value = ". jsp "/> <! -- Can be empty to facilitate the selection of view interpretation class Logic Based on the extension --> <property name = "viewClass" value = "org. springframework. web. servlet. view. jstlView "/> </bean> <! -- Resource file: messages. properties --> <bean id = "messageSource" class = "org. springframework. context. support. resourceBundleMessageSource "> <property name =" basenames "> <list> <value> messages </value> </list> </property> </bean> <! -- Validators --> <bean id = "validator" class = "org. springframework. validation. beanvalidation. localValidatorFactoryBean "> <property name =" validationMessageSource "ref =" messageSource "/> </bean> <! -- Custom data type converter --> <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>
Add conversion-service to <mvc: annotation-driven/> and add the default system converter to conversion-service. IntConverter and DateConverter are listed above. Of course, it can also be a custom type, which is global.
Added properties that support multiple languages to the validator validators. Of course, spring's multilingual language is based on the http header's 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; } }
This is a simple controller. In add, there is an annotation @ Valid, which is required. Without 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; }}
In addition to @ Tel, all others are spring's built-in annotation. Of course, you can also search for them by yourself.
5. message. properties
Valid. required = the field value cannot be empty valid. name = username cannot be empty valid. password = Minimum password 4-digit valid. ageMin = age cannot be less than {1} years old valid. ageMax = age cannot be greater than {1} years old valid. email = invalid email format valid. address = the contact address is incorrect. valid. birthday = birthday cannot be greater than today's valid. likesMin = the minimum value of likesMin is 1 valid. tel = the mobile phone number cannot be smaller than {min} characters
It corresponds to the annotation message Value of User4 model. To enable international languages, you only need to add a file named 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 an interface. Note that the annotation interface java is written as follows: @ 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 the verification Implementation Method of @ 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; }}
The two are global 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">
Note: In form, the modelAttribute value corresponds to the User4 class name, starting with lowercase. Otherwise, an error occurs.
9. Page UI result:
Click Add button:
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.