本章节内容很丰富,主要有基本的表单操作,数据的格式化,数据的校验,以及提示信息的国际化等实用技能。
首先看效果图
项目结构图
接下来用代码重点学习SpringMVC的表单操作,数据格式化,数据校验以及错误提示信息国际化。请读者将重点放在UserController.java,User.java,input.jsp三个文件中。
maven 项目必不可少的pom.xml文件。里面有该功能需要的所有jar包。
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.springmvc
springmvc
0.0.1-SNAPSHOT
war
maven-compiler-plugin
1.7
1.7
UTF-8
4.1.3.RELEASE
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-core
${spring.version}
org.springframework
spring-web
${spring.version}
javax.servlet
javax.servlet-api
4.0.0
provided
javax.servlet
jstl
1.2
taglibs
standard
1.1.2
javax.servlet.jsp
jsp-api
2.2
provided
org.hibernate
hibernate-validator
5.4.1.Final
javax.validation
validation-api
1.1.0.Final
SpringMVC的核心配置文件
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
class="org.springframework.context.support.ResourceBundleMessageSource">
以上是准备工作。下面开始核心代码介绍。
数据的校验思路:
第一步,在实体类中指定属性添加校验注解(如@NotEmpty),
第二步,在控制层目标方法实体类参数添加注解@Valid,
第三步,在返回页面加上显示提示错误信息
数据格式化思路:只需要在实体类中加上注解即可。
信息国际化思路:
第一步,在SpringMVC配置文件中配置国际化资源文件
第二步,创建文件i18n_zh_CN.properties文件
第三步,在i18n_zh_CN.properties文件配置国际化信息(要严格按照SpringMVC的语法)
UserController.java,两个重点知识。一个是SpringMVC的rest风格的增删改查。另一个是@Valid注解用法。具体看代码。
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.itdragon.springmvc.crud.dao.PositionDao;
import com.itdragon.springmvc.crud.dao.UserDao;
import com.itdragon.spring