java web中异常处理

来源:互联网 发布:淘宝情趣内衣图片无码 编辑:程序博客网 时间:2024/05/16 09:50

本文用于记录java web开发中使用的异常处理方式。


1、使用spring的异常处理注解

   该方式请搜索spring中  @ExceptionHandler  注解的使用和介绍。


2、使用HandlerExceptionResolver方式

实现并使用Spring提供的HandlerExceptionResolver接口处理异常。该接口中有一个接口,说明如下:

    /**      * Interface to be implemented by objects than can resolve exceptions thrown      * during handler mapping or execution, in the typical case to error views.      * Implementors are typically registered as beans in the application context.      *      * <p>Error views are analogous to the error page JSPs, but can be used with      * any kind of exception including any checked exception, with potentially      * fine-granular mappings for specific handlers.      *      * @author Juergen Hoeller      * @since 22.11.2003      */      public interface HandlerExceptionResolver {                /**          * Try to resolve the given exception that got thrown during on handler execution,          * returning a ModelAndView that represents a specific error page if appropriate.          * <p>The returned ModelAndView may be {@linkplain ModelAndView#isEmpty() empty}          * to indicate that the exception has been resolved successfully but that no view          * should be rendered, for instance by setting a status code.          * @param request current HTTP request          * @param response current HTTP response          * @param handler the executed handler, or <code>null</code> if none chosen at the          * time of the exception (for example, if multipart resolution failed)          * @param ex the exception that got thrown during handler execution          * @return a corresponding ModelAndView to forward to,          * or <code>null</code> for default processing          */          ModelAndView resolveException(                  HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);            }  

需要使用该方式处理异常时只需要实现该接口,并在配置文件中配置相关的bean即可。

eg:java实现demo

package com.landsem.update.base.exception.handler;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.springframework.dao.DataIntegrityViolationException;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView;import com.landsem.update.base.exception.ActionUnSupportException;public class ExceptionDispatcher implements HandlerExceptionResolver {protected static Logger logger = Logger.getLogger(ExceptionDispatcher.class);@Overridepublic ModelAndView resolveException(HttpServletRequest arg0,HttpServletResponse arg1, Object arg2, Exception arg3) {//action unSupport exception.自定义的异常if (arg3 instanceof ActionUnSupportException) {logger.error("ActionUnSupportException exception.");arg3.printStackTrace();}//DataIntegrityViolationException exception.数据库抛出的异常else if (arg3 instanceof DataIntegrityViolationException) {logger.error("DataIntegrityViolationException");arg3.printStackTrace();}//base exception.根异常else if (arg3 instanceof Exception) {logger.error("unknown exception.");arg3.printStackTrace();}return null;}}
在applicationContext.xml中进行配置,如:

<?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:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"xmlns:jee="http://www.springframework.org/schema/jee"xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  <!-- 异常处理器 -->   <!-- =================================异常处理 ====================================== -->    <bean id="exceptionHandler" class="com.landsem.update.base.exception.handler.ExceptionDispatcher"/></beans>


3、使用HandlerInterceptorAdapter进行拦截并处理抛出的异常

Spring为我们提供了org.springframework.web.servlet.handler.HandlerInterceptorAdapter这个适配器,继承此类并做相关简单配置,可以非常方便的实现自己的拦截器。他的三个方法如下,具体说明请见spring官方文档:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)            throws Exception {            return true;        }        public void postHandle(                HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)                throws Exception {        }        public void afterCompletion(                HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)                throws Exception {        }  

eg:如下用他拦截http请求并做一个日志记录,相关功能代码并未进行实现,读者可以根据实际情况完善添加

package com.landsem.update.base.aop;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;public class LoggerInterception extends HandlerInterceptorAdapter {@Overridepublic void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {// TODO Auto-generated method stubsuper.afterCompletion(request, response, handler, ex);}@Overridepublic void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {// TODO Auto-generated method stubsuper.postHandle(request, response, handler, modelAndView);}@Overridepublic boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {// TODO Auto-generated method stubreturn super.preHandle(request, response, handler);}}
在spring-servlet.xml中进行相关的配置,主要在DefaultAnnotationHandlerMapping中对其进行配置:

<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans                     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                     http://www.springframework.org/schema/context                        http://www.springframework.org/schema/context/spring-context-4.0.xsd                        http://www.springframework.org/schema/aop                         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd                                                "><!-- 自动扫描注解的Controller --><context:component-scan base-package="com.landsem.update.base.controller.impl" /><context:component-scan base-package="com.landsem.update.base.business" /><!-- <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />  --><!-- =================================日志记录====================================== --><!-- 处理方法级别上的@RequestMapping注解 ,完成请求和注解POJO的映射-->  <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>  <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">       <property name="interceptors">          <list>              <bean class="com.landsem.update.base.aop.LoggerInterception"/>  <!-- 用于日志存储 -->        </list>      </property> </bean> <!-- 视图解析器策略 和 视图解析器 --><!-- 对JSTL提供良好的支持 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- 默认的viewClass,可以不用配置 <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView" /> --><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean></beans>
注意:网上有帖子说该方法不能和@ExceptionHandler(即方法一)同时使用,笔者暂时未做验证。


0 0
原创粉丝点击