spring mvc异常

在spring mvc 3中,处理异常的是试用exceptionresolver去做异常,先来个简单DEMO看下:

1) 自定义异常类

 
Java代码 复制代码 收藏代码
  1. public class SpringException extends RuntimeException{ 
  2.       
  3.     private String exceptionMsg; 
  4.   
  5.     public SpringException(String exceptionMsg) { 
  6.         this.exceptionMsg = exceptionMsg; 
  7.     } 
  8.      
  9.     public String getExceptionMsg(){ 
  10.         return this.exceptionMsg; 
  11.     } 
  12.      
  13.     public void setExceptionMsg(String exceptionMsg) { 
  14.         this.exceptionMsg = exceptionMsg; 
  15.     } 
public class SpringException extends RuntimeException{
	 
	private String exceptionMsg;
 
	public SpringException(String exceptionMsg) {
		this.exceptionMsg = exceptionMsg;
	}
	
	public String getExceptionMsg(){
		return this.exceptionMsg;
	}
	
	public void setExceptionMsg(String exceptionMsg) {
		this.exceptionMsg = exceptionMsg;
	}
}


2) 一个简单的控制器,其中用到了注解
  
Java代码 复制代码 收藏代码
  1. @Controller 
  2. public class StudentController { 
  3.  
  4.    @RequestMapping(value = "/student", method = RequestMethod.GET) 
  5.    public ModelAndView student() { 
  6.       return new ModelAndView("student", "command", new Student()); 
  7.    } 
  8.  
  9.    @RequestMapping(value = "/addStudent", method = RequestMethod.POST) 
  10.    @ExceptionHandler({SpringException.class}) 
  11.    public String addStudent( @ModelAttribute("HelloWeb")Student student,  
  12.       ModelMap model) { 
  13.  
  14.       if(student.getName().length() < 5 ){ 
  15.          throw new SpringException("Given name is too short"); 
  16.       }else
  17.        model.addAttribute("name", student.getName()); 
  18.       } 
  19.        
  20.    } 
@Controller
public class StudentController {

   @RequestMapping(value = "/student", method = RequestMethod.GET)
   public ModelAndView student() {
      return new ModelAndView("student", "command", new Student());
   }

   @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   @ExceptionHandler({SpringException.class})
   public String addStudent( @ModelAttribute("HelloWeb")Student student, 
      ModelMap model) {

      if(student.getName().length() < 5 ){
         throw new SpringException("Given name is too short");
      }else{
       model.addAttribute("name", student.getName());
      }
      
   }
}


3 在传统的xxxx-servlet.xml中配置SimpleMappingExceptionResolver

  
Java代码 复制代码 收藏代码
  1. <bean class="org.springframework.web.servlet.handler. 
  2.     SimpleMappingExceptionResolver"> 
  3. <property name="exceptionMappings"
  4.     <props> 
  5.        <prop key="com.tutorialspoint.SpringException"
  6.           ExceptionPage 
  7.        </prop> 
  8.     </props> 
  9. </property> 
  10. <property name="defaultErrorView" value="error"/> 
  <bean class="org.springframework.web.servlet.handler.
      SimpleMappingExceptionResolver">
   <property name="exceptionMappings">
      <props>
         <prop key="com.tutorialspoint.SpringException">
            ExceptionPage
         </prop>
      </props>
   </property>
   <property name="defaultErrorView" value="error"/>


  其中      ExceptionPage.jsp得定义出来,如下页面:

  
Java代码 复制代码 收藏代码
  1. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 
  2. <html> 
  3. <head> 
  4.     <title>Spring MVC Exception Handling</title> 
  5. </head> 
  6. <body> 
  7.  
  8. <h2>Spring MVC Exception Handling</h2> 
  9.  
  10. <h3>${exception.exceptionMsg}</h3> 
  11.  
  12. </body> 
  13. </html> 
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Exception Handling</title>
</head>
<body>

<h2>Spring MVC Exception Handling</h2>

<h3>${exception.exceptionMsg}</h3>

</body>
</html>


   这样当有异常的话,就出现ExceptionPage.jsp的页面了;
