Las etiquetas de formulario que vienen con Spring MVC son relativamente simples, y a menudo deben completarse con la ayuda de EL y JSTL.
Aquí hay una función de página de envío de formulario relativamente simple:
1. Modelo de usuario
paquete com.my.controller.bean; import java.util.date; import java.util.list; import javax.validation.constraints.future; import javax.validation.constaints.max; import javax.validation.constraints.min; import javax.validation.constraints.notnull; org.hibernate.validator.constraints.email; importar org.hibernate.validator.constraints.length; import. @Length (min = 2, max = 50, mensaje = "Rango de longitud de nombre de usuario = 2-50") Nombre de cadena privada; @Future (Message = "El tiempo no puede ser menor que hoy") Fecha privada CreateTime; @Notempty (mensaje = "Cliente no puede estar vacío") Lista privada <Customer> Clientes; @Notnull (mensaje = "La chica no puede estar vacía") niña booleana privada; cadena privada [] cbx; @Notnull (mensaje = "edad no puede ser nulo") @min (value = 18, mensaje = "mínimo 18 años") @max (valor = 100, mensaje = "máximo 100 años de edad") private int Age; @Mail (mensaje = "El formato de correo electrónico es incorrecto") Correo electrónico de cadena privada; 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; } fecha pública getCreateTime () {return CreateTime; } public void setCreateTime (date CreateTime) {this.CreateTime = CreateTime; } Lista pública <Customer> getCustomers () {return clientes; } public void setCustomers (List <Customer> Clientes) {this.customers = clientes; } public boolean isGirl () {return girl; } public void setgirl (boolean girl) {this.girl = girl; } public String [] getCbx () {return cbx; } public void setcbx (string [] cbx) {this.cbx = cbx; } public int getAge () {return Age; } public void setAge (int Age) {this.age = edad; } public String getEmail () {return email; } public void setEmail (correo electrónico de cadena) {this.email = correo electrónico; }} 2. Controlador
paquete com.my.controller; import java.util.arrayList; import java.util.date; import java.util.list; import javax.validation.valid; import org.springframework.stereotype.controller; import og.springframework.validation.bindingres org. org.springframework.web.servlet.modelandview; import com.my.controller.bean.customer; import com.my.controller.bean.user;@controler@requestmapping (valor = "/post") public class testPostController {private estatic list <serem> usuarios = new arrayList <usser> (); {// --------------------------------------- Usuario user = users.get (0); user.setID (1); user.setName ("Robin"); user.setCreateTime (nueva fecha ()); user.setgirl (verdadero); user.setCbx (nueva cadena [] {"1", "2", "3"}); user.setage (18); user.setEmail ("[email protected]"); user.setCustomers (New ArrayList <Customer> ()); Cliente Customer1 = New Customer (); Customer1.setID (1); Customer1.setCompany ("Compañía - 1"); Customer1.setCreateTime (nueva fecha ()); Customer1.setUser (usuario); user.getCustomers (). ADD (Customer1); Cliente Customer2 = New Customer (); customer2.setid (1); Customer2.setCompany ("Compañía - 2"); customer2.setCreateTime (nueva fecha ()); Customer2.SetUser (usuario); user.getCustomers (). ADD (Customer2); } @RequestMapping public ModelAndView index () {modelandView View = new ModelAndView ("testPost/index"); ver.AdDObject ("usuarios", usuarios); Vista de regreso; } @RequestMapping (valor = "/adduser", método = requestmethod.post) public modelandView addUser (@modelattribute @Valid User User, BindingResult Result) {ModelAndView View = new ModelAndView ("Redirect:/Post"); if (result.haserrors ()) {List <SilDerRor> errores = result.getFielderRors (); For (Fielderror Err: errores) {System.out.println ("ObjectName:" + Err.GetObjectName () + "/tfieldName:" + err.getField () + "/tfieldvalue:" + err.getRegetedValue () + "/tMessage:" + err.getDefaultMessage ()); } ver.AdDObject ("usuarios", usuarios); Vista de regreso; } user.setID (users.size () + 1); user.getCustomers (). Get (0) .SetId (1); user.getCustomers (). Get (0) .SetUser (usuario); ussers.add (usuario); ver.AdDObject ("usuarios", usuarios); Vista de regreso; }} 3. Ver
<%@ page lenguaje = "java" contentType = "text/html; charset = utf-8" PageEncoding = "utf-8"%> <%@ page import = "com.my.controller.bean.*"%> <%@ taglib uri = "http://java.sun/jsp/jstl/core" prefixy "cy"%@%@%@%@%@ st taglib uri = "http://java.sun.com/jsp/jstl/fmt" prefix = "fmt"%> <%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn"%> <%@ prefix = "st" "st" "st" "st" uri = "http://www.springframework.org/tags" %> < %@ taglib uri = "http://www.springframework.org/tags/form" prefix = "sf" %> <! doctype html público "-// w3c // dtd html transmil "" http://www.w3.org/tr/html4/loose.dtd"><html><head >meta http-equiv = "content-type" content = "text/html; charset = utf-8"> <title> índice </title> </head> <fmt> Action = "<st: url value ="/post/adduser "> </st: url>" método = "post"> <c: foreach elementos = "$ {users}" var = "user"> user: $ {user.name} <br/> create tiempo: <fmt: formatDate value = "$ {us.createtime}"/> <br/> es girl: <c: c: c: c: c: c: c: c: c: c: c: c: c: c: c: c: c: cho: COLE test = "$ {user.girl}"> sí </c: when> <c: when test = "$ {! user.girl}"> no </c: when> <c: lo contrario> n/a </a: lo contrario> </c: elegir> <br/> casillas de verificación: <c: elementos de foreach = "$ {user.cbx}" ítem "> $ {erg {{{{{{{{{}, <c: foreach items =" foreach para. Age: $ {user.age} <br/> correo electrónico: $ {user.email} <br/> <hr/> <table> <thead> <tr style = "text-align: izquierda; backgro con-color: #eee; "> <th> nombre de la empresa </th> <th> user </th> <th> crea tiempo </th> </tr> </thead> <tbody> <c: foreach elementos =" $ {user.customers} "var =" item "> <tr> <td> $ {item.comPany} </td> <TD> $ {erg. <TD> <fmt: formatDate value = "$ {item.createTime}" patrón = "aaa yyy-mm-dd"/> </td> </td> </c: foreach> </bbody> </table> <hr/> </c: foreach> nombre de usuario: <input type = "text" name = "name" id = "name"/> <> es <br/> es gemel: <bray " name = "girl" id = "isGirl" value = "true" checked = "checked"/> <etiqueta for = "isGirl"> yes </label> <input type = "radio" name = "girl" id = "nogirl" value = "false"/> <etiqueta for = "nogirl"> no </etiqueta> <br/> chechBoxs: <input type = "checkBox" name = "cbx" id = "oval" /> <etiqueta for = "cbx1"> 1 </selet> <input type = "checkBox" name = "cbx" id = "cbx2" valor = "2"/> <etiqueta for = "cbx2"> 2 </sello> <input type = "checkBox" name = "cbx" id = "cbx3" valor = "3"/> <etiqueta para = "cbx3"> 3 </selabe type = "text" name = "age" id = "edad" /> <br/> e-correo electrónico: <input type = "text" name = "correo electrónico" id = "correo electrónico" /> <br/> create tiempo: <input type = "text" name = "createTime" id = "createTime" /> <br/> Company: <input type = "text" name = "clientes [0] .company" Id = "CLECTS [0] .Company. <input type = "subt" value = "add"/> <sf: errores path = "*"> </sf: errores> </form> <hr // </body> </html>4. Resultados de la prueba
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.