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}
成功
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章