SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-002- Spring的JSP标签之form标签(<sf:input><sf:errors><sf:form>)
一、
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";
} }
SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-002- Spring的JSP标签之form标签(<sf:input><sf:errors><sf:form>)的更多相关文章
- SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-006- 使用thymeleaf(TemplateResolver、SpringTemplateEngine、ThymeleafViewResolver、th:include、th:object、th:field="*{firstName}")
一.在Spring中使用thymeleaf的步骤 1.配置 In order to use Thymeleaf with Spring, you’ll need to configure three ...
- SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-003- SPRING的GENERAL TAG LIBRARY简介及用<s:message>和ReloadableResourceBundleMessageSource实现国际化
一. SPRING支持的GENERAL TAG LIBRARY 1. 二.用<s:message>和ReloadableResourceBundleMessageSource实现国际化 1 ...
- SPRING IN ACTION 第4版笔记-第六章Rendering web views-001- Spring支持的View Resolver、InternalResourceViewResolver、JstlView
一.Spring支持的View Resolver 二.InternalResourceViewResolver Spring supports JSP views in two ways: Inte ...
- SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-005- 使用ApacheTiles(TilesConfigurer、TilesViewResolver、<put-attribute>、<t:insertAttribute>)
一. 1.定义TilesConfigurer.TilesViewResolver的bean 注意有tiles2和tiles3,这里使用tiles3 (1)java形式 package spittr.w ...
- SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-004- <s:url>、<s:escapeBody>标签
一.<s:url> <s:url>可以直接生成一个url或url变量,它会在href的基础上加上应用context 1. <a href="<s:url ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver
一.什么是multipart The Spittr application calls for file uploads in two places. When a new user register ...
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-005-Bean的作用域@Scope、ProxyMode
一. Spring的bean默认是单例的 But sometimes you may find yourself working with a mutable class that does main ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)
一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...
- SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-006Spring-Data的运行规则(@EnableJpaRepositories、<jpa:repositories>)
一.JpaRepository 1.要使Spring自动生成实现类的步骤 (1)配置文件xml <?xml version="1.0" encoding="UTF- ...
随机推荐
- linux---基本查找命令
基本查找命令 一.文件查找命令:find 最大特点:功能强大,可以使用文件的各种属性作为查找条件来查找文件 文件属性:文件权限.文件所有者.文件大小.修改时间.文件类型 语法:find[起始查找目录] ...
- ping 命令详解
Linux系统的ping命令是常用的网络命令,它通常用来测试与目标主机的连通性,我们经常会说"ping一下某机器,看是不是开着".不能打开网页时会说"你先ping网关地址 ...
- oc语言学习之基础知识点介绍(三):类方法、封装以及继承的介绍
一.类方法的使用 /* 像我们之前学的方法,必须先实例化这个类的对象才能调用这个方法,类方法不用实例化对象,直接调用这个方法. 之前学的方法调用的语法: [对象名 方法名]; //对象方法 类方法: ...
- apache http server 多线程模式
一般apache采用prefork和worker机制,通过apachectl -l命令查看默认使用的prefork机制.需要修改prefork策略 那么需要做如下修改: 1,/usr/local/ap ...
- plupload+struts2实现文件上传下载
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" ...
- DIV+CSS相对IE8的兼容问题
CSS技巧: 1.div的垂直居中问题 vertical-align:middle; 将行距增加到和整个DIV一样高 line-height:200px; 然后插入文字,就垂直居中了.缺点是要控制内容 ...
- JEditorPane中html文档中文乱码解决
Culturally dependent information in some documents is handled through a mechanism called character e ...
- iOS 隔离导航控制器
题外话:最近这两个月一直很闲,项目上基本没有啥大的需求.对于程序员来说,如果没有需求其实是一件很难受的事情,之前好多次在项目中没事找事,该优化的优化,该整理的整理.可能好多程序员都遇到过与我类似的情况 ...
- swift-计算器(斯坦福公开课)
看了斯坦福老头的课,真心觉得,我的中文怎么也变的这么垃圾了.是关于iOS8的课程,用swift写的,一个计算器应用的制作,看看人家的课,再看看咱们学校的课(不过垃圾学校,纯粹觉得大学浪费了),废话啊, ...
- TortoiseSVN本地代码版本控制设置步骤。
1.下载安装TortoiseSVN客户端. 2.在某个盘创建空的文件夹作为项目代码的版本库.在空的文件夹内部右键鼠标TortoiseSVN->Create repository here 3.在 ...