As tags de formulário que acompanham o MVC da primavera são relativamente simples e geralmente precisam ser concluídas com a ajuda de EL e JSTL.
Aqui está uma função de página de envio de formulário relativamente simples:
1. Modelo de usuário
pacote com.my.Controller.Bean; importar java.util.date; importar java.util.list; importar javax.validation.constraints.future; importar javax.validation.COnstraints.Max; import javax.validation.constraints.min; import.validation.max; org.hibernate.validator.constraints.email; importar org.hibernate.validator.constraints.length; importar org.hibernate.validator.constraints.NOTEMPTY; usuário público usuário {private longo id; @Length (min = 2, max = 50, message = "Faixa de comprimento do nome do usuário = 2-50") Nome da sequência privada; @Future (message = "tempo não pode ser menor que hoje") data privada createTime; @NotEmpty (message = "Customer não pode estar vazio") Lista privada <Cliente> clientes; @NotNull (message = "Girl não pode estar vazio") Garota booleana privada; String privada [] CBX; @NotNull (message = "Age não pode ser nulo") @min (value = 18, message = "Mínimo 18 anos") @max (value = 100, message = "" máximo 100 anos ") private INT AGE; @Email (message = "Formato de email está incorreto") email de sequência privada; public Long getId () {return id; } public void setId (longo id) {this.id = id; } public string getName () {return name; } public void setName (nome da string) {this.name = name; } public data getCreateTime () {return createTime; } public void setCreateTime (data createTime) {this.createTime = createTime; } Lista pública <STILDOME> getCustomers () {retorna clientes; } public void setCustomers (list <luster> clientes) {this.customers = clientes; } public boolean iSGirl () {Return Girl; } public void setGirl (menina booleana) {this.Girl = Girl; } public string [] getCbx () {return cbx; } public void setCbx (string [] cbx) {this.cbx = cbx; } public int getage () {Age de retorno; } public void setage (int Age) {this.age = Age; } public String getEmail () {retornar email; } public void setEmail (string email) {this.email = email; }} 2. Controlador
pacote com.my.controller; importar java.util.ArrayList; importar java.util.date; importar java.util.list; importar javax.validation.valid; importar org.springframework.tereotype.controller; importação org.springframewring.validation.vringwork.bindings; org.springframework.validation.fielderror; importar org.springframework.web.bind.annotation.modelattribute; importar org.springframework.web.bind.annotation.requestMapping; import org.springframework.webind.bind.annotation.requestMapping; import.springframework.webind.bind.annotation.annotation.requestMappation; import.springframework.webhind.bind.annotation.requestMappation; import.springframework.webhind.bind.annotation.annotation.annotation; org.springframework.web.servlet.modlandview; importar com.my.controller.bean.customer; importar com.my.controller.bean.user;@controller@requestmapp (value = "/post") public class Testcontroller {private static <vester> {// --------------------------------------- Usuário do usuário = usuários.get (0); user.setId (1); user.setName ("Robin"); user.setCreateTime (new Date ()); user.setGirl (true); user.setCbx (new String [] {"1", "2", "3"}); user.setage (18); user.setemail ("[email protected]"); user.setCustomers (novo ArrayList <Terporwer> ()); Cliente cliente1 = novo cliente (); cliente1.setId (1); Customer1.SetCompany ("Companhia - 1"); cliente1.setCreateTime (new Date ()); cliente1.setUser (usuário); user.getCustomers (). Add (Customer1); Cliente cliente2 = novo cliente (); cliente2.setId (1); Customer2.SetCompany ("Companhia - 2"); cliente2.setCreateTime (new Date ()); cliente2.setUser (usuário); user.getCustomers (). Add (Customer2); } @RequestMapping public ModelAndView Index () {ModelAndView View = new ModelAndView ("TestPost/Index"); view.adDoBject ("Usuários", usuários); Visão de retorno; } @ReQuestMapping (value = "/addUser", método = requestMethod.post) public ModelAndView AddUser (@modelattribute @Valid Usuário do usuário, resultado BindingResult) {ModelAndView View = new ModelAndView ("Redirect:/post"); if (result.haserrors ()) {list <fielderror> erros = resultado.getfielderrors (); para (fielderror err: erros) {system.out.println ("objectName:" + err.getObjectName () + "/tfieldName:" + err.getfield () + "/tfieldValue:" + err.getRejectValue () + "/tmessage:" + err.getDefaultMessage (); } view.addobject ("usuários", usuários); Visão de retorno; } user.setId (users.size () + 1); user.getCustomers (). get (0) .SetId (1); user.getCustomers (). get (0) .setUser (usuário); usuários.add (usuário); view.adDoBject ("Usuários", usuários); Visão de retorno; }} 3. Ver
<%@ página de página = "java" contentType = "text/html; charset = utf-8" pageEncoding = "utf-8"%> <%@ página import = "com.my.controller.bean. taglib uri = "http://java.sun.com/jsp/jstl/fmt" prefix = "fmt"%> <%@ taglib uri = "http://java.sun.com/jsp/jstl/functs" = prefix = "Fn"%> uri = "http://www.springframework.org/tags" %> < %@ taglib uri = "http://www.springframework.org/tags/form" prefix = "sf" %> <! "http://www.w3.org/tr/html4/loose.dtd"><html> <head><meta http-equiv =" content-type "content =" text/html; charset = utf-8 "> <title> ÍNDICE </title> </body> <body> <body> <body> <body> <fm/bodyl/bodyl; Action = "<st: url value ="/post/adduser "> </st: url>" method = "post"> <c: foreach itens = "$ {users}" var = "user"> user: $ {user.name} <br/> Criar tempo: <fmt: formatdate = "$ {user.cretime}}}}" test = "$ {user.Girl}"> sim </c: quando> <c: quando test = "$ {! user.Girl}"> no </c: when> <c: caso contrário> n/a </c: caso contrário, </c: escolha> <br/> Caixas de seleção: <c: foreach = $ {{user.cbx} Idade: $ {user.age} <br/> E-mail: $ {user.email} <br/> <hr/> <table> <Thead> <tr style = "text-align: esquerda; Background-Color: #eee; "> <th> Nome da empresa </th> <th> Usuário </th> <th> Crie tempo </th> </tr> </thead> <tbody> <c: foreach itens =" $ {user.customers} "var =" item "> <t> <td> $ {item.company} </td> <td> <fmt: formatdate value = "$ {item.createTime}" padrony = "yyyy-mm-dd"/> </td> </td> </c: foreach> </tbody> </ tabela> <hr/> </c: para each name: <input) name = "girl" id = "isGirl" value = "true" checked = "checked"/> <Label for = "isgirl"> sim </elabel> <input type = "radio" name = "girl" id = "nogirl" value = "false"/> <etiqueta para = "nogirl"> no </etiquet> <br/> value = "1" /> <Label para = "cbx1"> 1 </elabel> <input type = "Caixa de seleção" name = "cbx" id = "cbx2" value = "2" /> <Rótulo para = "cbx2"> 2 </cret> <input Type = "caixa de seleção" name = "cbx" id = "CX3" <br/> Idade: <input type = "text" name = "idade" id = "idade"/> <br/> e-mail: <input type = "text" name = "email" id = "email"/> <br/> Criar tempo: <brut] type = "text" name = "createTime" = "cateTime"/[> <br. id = "clientes [0] .company"/> <br/> <input type = "submit" value = "add"/> <sf: erros path = "*"> </sf: erros> </form> <hr // </body> </html>4. Resultados dos testes
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.