异常处理的方式一:注解方式
如果只为某个控制器中的方法抛出的异常进行处理,可以在该控制器中定义一个方法,使用@ExceptionHandler()注解修饰它,该注解的括号内表明要处理的异常类型。这样的话当该控制器抛出异常时就会被相应的添加了@ExceptionHandler()注解的类被捕获并处理,例如,将上篇博客中的HelloController处理器进行如下修改:
package cn.jingpengchong.hello.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("hello")
public String hello(int i) {
i = 1/i;
return "toView";
}
@ExceptionHandler(ArithmeticException.class)
public String exception(Exception exception, Model model) {
mdel.addAttribute("msg", exception.getMessage());
return "error";
}
}
配置文件中添加<mvc:annotation-driven>标签。
当请求中的参数i为0的时候,就会抛出异常,而该控制器中的@ExceptionHandler注解会将该异常捕获到,并执行exception()方法:
注意:一个Controller类有多个@ExceptionHandler 注解修饰的方法则使用当前异常继承最近的@ExceptionHandler注解修饰方法处理异常。
如果要处理多个控制器抛出的异常,那么可以新建一个类,将该类用注解@ControllerAdvice修饰,将异常的处理方法写在该类中,例如:
package cn.jingpengchong.hello.exception;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class AllException {
@ExceptionHandler(ArithmeticException.class)
public String exception(Exception exception, Model model) {
model.addAttribute("msg", exception.getMessage());
return "error";
}
}
这样也是好使的:
注意:当控制器中抛出一个异常后,会先在当前控制器找有没有处理此异常的@ExceptionHandler注解修饰的方法,如果没有的话才去@ControllerAdvice标记所修饰的类中查找@ExceptionHandler标记的方法。
异常处理的方式二:配置方式
在spring的xml配置文件中配置视图解析器SimpleMappingExceptionResolver,该视图解析器用于服务器端当发生异常时根据发生的异常类型跳转到指定的视图以显示异常信息,例:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--将异常信息添加进页面属性 -->
<property name="exceptionAttribute" value="msg"/>
<!-- 异常类型匹配 -->
<property name="exceptionMappings">
<props>
<!-- 捕获到的异常具体跳转到哪个页面 -->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
</bean>
这样也是好使的: