SpringMVC异常的使用


1.创建一个异常类,需要extend RuntimeException,继承父类中所有的方法


2.局部异常,仅能处理这个Controller中的异常


 在Controller中添加异常处理方法
 

  @ExceptionHandler(value={UserException.class})
 public String handlerExceString(UserException e,HttpServletRequest req){
  req.setAttribute("e", e);
  return "error";
 }


3.全局异常,在SpringMVC配置文件dispatcherServlet-servlet.xml里加入


 <!-- 全局异常SimpleMappingExceptionResolver -->
 <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  <property name="exceptionMappings">
   <props>   <!--error是指向的异常提示信息的页面-->
    <prop key="cn.bdqn.pojo.UserException">error</prop>
   </props>  <!--cn.bdqn.pojo.UserException异常类的完全限定名-->
  </property>
 </bean>


4.创建error.jsp


  使用EL表达式在页面中显示异常信息


 <body>
  <h1>
   <!-- ${e.message} --><!-- 局部异常 -->
   ${exception.message}<!-- 全局异常 -->
  </h1>
 </body>

原文地址:https://www.cnblogs.com/fifiyong/p/5820044.html