java web中异常处理

本文用于记录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);

	@Override
	public 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.xsd
		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/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://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 {

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		return 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提供良好的支持 -->
	<bean
		class="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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值