使用场景:当浏览器向浏览器发送请求,而服务器处理请求出现了异常的情况,如果直接把错误信息给浏览器展示出来是很不好的,因为用户就能看到具体的代码错误信息。所以当出现异常情况时,服务器可以给用户一个本次请求异常的页面,让用户知道当前服务器有点问题,请稍后再试。

实现流程

  • 1)自定义异常类
public class MyException  extends RuntimeException{
     private String message;
     public MyException(){}
     public MyException(String message){
        this.message = message;
     }
     public void setMessage(String message) {
        this.message = message;
     }
     @Override
     public String getMessage() {
        return message;
     }
}
  • 2)自定义异常处理类,处理我们抛出的异常

    • 对于异常的处理,我是把它转发到一个error页面,这里大家可以自己创建一个
@Component
public class ExceptionResolver implements HandlerExceptionResolver {
     @Override
     public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof MyException){
                    ModelAndView mv = new ModelAndView();
         mv.addObject("errorMessage", e.getMessage());
         mv.setViewName("error.jsp");
         return mv;
        }
        return null;
     }
}
  • Controller类:这里是捕获了一个空指针异常,然后抛出了我们自定义的异常
@Controller
public class UserController {
     @RequestMapping("testException.do")
     public String testException(){
     try {
            String str = null;
            str.length();
     }catch (NullPointerException e){
            e.printStackTrace();
            throw new MyException("服务器繁忙,请稍后再试!!!");
     }
            return "testException.jsp";
     }
}
  • ApplicationContext.xml(Spring核心配置文件)配置信息如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启spring注解驱动-->
 <context:component-scan base-package="com.cjh"/>
<!-- 开启mvc注解驱动-->
 <mvc:annotation-driven></mvc:annotation-driven>

</beans>

cing_self
18 声望3 粉丝