Al usar InitBinder para la verificación, algunos de los datos enviados en este controlador deben ser de naturaleza comercial, es decir, solo se utilizará en situaciones de verificación relativamente complejas. La verificación de forma más simple se puede resolver mediante la verificación de anotaciones.
Para el uso de la verificación de la anotación, consulte: http://www.vevb.com/article/136448.htm
Una cosa a tener en cuenta aquí: InitBinder y Anotation solo pueden elegir una de dos verificaciones. Si se usa InitBinder, la verificación de anotación no se puede usar.
Las configuraciones anteriores de Web.xml y Spring.xml no se repetirán, consulte la configuración en el enlace anterior. Exactamente lo mismo.
Cargue directamente el código:
1. Clase de entidad del modelo de usuario5
paquete com.my.controller.bean; import java.util.date; public class User5 {private Long id; nombre de cadena privada; contraseña de cadena privada; Fecha privada CreateTime; edad privada int; public Long getId () {return id; } public void setid (ID long) {this.id = id; } public String getName () {nombre de retorno; } public void setName (nombre de cadena) {this.name = name; } public String getPassword () {return Password; } public void setPassword (String Password) {this.password = contraseña; } fecha pública getCreateTime () {return CreateTime; } public void setCreateTime (date CreateTime) {this.CreateTime = CreateTime; } public int getAge () {return Age; } public void setAge (int Age) {this.age = edad; }}2. Agregue un nuevo validador:
paquete com.my.controller.validator; import org.springframework.stereotype.component; import org.springframework.validation.errors; import org.springframework.validation.validationutils; import og.springframework.validation.validator; import; com.my.controller.bean.user5; @ComponentPublic La clase TestValidator implementa Validator {@Override public Boolean Supports (class <?> ParamClass) {return user5.class.equals (paramClass); } @Override public void Validate (Obj OBJ, errores de errores) {user5 user = (user5) obj; ValidationUtils.RejectifemptyorWhiteSpace (errores, "nombre", "válido.name", null, ""); if (user.getage () <18) {errores.rejectValue ("edad", "válido.agemina", nuevo objeto [] {"edad", 18}, "La edad no puede ser inferior a {1} años de edad"); }}}@Component necesita ser agregado aquí y se inyecta DI
3. Controlador
paquete com.my.controller; import java.util.linkedhashmap; import java.util.list; import java.util.map; import javax.validation.valid; importar org.springframework.beans.annotation.aUtowired; import org.springframework.beans.beans.beans. org. org. org.springframework.web.servlet.modelandview; import com.my.controller.bean.user5; @controler @requestmapping (valor = "binder") clase pública testinitbinderController {@aUtowired @Qualifier (value = "testValidator") validador de validador de validador privado; @InitBinder Private Void InitBinder (WebDatabinder Binder) {Binder.SetValidator (Validator); } @RequestMapping (método = requestmethod.get) public string index () {return "/testInitBinder/index"; } @RequestMapping (valor = "add", método = requestmethod.post) public modelandView add (@modelattribute @Valid User5 User, BindingResult Result) {ModelAndView View = new ModelAndView ("testInitBinder/index"); ver.AdDObject ("usuario", usuario); if (result.haserrors ()) {list <fielderror> errs = result.getFielderRors (); Map <string, string> maperrors = new LinkedHashMap <String, String> (); for (fielderror err: errs) {system.out.println ("objectName:" + err.getObjectName () + "/tfieldName:" + err.getField () + "/tfieldvalue:" + err.getReCejedValue () + "/tMessage:" + err.getDefaultMessage ()); maperrors.put (err.getField (), err.getDefaultMessage ()); ver.AdDObject ("errores", maperrors); } Vista de retorno; } Vista de retorno; }}Inyectar validador en el controlador.
De hecho, utilizando InitBinder, el método Err.getDefaultMessage () en el controlador Agregar no puede obtener el mensaje correcto correspondiente. Puede ver el resultado final de impresión de entrada.
4. Ver
<%@ page lenguaje = "java" contentType = "text/html; charset = utf-8" pageCoding = "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 = "st" uri = "http://www.springframework.org/tags"%> <%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%> <DocType html público "-// w3c // dtd html 4.01 transmor "http://www.w3.org/tr/html4/loose.dtd"><html><head><meta http-equiv =" content-thype "content =" text/html; charset = utf-8 "> <title> init binder </tittle> </thead> <body> <form: form: acción ="/" method="post" modelAttribute="user5"> User name:<input type="text" id="name" name="name" value="${user.name}" /><br/> Password:<input type="text" id="password" name="password" value="${user.password}" /><br/> Age:<input type="text" id="age" name="age" value = "$ {user.age}"/> <br/> <input type = "subt" value = "add"/> <hr/> error: <br/> <form: errores path = "*"> </form: errores> </form: form> </body> </html>Tenga en cuenta que solo puede usar <Form: errores/> para obtener información de error, y esto <form: errores/> debe estar en <form: form/>.
5. Prueba de resultados
Haga clic en el botón Agregar:
Impresión:
Puede ver que la información correcta del error no se puede obtener aquí.
De hecho, cuando los datos enviados en una página de formulario muy complejo tienen cierta lógica comercial, InitBinder no debe usarse mucho, porque muchas veces podemos usar un mapa para insertar errores en ella y leerlo en la página. Por ejemplo:
Map <string, string> errores;
errores.add ("nombre", "¡El nombre de usuario no puede estar vacío!");
:
:
Solo necesitas usar:
<span style = "color: rojo;"> $ {errores.name} <span>Hazlo.
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.