转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7085268.html
前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十五)——SpringMVC注解开发(基础篇)
本文主要内容:
(1)SpringMVC校验
(2)数据回显
(3)异常处理器
(4)图片上传
(5)Json数据交互
(6)支持RESTful
1.SpringMVC校验
1.1校验理解
项目中,通常使用较多的是前端的校验,比如页面中js校验。对于安全要求较高的建议在服务器进行校验。
服务器校验:
控制层controller:校验页面请求的参数的合法性。在服务端控制层controller校验,不区分客户端类型(浏览器、手机客户端、远程调用)
业务层service(使用较多):主要校验关键业务参数,仅限于service接口中使用的参数。
持久层dao:一般是不校验的。
1.2springmvc校验需求
springmvc使用hibernate的校验框架validation(和hibernate没有任何关系)。
校验思路:
页面提交请求的参数,请求到controller方法中,使用validation进行校验。如果校验出错,将错误信息展示Dao页面。
具体需求:
商品修改,添加校验(校验商品名称长度、生成日期的非空校验),如果校验出错,在商品修改页面显示错误信息。
1.3环境准备
hibernate的校验框架validation所需要jar包:
1.4配置校验器
在classpath下springmvc.xml中配置:
<!-- 校验器 --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <!-- Hibernate校验器--> <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.5将validator注入到处理器适配器中
在classpath下springmvc.xml中配置:
1.5.1配置方式1
1.5.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.6在pojo中添加校验规则
在ItemsCustom.java中添加校验规则:
/** * 商品信息的扩展类 * @author Joanna.Yan * */ public class ItemsCustom extends Items{ //添加商品信息的扩展属性 }
这里ItemsCustom直接继承的是Items,所以我们在Items中添加:
1.7CustomValidationMessages.properties
在classpath下新建CustomValidationMessages.properties文件,配置校验错误信息:
1.8捕获校验错误信息
一个BindingResult对应一个pojo。
1.9在页面显示校验错误信息
1.9.1方式一
在controller中将错误信息传到页面即可。
//商品信息修改提交 //在需要校验的pojo前添加@Validated,在需要校验的pojo后边添加BindingResult bindingResult接收校验出错信息 //注意:@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。 @RequestMapping("/editItemsSubmit") public String editItemsSubmit(Model model,HttpServletRequest request,Integer id, @Validated ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception{ //获取校验错误信息 if(bindingResult.hasErrors()){ List<ObjectError> allErrors=bindingResult.getAllErrors(); for (ObjectError objectError : allErrors) { System.out.println(objectError.getDefaultMessage()); } //将错误信息传到页面 model.addAttribute("allErrors", allErrors); //出错,重新到商品页面 return "items/editItems"; } //调用service更新商品信息,页面需要将商品信息传到此方法 itemsService.updateItems(id, itemsCustom); //重定向到商品的查询列表 // return "redirect:queryItems.action"; //页面转发 // return "forward:queryItems.action"; return "success"; }
页面显示错误信息:
<c:if test="${allErrors!=null }"> <c:forEach items="${allErrors }" var="error"> ${error.defaultMessage }<br/> </c:forEach> </c:if>
1.9.2方式二
修改Controller方法:
//商品信息修改提交 //在需要校验的pojo前添加@Validated,在需要校验的pojo后边添加BindingResult bindingResult接收校验出错信息 //注意:@Validated和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。 @RequestMapping("/editItemsSubmit") public String editItemsSubmit(Model model,HttpServletRequest request,Integer id, @Validated ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception{ //获取校验错误信息 if(bindingResult.hasErrors()){ List<ObjectError> allErrors=bindingResult.getAllErrors(); for (ObjectError objectError : allErrors) { System.out.println(objectError.getDefaultMessage()); }//出错,重新到商品页面 return "items/editItems"; } //调用service更新商品信息,页面需要将商品信息传到此方法 itemsService.updateItems(id, itemsCustom); //重定向到商品的查询列表 // return "redirect:queryItems.action"; //页面转发 // return "forward:queryItems.action"; return "success"; }
商品修改页面显示错误信息:
页头:
<%@ 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:hasBindErrors name="item"> <c:forEach items="${errors.allErrors}" var="error"> ${error.defaultMessage }<br/> </c:forEach> </spring:hasBindErrors>
<spring:hasBindErrors name="item">表示如果item参数绑定校验错误下边显示错误信息。
1.10分组校验
1.10.1需求
在pojo中定义校验规则,而pojo是被多个controller所共用,当不同的controller方法对同一个pojo进行校验,但是每个controller方法需要不同的校验。
解决方法:
定义多个校验分组(其实是一个java接口),分组中定义有哪些规则。
每个controller方法使用不同的校验分组。
1.10.2校验分组
/** * 校验分组 * @author Joanna.Yan * */ public interface ValidGroup1 { //接口中不需要定义任何方法,仅是对不同的校验规则进行分组 //此分组只校验商品名称长度 }
/** * 校验分组 * @author Joanna.Yan * */ public interface ValidGroup2 { //接口中不需要定义任何方法,仅是对不同的校验规则进行分组 }
1.10.3在校验规则中添加分组
1.10.4在controller方法中使用指定分组的校验
1.10.4校验注解
@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.2pojo数据回显方法
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") ItemsCustom itemsCustom)
页面:
<tr> <td>商品名称</td> <td><input type="text" name="name" value="${item.name }"/></td> </tr> <tr> <td>商品价格</td> <td><input type="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 = new HashMap<String,String>(); itemTypes.put("101", "数码"); itemTypes.put("102", "母婴"); return itemTypes; }
页面:
商品类型: <select name="itemtype"> <c:forEach items="${itemtypes }" var="itemtype"> <option value="${itemtype.key }">${itemtype.value }</option> </c:forEach> </select>
2.3简单类型数据回显
最简单方法使用model。
//简单数据类型回显 model.addAttribute("id", id);
3.异常处理器
3.1异常处理思路
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、通过测试手段减少运行时异常的发生。
系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
3.2自定义异常类
对不同的异常类型定义异常类,继承Exception。
package joanna.yan.ssm.exception; /** * 系统自定义异常类,针对预期的异常。需要在程序中抛出此类异常。 * @author Joanna.Yan * */ public class CustomException extends Exception{ //异常信息 public String message; public CustomException(String message) { super(); this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
3.3全局异常处理器
思路:
系统遇到异常,在程序中手动抛出,dao抛给service、service抛给controller、controller抛给前端控制器,前端控制器调用全局异常处理器。
全局异常处理器处理思路:
解析出异常类型
如果该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展示
如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)
springmvc提供一个HandlerExceptionResolver接口。
package joanna.yan.ssm.exc
http://www.cnblogs.com/Joanna-Yan/p/7085268.html