springmvc 自定义异常处理机制

来源:互联网 发布:黑客帝国动画版 知乎 编辑:程序博客网 时间:2024/06/05 09:13

本篇文章,我们讲解如何在springmvc中自定义异常处理机制,本文只是讲解一些基础的配置和用法,偏实用型

首先,我们看一下错误页面结构:


接下来,我们讲解具体的配置流程

1、首先,我们需要定义异常类CustomSimpleMappingExceptionResolver,它继承SimpleMappingExceptionResolver,具体实现如下(注意:需要修改对应的package路径)

package com.common.exception.inter;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver{ @Override      protected ModelAndView doResolveException(HttpServletRequest request,              HttpServletResponse response, Object handler, Exception ex) {          // Expose ModelAndView for chosen error view.          String viewName = determineViewName(ex, request);          if (viewName != null) {// JSP格式返回              if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request                      .getHeader("X-Requested-With")!= null && request                      .getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {                  // 如果不是异步请求                  // Apply HTTP status code for error views, if specified.                  // Only apply it if we're processing a top-level request.                  Integer statusCode = determineStatusCode(request, viewName);                  if (statusCode != null) {                      applyStatusCodeIfPossible(request, response, statusCode);                  }                  return getModelAndView(viewName, ex, request);              } else {// JSON格式返回                  try {                      PrintWriter writer = response.getWriter();                      writer.write(ex.getMessage());                      /*writer.flush();*/                  } catch (IOException e) {                      e.printStackTrace();                  }                  return null;              }          } else {              return null;          }      }  }

2、定义BusinessException类,它继承了Exception,具体实现如下,同样需要根据你自己的路径修改对应包名

package com.common.exception;public class BusinessException extends Exception{private static final long serialVersionUID = 1L;        public BusinessException() {          // TODO Auto-generated constructor stub      }        public BusinessException(String message) {          super(message);          // TODO Auto-generated constructor stub      }      public BusinessException(Throwable cause) {          super(cause);          // TODO Auto-generated constructor stub      }      public BusinessException(String message, Throwable cause) {          super(message, cause);          // TODO Auto-generated constructor stub      }  }

3、添加错误页面errorpage.jsp(在本文中我只给出这一个错误页面示例,大家如果要定义其他错误页面示例可根据前面的结构图自己实现)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isErrorPage="true"%>  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  <%String path= request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/1999/xhtml">  <head>      <title>error page</title>      <script type="text/javascript">          $(function(){              $("#center-div").center(true);          })      </script>  </head>  <body style="margin: 0;padding: 0;background-color: #f5f5f5;">      <div id="center-div">          <table style="height: 100%; width: 600px; text-align: center;">              <tr>                  <td>                      <%= exception.getMessage()%>                      <p style="line-height: 12px; color: #666666; font-family: Tahoma, '宋体'; font-size: 12px; text-align: left;">                      <a href="javascript:history.go(-1);">返回</a>!!!                      </p>                  </td>              </tr>          </table>      </div>  </body>  </html>

4、在applicationContext.xml配置文件中添加以下配置,注意修改对应的类路径和错误页面路径,如果有多个错误页面,添加prop标签即可

<bean id="exceptionResolver" class="com.common.exception.inter.CustomSimpleMappingExceptionResolver">        <property name="exceptionMappings">           <props>             <prop key="com.common.exception.BusinessException">error/errorpage</prop>         </props>        </property>       </bean>


5、到此,我们已经基本完成了springmvc的自定义异常的配置,但是此类异常机制也存在一定缺陷,那就是只能在controller层返回错误页面,因此在service层和dao层的发生的异常,我们只能依次throw给上层处理,下面给出controller层处理异常的用法示例

@RequestMapping(value="logout",method = RequestMethod.GET)public String logout(HttpServletRequest request,HttpServletResponse response) throws BusinessException{try {request.getSession().invalidate();} catch (Exception e) {throw new BusinessException("请求异常");}return "index";}

6、以上配置完成就已经实现了自定义异常,最后我们在web.xml配置文件添加以下配置,自定义一些常见错误页面,注意基础异常返回的错误页面直接根据web.xml中映射关系返回,不经过applicationContext.xml中的映射关系。

<!-- 自定义错误页面 -->  <error-page>         <error-code>400</error-code>         <location>/WEB-INF/page/error/400.jsp</location>     </error-page><error-page>         <error-code>403</error-code>         <location>/WEB-INF/page/error/403.jsp</location>     </error-page>    <error-page>         <error-code>404</error-code>         <location>/WEB-INF/page/error/404.jsp</location>     </error-page>  <error-page>         <error-code>405</error-code>         <location>/WEB-INF/page/error/405.jsp</location>     </error-page>     <error-page>         <error-code>500</error-code>         <location>/WEB-INF/page/error/500.jsp</location>     </error-page>    <error-page>         <exception-type>java.lang.Exception</exception-type>         <location>/WEB-INF/page/error/errorpage.jsp</location>     </error-page>     <error-page>         <exception-type>java.lang.NullPointerException</exception-type>         <location>/WEB-INF/page/error/errorpage.jsp</location>     </error-page>     <error-page>         <exception-type>javax.servlet.ServletException</exception-type>         <location>/WEB-INF/page/error/errorpage.jsp</location>     </error-page> 



0 0
原创粉丝点击