版权声明:如需转载,请注明出处! https://blog.csdn.net/qq_41172416/article/details/83625666
对于异常处理我们分为局部异常处理,和全局异常处理,下面我们开始
一、局部异常处理
1、 局部异常使用@ExceptionHandler实现,@ExceptionHandler可以指定多个异常。
package com.bdqn.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class local {
@RequestMapping("local.html")
public String demo1(){
//throw new RuntimeException("用户名或密码输入不正确!");
throw new NullPointerException("我是空指针异常");
}
@ExceptionHandler(value={RuntimeException.class,NullPointerException.class})
public String exception(RuntimeException e,HttpServletRequest request){
request.setAttribute("e",e);
return "error_local";
}
}
注意: jsp页面使用${e.message}输出异常信息
2、页面展示效果
二、全局异常处理
1、在springmvc_servlet.xml中配置全局异常
<!-- 全局异常处理 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.RuntimeException">error</prop>
</props>
</property>
</bean>
2、在控制器中编写异常类
package com.bdqn.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class global {
@RequestMapping("global.html")
public String demo2(){
throw new RuntimeException("我是全局异常");
}
}
3、在jsp页面使用${exception.message }展示数据