SpringMVC和Mybatis(四)异常处理、上传图片、json的数据交互

异常处理
1.预期异常2.运行时异常
预期异常进行捕获,dao抛到service抛到controller抛到dispatch,springmvc提供全局异常处理器,一个系统只有一个统一异常处理。
自定义异常:
创建exception的包创建CustomException
public class CustomException extends Exception{


public String message;
public CustomException(String message){
super(message);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}

}




全局异常处理器:
解析出异常类型,如果是自定义的异常,直接取出异常信息,在错误界面显示;如果不是系统异常,一般为运行异常,需要构造一个自定义的异常类型(信息为“未知错误”)。
springmvc提供了一个HandlerExceptionResolver接口
在exception包内创建CustomExceptionResolver
public class CustomExceptionResolver implements HandlerExceptionResolver {


@Override
public ModelAndView resolveException(HttpServletRequest arg0, 
HttpServletResponse arg1, Object arg2,
Exception arg3) {
//Object 就是handler就是处理器适配器要执行handler的对象,(只有method)
//解析出异常的类型
//如果是自定义异常就取出
// String message = null;
// if (arg3 instanceof CustomException) {
// message = ((CustomException)arg3).getMessage();
// } else {
// //如果不是构造一个未知错误
// message = "未知错误";
// }


CustomException customException = null;
if (arg3 instanceof CustomException) {
customException = (CustomException)arg3;
} else {
customException = new CustomException("未知错误");
}
String message = customException.getMessage();

ModelAndView modelAndView = new ModelAndView();

modelAndView.addObject("message", message);
modelAndView.setViewName("error");

return modelAndView;
}


}




错误页面
同success.jsp一样创建在jsp包内error.jsp
</head>
  
  <body>
    ${message }
  </body>
</html>
在springmvc.xml配置
只能有一个类起异常的作用
<!-- 全局异常处理器 -->
<bean class="cn.itcast.ssm.exception.CustomExceptionResolver"></bean>
</beans>


测试手动抛出异常
在controller内抛出异常
@RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
public String editItems(Model model,@RequestParam


(value="id",required=true,defaultValue="")Integer items_id)throws Exception{
//传入的id要和前段页面的参数id名一致,才能参数绑定
//调用service根据商品id查询商品信息
ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
//判断商品是否为空,根据id没有查询到商品,抛出异常,提示用户商品不存在
if (itemsCustom == null) {
throw new CustomException("商品信息不存在");
}


同时还需要修改ItemsServiceImpl.java
@Override
public ItemsCustom findItemsById(Integer id) throws Exception {
Items items = itemsMapper.selectByPrimaryKey(id);
//中间对商品信息进行业务处理
//...
//最后返回ItemsCustom
ItemsCustom itemsCustom = null;
//异常抛出判断是否为空
if (items!=null) {
itemsCustom = new ItemsCustom();
//将items的内容拷贝到itemsCustom
BeanUtils.copyProperties(items, itemsCustom);





return itemsCustom;
}


因为有throws 的抛出异常,可以在service抛出异常。
如果与操作业务有关的异常,建议在service中抛出异常。
与业务功能没有关系的异常(随便输入字符),建议在controller中抛出异常。
==========================================================================
上传图片
springmvc对于多部件的解析
分析:在页面form中提交enctype="multipart/form-data"的数据时,需要对multipart类型解析。
加入jar包:commons-fileupload-1.2.2.jar commons-io-2.4.jar 解析器就是使用这个jar包
在springmvc.xml中配置multipart类型解析器。


<!-- 文件上传 -->
<bean id="multipartResolver" 


class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的大小 -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
</beans>


editItems.jsp
</head>
  <body>
  <!-- 显示错误信息 -->
  <c:if test="${allErrors!=null }">
  <c:forEach items="${allErrors }" var="error">
  ${error.defaultMessage }<br />
  </c:forEach>
  </c:if>
  <form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" 


method="post" enctype="multipart/form-data">
。。。。。。
<td>商品图片</td>
  <td>
  <c:if test="${itemsCustom.pic !=null }">
  <img src="/pic/${itemsCustom.pic }" width=100 height=100 />
  <br />
  </c:if>
  <input type="file" name="items_pic" />
  </td>






正式项目会建立图片服务器。在Tomcat内创建一个虚拟目录,存储图片。
修改Tomcat配置文件
C:\Program Files\tomcat-7\conf\server.xml
<Context docBase="E:\myPorject\meEclipseJava\temp" path="/pic" reloadable="false" />


      </Host>
    </Engine>
  </Service>
</Server>


E:\myPorject\meEclipseJava\temp是实际目录,/pic是虚拟目录
重启Tomcat,使用http://localhost:8081/pic/8956ceef108e049cec136c4221b51737.jpg测试是否可以打开


图片
一定要将图片目录分级创建(提高i/o新能),一般按照时间顺序创建。
商品修改controller方法:
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,Integer id,
@Validated(value={ValidGroup1.class}) ItemsCustom itemsCustom,
BindingResult bindingResult,MultipartFile items_pic//接收商品的图片
)throws Exception{


//获取校验信息
if (bindingResult.hasErrors()) {
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError objectError : allErrors) {
System.out.println(objectError.getDefaultMessage());
}
model.addAttribute("allErrors", allErrors);
model.addAttribute("itemsCustom", itemsCustom);
return "items/editItems";
}
//上传图片
//图片的原始名称
String originalFilename = items_pic.getOriginalFilename();
//数组会越界所以要加&&
if (items_pic != null && originalFilename!=null && originalFilename.length()>0) 


{
String pic_path = "E:\\myPorject\\meEclipseJava\\temp\\";

//生成新的名称
String newfilename = UUID.randomUUID() + originalFilename.substring


(originalFilename.lastIndexOf("."));

File newFile = new File(pic_path+newfilename);
//写入磁盘
items_pic.transferTo(newFile);
//写入itemsCustom中
itemsCustom.setPic(newfilename);
}


itemsService.updateItems(id, itemsCustom);


return "items/editItems";
// return "forward:queryItems.action";
}
==========================================================================================
json的数据交互
json数据格式在接口调用中,因为格式简单,在html中常用
比如:webservice接口,传输json数据和xml数据
当客户端请求key/value串分两种
第一种请求的是json串
contentType=application/json
@RequestBody将json串转成java对象
@ResponseBody将java对象转成json串输出
第二种请求的是key/value串
contentType=application/x-www-form-urlencoded
不需要转java对象
@ResponseBody将java对象转成json串输出
最后都输出json数据到html


