一、
Spring offers two JSP tag libraries to help define the view of your Spring MVC web views.
One tag library renders HTML form tags that are bound to a model attribute.
The other has a hodgepodge of utility tags that come in handy from time to time.
1.Spring支持的form标签
2.一般用法
1 <%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %> 2 <sf:form method="POST" commandName="spitter"> 3 First Name: 4 <sf:input path="firstName" /> 5 <br/> Last Name: 6 <sf:input path="lastName" /> 7 <br/> Email: 8 <sf:input path="email" /> 9 <br/> Username: 10 <sf:input path="username" /> 11 <br/> Password: 12 <sf:password path="password" /> 13 <br/> 14 <input type="submit" value="Register" /> 15 </sf:form>
path是和model里的对象的属性对应,commandName是和model的key对应,这里设定了commandName="spitter",则要保证每个返回到这个view的handler的model都要有值为"spitter"的key,所以showRegistrationForm()要修改,返回一个空对象,否则会报java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'spitter' available as request attribute。
1 RequestMapping(value = "/register", method = GET) 2 public String showRegistrationForm(Model model) { 3 model.addAttribute(new Spitter()); 4 return "registerForm"; 5 }
3.Spring form标签还支持html5,如可以指定data、range、email
<sf:input path="email" type="email" />
4.显示错误
1 <sf:form method="POST" commandName="spitter"> 2 First Name: 3 <sf:input path="firstName" /> 4 <sf:errors path="firstName" /> 5 <br/> ... 6 </sf:form>
若验证有错,会解析类似如下:
First Name: <input id="firstName" name="firstName" type="text" value="J"/> <span id="firstName.errors">size must be between 2 and 30</span>
5.可以加css
1 <sf:form method="POST" commandName="spitter"> 2 First Name: 3 <sf:input path="firstName" /> 4 <sf:errors path="firstName" cssClass="error" /> 5 <br/> ... 6 </sf:form>
span.error {color: red;}
6.错误集中显示
<sf:form method="POST" commandName="spitter">
<sf:errors path="*" element="div" cssClass="errors" />
...
</sf:form>
div.errors { background - color: #ffcccc; border: 2 px solid red; }
7.哪个字段有错就红色显示该字段
1 <sf:form method="POST" commandName="spitter"> 2 <sf:label path="firstName" cssErrorClass="error">First Name</sf:label>: 3 <sf:input path="firstName" cssErrorClass="error" /> 4 <br/> ... 5 </sf:form>
8.要实体类中写验证规则
1 package spittr; 2 3 import javax.validation.constraints.NotNull; 4 import javax.validation.constraints.Size; 5 6 import org.apache.commons.lang3.builder.EqualsBuilder; 7 import org.apache.commons.lang3.builder.HashCodeBuilder; 8 import org.hibernate.validator.constraints.Email; 9 10 public class Spitter { 11 12 private Long id; 13 14 @NotNull 15 @Size(min=5, max=16, message="{username.size}") 16 private String username; 17 18 @NotNull 19 @Size(min=5, max=25, message="{password.size}") 20 private String password; 21 22 @NotNull 23 @Size(min=2, max=30, message="{firstName.size}") 24 private String firstName; 25 26 @NotNull 27 @Size(min=2, max=30, message="{lastName.size}") 28 private String lastName; 29 30 @NotNull 31 @Email 32 private String email; 33 34 @Override 35 public boolean equals(Object that) { 36 return EqualsBuilder.reflectionEquals(this, that, "firstName", "lastName", "username", "password", "email"); 37 } 38 39 @Override 40 public int hashCode() { 41 return HashCodeBuilder.reflectionHashCode(this, "firstName", "lastName", "username", "password", "email"); 42 } 43 44 }
9.验证信息的资源文件,可定不同的语言版本支持国际化(不知道什么时候加载的
(1)ValidationMessages.properties
1 firstName.size=First name must be between {min} and {max} characters long. 2 lastName.size=Last name must be between {min} and {max} characters long. 3 username.size=Username must be between {min} and {max} characters long. 4 password.size=Password must be between {min} and {max} characters long. 5 email.valid=The email address must be valid.
(2)ValidationMessages_es.properties 西班牙
1 firstName.size=Nombre debe ser entre {min} y {max} caracteres largo. 2 lastName.size=El apellido debe ser entre {min} y {max} caracteres largo. 3 username.size=Nombre de usuario debe ser entre {min} y {max} caracteres largo. 4 password.size=Contraseña debe estar entre {min} y {max} caracteres largo. 5 email.valid=La dirección de email no es válida
(3)webconfig.java
1 package spittr.web; 2 3 import org.springframework.context.MessageSource; 4 import org.springframework.context.annotation.Bean; 5 import org.springframework.context.annotation.ComponentScan; 6 import org.springframework.context.annotation.Configuration; 7 import org.springframework.context.support.ReloadableResourceBundleMessageSource; 8 import org.springframework.web.servlet.ViewResolver; 9 import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; 10 import org.springframework.web.servlet.config.annotation.EnableWebMvc; 11 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 12 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 13 import org.springframework.web.servlet.view.InternalResourceViewResolver; 14 15 @Configuration 16 @EnableWebMvc 17 @ComponentScan("spittr.web") 18 public class WebConfig extends WebMvcConfigurerAdapter { 19 20 @Bean 21 public ViewResolver viewResolver() { 22 InternalResourceViewResolver resolver = new InternalResourceViewResolver(); 23 resolver.setPrefix("/WEB-INF/views/"); 24 resolver.setSuffix(".jsp"); 25 return resolver; 26 } 27 28 @Override 29 public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 30 configurer.enable(); 31 } 32 33 @Override 34 public void addResourceHandlers(ResourceHandlerRegistry registry) { 35 // TODO Auto-generated method stub 36 super.addResourceHandlers(registry); 37 } 38 39 @Bean 40 public MessageSource messageSource() { 41 ReloadableResourceBundleMessageSource messageSource = 42 new ReloadableResourceBundleMessageSource(); 43 //messageSource.setBasename("file:///Users/habuma/messages"); 44 //messageSource.setBasename("messages"); 45 messageSource.setBasename("classpath:messages"); 46 messageSource.setCacheSeconds(10); 47 return messageSource; 48 } 49 50 }
10.view
1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 2 <%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %> 3 <%@ page session="false" %> 4 <html> 5 <head> 6 <title>Spitter</title> 7 <link rel="stylesheet" type="text/css" 8 href="<c:url value="/resources/style.css" />" > 9 </head> 10 <body> 11 <h1>Register</h1> 12 13 <sf:form method="POST" commandName="spitter" > 14 <sf:errors path="*" element="div" cssClass="errors" /> 15 <sf:label path="firstName" 16 cssErrorClass="error">First Name</sf:label>: 17 <sf:input path="firstName" cssErrorClass="error" /><br/> 18 <sf:label path="lastName" 19 cssErrorClass="error">Last Name</sf:label>: 20 <sf:input path="lastName" cssErrorClass="error" /><br/> 21 <sf:label path="email" 22 cssErrorClass="error">Email</sf:label>: 23 <sf:input path="email" cssErrorClass="error" /><br/> 24 <sf:label path="username" 25 cssErrorClass="error">Username</sf:label>: 26 <sf:input path="username" cssErrorClass="error" /><br/> 27 <sf:label path="password" 28 cssErrorClass="error">Password</sf:label>: 29 <sf:password path="password" cssErrorClass="error" /><br/> 30 <input type="submit" value="Register" /> 31 </sf:form> 32 </body> 33 </html>
11.controller
1 package spittr.web; 2 3 import static org.springframework.web.bind.annotation.RequestMethod.*; 4 5 import javax.validation.Valid; 6 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Controller; 9 import org.springframework.ui.Model; 10 import org.springframework.validation.Errors; 11 import org.springframework.web.bind.annotation.PathVariable; 12 import org.springframework.web.bind.annotation.RequestMapping; 13 14 import spittr.Spitter; 15 import spittr.data.SpitterRepository; 16 17 @Controller 18 @RequestMapping("/spitter") 19 public class SpitterController { 20 21 private SpitterRepository spitterRepository; 22 23 @Autowired 24 public SpitterController(SpitterRepository spitterRepository) { 25 this.spitterRepository = spitterRepository; 26 } 27 28 // @ModelAttribute 29 // public Spitter spitter() { 30 // return new Spitter(); 31 // } 32 33 @RequestMapping(value="/register", method=GET) 34 public String showRegistrationForm(Model model) { 35 model.addAttribute(new Spitter()); 36 return "registerForm"; 37 } 38 39 @RequestMapping(value="/register", method=POST) 40 public String processRegistration( 41 @Valid Spitter spitter, 42 Errors errors) { 43 if (errors.hasErrors()) { 44 return "registerForm"; 45 } 46 47 spitterRepository.save(spitter); 48 return "redirect:/spitter/" + spitter.getUsername(); 49 } 50 51 @RequestMapping(value="/{username}", method=GET) 52 public String showSpitterProfile(@PathVariable String username, Model model) { 53 Spitter spitter = spitterRepository.findByUsername(username); 54 model.addAttribute(spitter); 55 return "profile"; 56 } 57 58 }