注意一下,使用:
@ExceptionHandler(IOException.class)

  public ModelAndView handleIOException(IOException ex) {
则凡是IOException的子类异常的话,也会用handleIOException方法去处理的喔';

   可以看到,其实在spring mvc3中,如果使用

Java代码 复制代码 收藏代码
  1. @ExceptionHandler(IOException.class
  2.  
  3. public ModelAndView handleIOException(IOException ex) { 
 @ExceptionHandler(IOException.class)

  public ModelAndView handleIOException(IOException ex) {


   这个方法,其弊端在于,一个controller只能搭配响应一类异常,也就是说,
只能处理同一个controller中出现的ioexception;在最新的spring mvc 3.2中,比如DEMO如下:


Java代码 复制代码 收藏代码
  1. @Controller 
  2. public class UserCreditCardController { 
  3.  
  4.   private static final Logger logger = LoggerFactory.getLogger(UserCreditCardController.class); 
  5.  
  6.  
  7.   @RequestMapping(value = "userdetails", method = RequestMethod.GET) 
  8.   public String getCardDetails(Model model) throws IOException { 
  9.  
  10.     logger.info("This will throw an IOException"); 
  11.  
  12.     boolean throwException = true
  13.  
  14.     if (throwException) { 
  15.       throw new IOException("This is my IOException"); 
  16.     } 
  17.  
  18.     return "home"
  19.   } 
  20.  
@Controller
public class UserCreditCardController {

  private static final Logger logger = LoggerFactory.getLogger(UserCreditCardController.class);


  @RequestMapping(value = "userdetails", method = RequestMethod.GET)
  public String getCardDetails(Model model) throws IOException {

    logger.info("This will throw an IOException");

    boolean throwException = true;

    if (throwException) {
      throw new IOException("This is my IOException");
    }

    return "home";
  }

}


  还有一个controller:
Java代码 复制代码 收藏代码
  1. @Controller 
  2. public class UserAddressController { 
  3.  
  4.   private static final Logger logger = LoggerFactory.getLogger(UserAddressController.class); 
  5.  
  6.  
  7.   @RequestMapping(value = "useraddress", method = RequestMethod.GET) 
  8.   public String getUserAddress(Model model) throws IOException { 
  9.  
  10.     logger.info("This will throw an IOException"); 
  11.  
  12.     boolean throwException = true
  13.  
  14.     if (throwException) { 
  15.       throw new IOException("This is my IOException"); 
  16.     } 
  17.  
  18.     return "home"
  19.   } 
  20.  
@Controller
public class UserAddressController {

  private static final Logger logger = LoggerFactory.getLogger(UserAddressController.class);


  @RequestMapping(value = "useraddress", method = RequestMethod.GET)
  public String getUserAddress(Model model) throws IOException {

    logger.info("This will throw an IOException");

    boolean throwException = true;

    if (throwException) {
      throw new IOException("This is my IOException");
    }

    return "home";
  }

}


   两个controller都抛出了IOException的异常,则统一处理的为:

Java代码 复制代码 收藏代码
  1. @ControllerAdvice 
  2. public class MyControllerAdviceDemo { 
  3.  
  4.   private static final Logger logger = LoggerFactory.getLogger(MyControllerAdviceDemo.class); 
  5.  
  6.   @Autowired 
  7.   private UserDao userDao; 
  8.  
  9.   @ExceptionHandler(IOException.class
  10.   public ModelAndView handleIOException(IOException ex) { 
  11.  
  12.     logger.info("handleIOException - Catching: " + ex.getClass().getSimpleName()); 
  13.     return errorModelAndView(ex); 
  14.   } 
  15.  
  16.    
  17.   private ModelAndView errorModelAndView(Exception ex) { 
  18.     ModelAndView modelAndView = new ModelAndView(); 
  19.     modelAndView.setViewName("error"); 
  20.     modelAndView.addObject("name", ex.getClass().getSimpleName()); 
  21.     modelAndView.addObject("user", userDao.readUserName()); 
  22.  
  23.     return modelAndView; 
  24.   } 
@ControllerAdvice
public class MyControllerAdviceDemo {

  private static final Logger logger = LoggerFactory.getLogger(MyControllerAdviceDemo.class);

  @Autowired
  private UserDao userDao;

  @ExceptionHandler(IOException.class)
  public ModelAndView handleIOException(IOException ex) {

    logger.info("handleIOException - Catching: " + ex.getClass().getSimpleName());
    return errorModelAndView(ex);
  }

  
  private ModelAndView errorModelAndView(Exception ex) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("error");
    modelAndView.addObject("name", ex.getClass().getSimpleName());
    modelAndView.addObject("user", userDao.readUserName());

    return modelAndView;
  }
}

   这样一来,使用了@ControllerAdvice标签,则无论应用中有多少个controller,只要
其中一个抛出IOException,都会使用 MyControllerAdviceDemo 去处理了;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值