环境准备
jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar
@RequestBody和@ResponseBody是使用上面的包


在注解适配器中加入messageConverters
<!-- 注解适配器 -->
<bean 


class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" 


></bean>
<list>
</property>
</bean>
如果使用<mvc:annotation-driven /> 则不需要用上面的内容


json交互测试
1.输入json
jsp页面


<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-


1.4.4.min.js"></script>
<script type="text/javascript">
//请求json
function requestJson(){

$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/requestJson.action',
contentType:'application/json;charset=utf-8',
data:'{"name":"手机","price":"999"}',
success:function(data){//return json result
alert(data);
}
});
}
//请求key/value
function responseJson(){}

</script>
  </head>
  
  <body>
  <input type="button" οnclick="requestJson()" value="请求json" />
  <input type="button" οnclick="responseJson()" value="请求key/value" />
  </body>
</html>


controller


@Controller
public class JsonTest {


//请求json(商品信息),输出相应json(商品信息)
//@RequestBody 已经把json串转成商品信息java对象
//@ResponseBody 将itemsCustom转成json串
@RequestMapping("/requestJson")
public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){

return itemsCustom;
}
}


通过点击后,使用浏览器的F12键查看Request URL、Request Headers和Response Header的ContextType、


Request Payload、Response为
{"id":null,"name":"手机","price":999.0,"pic":null,"createtime":null,"detail":null}
成功
2.输入key/value
jsp页面
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-


1.4.4.min.js"></script>
<script type="text/javascript">
//请求json
function requestJson(){

$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/requestJson.action',
contentType:'application/json;charset=utf-8',
data:'{"name":"手机","price":"999"}',
success:function(data){//return json result
alert(data);
}
});
}
//请求key/value
function responseJson(){
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/responseJson.action',
//因为提交为默认类型所以不需要,默认是key/value
//contentType:'application/json;charset=utf-8',
data:'name=手机&price=999',
success:function(data){//return json result
alert(data);
}
});
}

</script>
  </head>
  
  <body>
  <input type="button" οnclick="requestJson()" value="请求json" />
  <input type="button" οnclick="responseJson()" value="请求key/value" />
  </body>
</html>


controller
@RequestMapping("/responseJson")
public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){

return itemsCustom;
}


通过点击后,使用浏览器的F12键查看Request URL、Request Headers和Response Header的ContextType、


Request Payload、Response为
{"id":null,"name":"手机","price":999.0,"pic":null,"createtime":null,"detail":null}
成功
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值