应用场景:当浏览器向浏览器发送申请,而服务器解决申请呈现了异样的状况,如果间接把错误信息给浏览器展现进去是很不好的,因为用户就能看到具体的代码错误信息。所以当出现异常状况时,服务器能够给用户一个本次申请异样的页面,让用户晓得以后服务器有点问题,请稍后再试。
实现流程
- 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页面,这里大家能够本人创立一个
@Componentpublic 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类:这里是捕捉了一个空指针异样,而后抛出了咱们自定义的异样
@Controllerpublic 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>