一種方法是使用HandlerExceptionResolver
界面。
HandlerExceptionResolver接口的替代方法是@ExceptionHandler
註釋。在控制器中使用@ExceptionHandler
方法註釋來指定在執行控制器方法期間拋出特定類型的異常時調用哪個方法。例如:
package com.spring3;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@ExceptionHandler(Exception.class)
public ModelAndView handleMyException(Exception exception) {
ModelAndView mv = new ModelAndView("redirect:errorMessage.html?error=" + exception.getMessage());
return mv;
}
@RequestMapping(value = "/errorMessage", method = RequestMethod.GET)
public ModelAndView handleMyExceptionOnRedirect(@RequestParam("error") String error) {
ModelAndView mv = new ModelAndView("uncaughtExceptionSpring");
v.addObject("error", error);
return mv;
}
@RequestMapping("/hello")
public ModelAndView helloWorld() throws Exception {
String message = "Hello World, Spring 3.0!";
return new ModelAndView("hello", "message", message);
}
}
Spring MVC的異常處理和顯示自定義視圖Part1,2,3,4
發生的這種情況的解決方案。但真的沒有標準的解決方案春天? – user1573576 2012-08-03 08:50:37