Spring MVC異常處理 和 重新導向傳遞資料,mvc異常處理
1.異常處理介紹
Spring在web項目中,如果在請求處理時出現異常,那輸出會是Servlet響應。這時異常需要以某種方式轉換為響應。
Spring將異常轉換為響應的方式:
a.特定的Spring異常將自動對應為指定的HTTP狀態代碼;
b.異常上添加@ResponseStatus註解,從而將其映射為某一個HTTP狀態代碼;
c.方法上添加@ExceptionHandler註解,使其處理異常。
2.異常處理代碼
1 @RequestMapping("getPathVariable/{id}")2 public String getPathVariable(3 @PathVariable("id") String id){4 if("error".equals(id)){5 throw new SpittleException();6 }7 return "index";8 }
1 package com.taozhiye.controller; 2 3 import org.springframework.http.HttpStatus; 4 import org.springframework.web.bind.annotation.ResponseStatus; 5 6 @ResponseStatus( 7 // 404 8 value = HttpStatus.NOT_FOUND, 9 reason = "Spittle not found"10 )11 public class SpittleException extends RuntimeException {12 13 }
正常情況下,當id為error時,會報錯,這時是500錯誤,我們可以通過@ResponseStatus註解,映射到404狀態代碼上,進行簡單的異常處理。
第二種方法是報相應的異常,直接跳轉到錯誤頁面。
1 package com.taozhiye.controller; 2 3 import org.springframework.web.bind.annotation.ControllerAdvice; 4 import org.springframework.web.bind.annotation.ExceptionHandler; 5 6 7 8 @ControllerAdvice 9 public class AppExcepitonHandler {10 11 @ExceptionHandler(Exception.class)12 public String deal(){13 System.out.println("出現異常");14 return "index";15 }16 }
3.重新導向傳值
1 @RequestMapping("getPathVariable/{id}") 2 public String getPathVariable( 3 @PathVariable("id") String id, 4 Model model, 5 RedirectAttributes model2){ 6 if("error".equals(id)){ 7 throw new SpittleException(); 8 }else if("findAll".equals(id)){ 9 /**10 * 重新導向傳參數:11 * 相當於把參數寫到session中,12 * 如果重新導向到controller的時候,用@ModelAttribute接收13 * 如果重新導向到頁面,可以直接接收14 */15 model2.addFlashAttribute("flash", "flash");16 /**17 * 通過url模板進行重新導向18 */19 return "redirect:/{id}";20 }else if("index".equals(id)){21 // model.addAttribute("id", id);22 /**23 * 轉寄不可以使用模板24 */25 // return "/{id}";26 model2.addFlashAttribute("flash", "flash");27 /**28 * 通過url模板進行重新導向29 */30 return "index";31 }else{32 return "ajax1";33 }34 }
@RequestMapping("/findAll") @ResponseBody public List<User> findAll(@ModelAttribute("flash") String flash){ System.out.println("flash:"+flash); return userService.findUserAll(); }@RequestMapping("/index") @ResponseBody public List<User> index(Map<String, Object> map,@ModelAttribute("flash")String flash){ System.out.println("flash:"+flash); return userService.findUserAll(); }
重新導向傳參數: 相當於把參數寫到session中, 如果重新導向到controller的時候,用@ModelAttribute接收 如果重新導向到頁面,可以直接接收