1 Validation(了解)
b/s系统中对http请求数据的校验多数在客户端进行,这也是出于简单及用户体验性上考虑,但是在一些安全性要求高的系统中服务端校验是不可缺少的,本节主要学习springmvc实现控制层添加校验。
Spring3支持JSR-303验证框架,JSR-303 是JAVA EE 6 中的一项子规范,叫做BeanValidation,官方参考实现是Hibernate Validator(与Hibernate ORM 没有关系),JSR 303 用于对Java Bean 中的字段的值进行验证。
1.1 需求
在商品信息修改提交时对商品信息内容进行校验,例如商品名称必须输入,价格合法性校验。
1.2 加入jar包
1.3 配置validator
<!--校验器 -->
<beanid="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!--校验器-->
<property name="providerClass"value="org.hibernate.validator.HibernateValidator"/>
<!--指定校验使用的资源文件,如果不指定则默认使用classpath下的ValidationMessages.properties -->
<property name="validationMessageSource"ref="messageSource"/>
</bean>
<!--校验错误信息配置文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!--资源文件名-->
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<!-- 资源文件编码格式 -->
<property name="fileEncodings"value="utf-8"/>
<!-- 对资源文件内容缓存时间,单位秒 -->
<property name="cacheSeconds"value="120"/>
</bean>
1.4 将validator加到处理器适配器
1.4.1 配置方式1
<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
1.4.2 配置方式2(自学)
<!--自定义webBinder -->
<bean id="customBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator"ref="validator"/>
</bean>
<!--注解适配器 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer"ref="customBinder"></property>
</bean>
1.4 添加验证规则
publicclass Items {
private Integerid;
@Size(min=1,max=30,message="{item.name.length.error}")
private Stringname;
@NotEmpty(message="{pic.is.null}")
private Stringpic;
1.6 错误消息文件CustomValidationMessages
item.name.length.error=商品名称在1到30个字符之间
pic.is.null=请上传图片
如果在eclipse中编辑properties文件无法看到中文则参考“Eclipse开发环境配置-indigo.docx”添加propedit插件。
1.7 捕获错误
修改Controller方法:
//商品修改提交
@RequestMapping("/editItemSubmit")
public String editItemSubmit(@Validated@ModelAttribute("item") Itemsitems,BindingResult result,
@RequestParam("pictureFile") MultipartFile[] pictureFile,Model model)
throws Exception {
//如果存在校验错误则转到商品修改页面
if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
for(ObjectError objectError:errors){
System.out.println(objectError.getCode());
System.out.println(objectError.getDefaultMessage());
}
return"item/editItem";
}
注意:添加@Validated表示在对items参数绑定时进行校验,校验信息写入BindingResult中,在要校验的pojo后边添加BingdingResult,一个BindingResult对应一个pojo,且BingdingResult放在pojo的后边。
商品修改页面显示错误信息:
页头:
<%@page language="java"contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt"
<%@taglib prefix="spring"uri="http://www.springframework.org/tags"%>
在需要显示错误信息地方:
<spring:hasBindErrorsname="item">
<c:forEachitems="${errors.allErrors}"var="error">
${error.defaultMessage}<br/>
</c:forEach>
</spring:hasBindErrors>
说明:
<spring:hasBindErrorsname="item">表示如果item参数绑定校验错误下边显示错误信息。
上边的方法也可以改为:
在controller方法中将error通过model放在request域,在页面上显示错误信息:
controller方法:
if(bindingResult.hasErrors()){
model.addAttribute("errors", bindingResult);
}
页面:
<c:forEachitems="${errors.allErrors}"var="error">
${error.defaultMessage }<br/>
</c:forEach>
1.8 分组校验
如果两处校验使用同一个Items类则可以设定校验分组,通过分组校验可以对每处的校验个性化。
需求:商品修改提交只校验商品名称长度
定义分组:
分组就是一个标识,这里定义一个接口:
publicinterface ValidGroup1 {
}
publicinterface ValidGroup2 {
}
指定分组校验:
publicclass Items {
private Integerid;
//这里指定分组ValidGroup1,此@Size校验只适用ValidGroup1校验
@Size(min=1,max=30,message="{item.name.length.error}",groups={ValidGroup1.class})
private Stringname;
//商品修改提交
@RequestMapping("/editItemSubmit")
public String editItemSubmit(@Validated(value={ValidGroup1.class})@ModelAttribute("item") Items items,BindingResultresult,
@RequestParam("pictureFile") MultipartFile[] pictureFile,Model model)
throws Exception {
在@Validated中添加value={ValidGroup1.class}表示商品修改使用了ValidGroup1分组校验规则,也可以指定多个分组中间用逗号分隔,
@Validated(value={ValidGroup1.class,ValidGroup2.class })
1.9 校验注解
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max=, min=) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
Hibernate Validator 附加的constraint
@NotBlank(message =) 验证字符串非null,且长度必须大于0
@Email 被注释的元素必须是电子邮箱地址
@Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串的必须非空
@Range(min=,max=,message=) 被注释的元素必须在合适的范围内
2 数据回显
2.1 需求
表单提交失败需要再回到表单页面重新填写,原来提交的数据需要重新在页面上显示。
2.2 简单数据类型
对于简单数据类型,如:Integer、String、Float等使用Model将传入的参数再放到request域实现显示。
如下:
@RequestMapping(value="/editItems",method={RequestMethod.GET})
public String editItems(Model model,Integer id)throws Exception{
//传入的id重新放到request域
model.addAttribute("id", id);
2.3 pojo类型
springmvc默认支持pojo数据回显,springmvc自动将形参中的pojo重新放回request域中,request的key为pojo的类名(首字母小写),如下:
controller方法:
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Integer id,ItemsCustom itemsCustom)throws Exception{
springmvc自动将itemsCustom放回request,相当于调用下边的代码:
model.addAttribute("itemsCustom", itemsCustom);
jsp页面:
页面中的从“itemsCustom”中取数据。
如果key不是pojo的类名(首字母小写),可以使用@ModelAttribute完成数据回显。
@ModelAttribute作用如下:
1、绑定请求参数到pojo并且暴露为模型数据传到视图页面
此方法可实现数据回显效果。
//商品修改提交
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Model model,@ModelAttribute("item")ItemsCustomitemsCustom)
页面:
<tr>
<td>商品名称</td>
<td><inputtype="text"name="name"value="${item.name }"/></td>
</tr>
<tr>
<td>商品价格</td>
<td><inputtype="text"name="price"value="${item.price }"/></td>
</tr>
如果不用@ModelAttribute也可以使用model.addAttribute("item", itemsCustom)完成数据回显。
2、将方法返回值暴露为模型数据传到视图页面
//商品分类
@ModelAttribute("itemtypes")
public Map<String, String> getItemTypes(){
Map<String, String> itemTypes = newHashMap<String,String>();
itemTypes.put("101", "数码");
itemTypes.put("102", "母婴");
returnitemTypes;
}
页面:
商品类型:
<selectname="itemtype">
<c:forEach items="${itemtypes }"var="itemtype">
<option value="${itemtype.key }">${itemtype.value }</option>
</c:forEach>
</select>
3 异常处理器
springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。
3.1 异常处理思路
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throwsException向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
3.2 自定义异常类
为了区别不同的异常通常根据异常类型自定义异常类,这里我们创建一个自定义系统异常,如果controller、service、dao抛出此类异常说明是系统预期处理的异常信息。
publicclass CustomException extends Exception {
/** serialVersionUID*/
privatestatic finallong serialVersionUID = -5212079010855161498L;
public CustomException(Stringmessage){
super(message);
this.message =message;
}
//异常信息
private Stringmessage;
public String getMessage() {
returnmessage;
}
publicvoid setMessage(String message) {
this.message = message;
}
}
3.3 自定义异常处理器
publicclass CustomExceptionResolver implementsHandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequestrequest,
HttpServletResponse response, Object handler, Exceptionex) {
ex.printStackTrace();
CustomException customException =null;
//如果抛出的是系统自定义异常则直接转换
if(exinstanceof CustomException){
customException = (CustomException)ex;
}else{
//如果抛出的不是系统自定义异常则重新构造一个未知错误异常。
customException = new CustomException("未知错误,请与系统管理员联系!");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", customException.getMessage());
modelAndView.setViewName("error");
returnmodelAndView;
}
}
3.4 错误页面
<%@page language="java"contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPEhtmlPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>错误页面</title>
</head>
<body>
您的操作出现错误如下:<br/>
${message }
</body>
</html>
3.5 异常处理器配置
在springmvc.xml中添加:
<!--异常处理器 -->
<bean id="handlerExceptionResolver"class="com.hsl.ssm.controller.exceptionResolver.CustomExceptionResolver"/>
3.6 异常测试
修改商品信息,id输入错误提示商品信息不存在。
修改controller方法“editItem”,调用service查询商品信息,如果商品信息为空则抛出异常:
//调用service查询商品信息
Items item = itemService.findItemById(id);
if(item ==null){
thrownew CustomException("商品信息不存在!");
}
在service中抛出异常方法同上。
4 上传图片
4.1 配置虚拟目录
在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:
<Context docBase="F:\develop\upload\temp"path="/pic" reloadable="false"/>
访问http://localhost:8080/pic即可访问F:\develop\upload\temp下的图片。
也可以通过eclipse配置:
4.2 配置解析器
<!--文件上传 -->
<beanid="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
4.3 jar包
CommonsMultipartResolver解析器依赖commons-fileupload和commons-io,加入如下jar包:4.4 图片上传
u controller:
//商品修改提交
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Items items, MultipartFilepictureFile)throws Exception{
//原始文件名称
String pictureFile_name = pictureFile.getOriginalFilename();
//新文件名称
String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf("."));
//上传图片
File uploadPic = new java.io.File("F:/develop/upload/temp/"+newFileName);
if(!uploadPic.exists()){
uploadPic.mkdirs();
}
//向磁盘写文件
pictureFile.transferTo(uploadPic);
.....
u 页面:
form添加enctype="multipart/form-data":
<formid="itemForm"
action="${pageContext.request.contextPath}/item/editItemSubmit.action"
method="post" enctype="multipart/form-data">
<input type="hidden"name="pic"value="${item.pic }"/>
file的name与controller形参一致:
<tr>
<td>商品图片</td>
<td><c:iftest="${item.pic !=null}">
<img src="/pic/${item.pic}"width=100height=100/>
<br />
</c:if><input type="file"name="pictureFile"/></td>
</tr>
5 json数据交互
5.1 @RequestBody
作用:
@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容转换为json、xml等格式的数据并绑定到controller方法的参数上。
本例子应用:
@RequestBody注解实现接收http请求的json数据,将json数据转换为java对象
5.2 @ResponseBody
作用:
该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端
本例子应用:
@ResponseBody注解实现将controller方法返回对象转换为json响应给客户端
5.3 请求json,响应json实现:
5.3.1 环境准备
Springmvc默认用MappingJacksonHttpMessageConverter对json数据进行转换,需要加入jackson的包,如下:5.3.2 配置json转换器
在注解适配器中加入messageConverters
<!--注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<propertyname="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
</bean>
注意:如果使用<mvc:annotation-driven/> 则不用定义上边的内容。
5.3.3 controller编写
//商品修改提交json信息,响应json信息
@RequestMapping("/editItemSubmit_RequestJson")
public@ResponseBody Items editItemSubmit_RequestJson(@RequestBody Items items)throws Exception {
System.out.println(items);
//itemService.saveItem(items);
return items;
}
5.3.4 页面js方法编写:
引入 js:
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/jquery-1.4.4.min.js"></script>
//请求json响应json
function request_json(){
$.ajax({
type:"post",
url:"${pageContext.request.contextPath }/item/editItemSubmit_RequestJson.action",
contentType:"application/json;charset=utf-8",
data:'{"name":"测试商品","price":99.9}',
success:function(data){
alert(data);
}
});
}
5.3.5 测试结果:
5.4 请key/value,响应json实现:
表单默认请求application/x-www-form-urlencoded格式的数据即key/value,通常有post和get两种方法,响应json数据是为了方便客户端处理,实现如下:
5.4.1 环境准备
同第一个例子
5.4.2 controller编写
// 商品修改提交,提交普通form表单数据,响应json
@RequestMapping("/editItemSubmit_ResponseJson")
public@ResponseBody Items editItemSubmit_ResponseJson(Items items)throws Exception {
System.out.println(items);
// itemService.saveItem(items);
return items;
}
5.4.3 页面js方法编写:
function formsubmit(){
var user =" name=测试商品&price=99.9";
alert(user);
$.ajax(
{
type:'post',//这里改为get也可以正常执行
url:'${pageContext.request.contextPath}/item/editItemSubmit_RequestJson.action',
//ContentType没指定将默认为:application/x-www-form-urlencoded
data:user,
success:function(data){
alert(data.name);
}
}
)
}
从上边的js代码看出,已去掉ContentType的定义,ContentType默认为:application/x-www-form-urlencoded格式。
5.4.4 测试结果
从上图可以看出请求的数据是标准的key/value格式。
5.5 小结
实际开发中常用第二种方法,请求key/value数据,响应json结果,方便客户端对结果进行解析。
6 RESTful支持
6.1 需求
RESTful方式实现商品信息查询,返回json数据
6.2 添加DispatcherServlet的rest配置
<servlet>
<servlet-name>springmvc-servlet-rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc-servlet-rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
6.3 URL 模板模式映射
@RequestMapping(value="/viewItems/{id}"):{×××}占位符,请求的URL可以是“/viewItems/1”或“/viewItems/2”,通过在方法中使用@PathVariable获取{×××}中的×××变量。
@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上。
@RequestMapping("/viewItems/{id}")
public @ResponseBody viewItems(@PathVariable("id") String id,Modelmodel)throws Exception{
//方法中使用@PathVariable获取useried的值,使用model传回页面
//调用 service查询商品信息
ItemsCustom itemsCustom =itemsService.findItemsById(id);
return itemsCustom;
}
如果RequestMapping中表示为"/viewItems/{id}",id和形参名称一致,@PathVariable不用指定名称。
6.4 静态资源访问<mvc:resources>
如果在DispatcherServlet中设置url-pattern为 /则必须对静态资源进行访问处理。
spring mvc 的<mvc:resourcesmapping="" location="">实现对静态资源进行映射访问。
如下是对js文件访问配置:
<mvc:resources location="/js/"mapping="/js/**"/>