springmvc的异常处理有局部异常和全局异常。
一、局部异常(只针对当前的Controller)
?实现步骤:创建自定义异常类:
package com.song.ssm.util;
public class MyException extends RuntimeException {
public MyException() {
}
public MyException(String message) {
super(message);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(Throwable cause) {
super(cause);
}
public MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
控制器中添加异常处理方法:
@ExceptionHandler(MyException.class)
public String execptionHandle(HttpServletRequest request,MyException myException){
request.setAttribute("mess",myException.getMessage());
return "error";
}
二、全局异常(针对整个项目)
1:xml实现方式:在springmvc的配置文件中添加如下代码:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.song.ssm.util.MyException">error</prop>
<prop key="java.lang.NullPointerException">error1</prop>
<prop key="java.lang.ArrayIndexOutOfBoundsException">error2</prop>
</props>
</property>
</bean>
2:annotation方式:创建全局异常处理类:
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(NullPointerException.class)
public String nullHandlerException(Model model){
model.addAttribute("mess","空指针异常!");
return "error1";
}
@ExceptionHandler(ArrayIndexOutOfBoundsException.class)
public String arrayHandlerException(Model model){
model.addAttribute("mess","下标越界异常!");
return "error2";
}
}
分别在error1和error2页面中显示对应的异常消息即可!
|