一、
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.一般用法
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<sf:form method="POST" commandName="spitter">
First Name:
<sf:input path="firstName" />
<br/> Last Name:
<sf:input path="lastName" />
<br/> Email:
<sf:input path="email" />
<br/> Username:
<sf:input path="username" />
<br/> Password:
<sf:password path="password" />
<br/>
<input type="submit" value="Register" />
</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。
RequestMapping(value = "/register", method = GET)
public String showRegistrationForm(Model model) {
model.addAttribute(new Spitter());
return "registerForm";
}
3.Spring form标签还支持html5,如可以指定data、range、email
<sf:input path="email" type="email" />
4.显示错误
<sf:form method="POST" commandName="spitter">
First Name:
<sf:input path="firstName" />
<sf:errors path="firstName" />
<br/> ...
</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
<sf:form method="POST" commandName="spitter">
First Name:
<sf:input path="firstName" />
<sf:errors path="firstName" cssClass="error" />
<br/> ...
</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.哪个字段有错就红色显示该字段
<sf:form method="POST" commandName="spitter">
<sf:label path="firstName" cssErrorClass="error">First Name</sf:label>:
<sf:input path="firstName" cssErrorClass="error" />
<br/> ...
</sf:form>
8.要实体类中写验证规则
package spittr; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hibernate.validator.constraints.Email; public class Spitter { private Long id; @NotNull
@Size(min=5, max=16, message="{username.size}")
private String username; @NotNull
@Size(min=5, max=25, message="{password.size}")
private String password; @NotNull
@Size(min=2, max=30, message="{firstName.size}")
private String firstName; @NotNull
@Size(min=2, max=30, message="{lastName.size}")
private String lastName; @NotNull
private String email; @Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that, "firstName", "lastName", "username", "password", "email");
} @Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, "firstName", "lastName", "username", "password", "email");
} }
9.验证信息的资源文件,可定不同的语言版本支持国际化(不知道什么时候加载的
(1)ValidationMessages.properties
firstName.size=First name must be between {min} and {max} characters long.
lastName.size=Last name must be between {min} and {max} characters long.
username.size=Username must be between {min} and {max} characters long.
password.size=Password must be between {min} and {max} characters long.
email.valid=The email address must be valid.
(2)ValidationMessages_es.properties 西班牙
firstName.size=Nombre debe ser entre {min} y {max} caracteres largo.
lastName.size=El apellido debe ser entre {min} y {max} caracteres largo.
username.size=Nombre de usuario debe ser entre {min} y {max} caracteres largo.
password.size=Contraseña debe estar entre {min} y {max} caracteres largo.
email.valid=La dirección de email no es válida
(3)webconfig.java
package spittr.web; import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration
@EnableWebMvc
@ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter { @Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
} @Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
} @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
super.addResourceHandlers(registry);
} @Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource =
new ReloadableResourceBundleMessageSource();
//messageSource.setBasename("file:///Users/habuma/messages");
//messageSource.setBasename("messages");
messageSource.setBasename("classpath:messages");
messageSource.setCacheSeconds(10);
return messageSource;
} }
10.view
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%@ page session="false" %>
<html>
<head>
<title>Spitter</title>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>Register</h1> <sf:form method="POST" commandName="spitter" >
<sf:errors path="*" element="div" cssClass="errors" />
<sf:label path="firstName"
cssErrorClass="error">First Name</sf:label>:
<sf:input path="firstName" cssErrorClass="error" /><br/>
<sf:label path="lastName"
cssErrorClass="error">Last Name</sf:label>:
<sf:input path="lastName" cssErrorClass="error" /><br/>
<sf:label path="email"
cssErrorClass="error">Email</sf:label>:
<sf:input path="email" cssErrorClass="error" /><br/>
<sf:label path="username"
cssErrorClass="error">Username</sf:label>:
<sf:input path="username" cssErrorClass="error" /><br/>
<sf:label path="password"
cssErrorClass="error">Password</sf:label>:
<sf:password path="password" cssErrorClass="error" /><br/>
<input type="submit" value="Register" />
</sf:form>
</body>
</html>
11.controller
package spittr.web; import static org.springframework.web.bind.annotation.RequestMethod.*; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import spittr.Spitter;
import spittr.data.SpitterRepository; @Controller
@RequestMapping("/spitter")
public class SpitterController { private SpitterRepository spitterRepository; @Autowired
public SpitterController(SpitterRepository spitterRepository) {
this.spitterRepository = spitterRepository;
} // @ModelAttribute
// public Spitter spitter() {
// return new Spitter();
// } @RequestMapping(value="/register", method=GET)
public String showRegistrationForm(Model model) {
model.addAttribute(new Spitter());
return "registerForm";
} @RequestMapping(value="/register", method=POST)
public String processRegistration(
@Valid Spitter spitter,
Errors errors) {
if (errors.hasErrors()) {
return "registerForm";
} spitterRepository.save(spitter);
return "redirect:/spitter/" + spitter.getUsername();
} @RequestMapping(value="/{username}", method=GET)
public String showSpitterProfile(@PathVariable String username, Model model) {
Spitter spitter = spitterRepository.findByUsername(username);
model.addAttribute(spitter);
return "profile";
} }