26.SpringMVC中的异常处理

在SpringMVC中可以把异常统一进行处理,只需加入以下配置:

<!-- Spring提供的默认的异常解析器,也可以自定义 -->
<!-- 可以在jsp目录下新建一个error目录,然后放入显示错误页面 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 
    <!-- 定义默认的异常处理页面,当该异常类型的注册时使用 -->  
	<!-- value="error" 表示跳转的逻辑视图名字 --> 
    <property name="defaultErrorView" value="error/error"></property>  

    <!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->  
    <property name="exceptionAttribute" value="ex"></property>  

    <!-- 定义需要特殊处理的异常,用简单类名或全限定名作为key,异常页名的逻辑视图名作为value -->  
    <property name="exceptionMappings">  
        <props>  
            <prop key="IOException">error/error_io</prop>  
            <prop key="java.sql.SQLException">error/error_sql</prop>  
        </props>  
    </property>
</bean>

ExceptionController.java

@RequestMapping("/exception")
@Controller
public class ExceptionController {
	@RequestMapping("/test1")
	public String test1() throws Exception{//直接抛出异常
		System.out.println("ExceptionController test1()...");
		int a=1/0;   //算数运算异常    就会走error/error.jsp
		System.out.println("a="+a);  //这些就不会执行
		return "test";
	}
	@RequestMapping("/test2")
	public String test2() throws Exception{
		System.out.println("ExceptionController test2()...");
		int a=1;
		if(a==1) {
			throw new IOException("IO异常测试");  //指明是IOException,就走error/error_io.jsp
		}
		return "test";
	}
	@RequestMapping("/test3")
	public String test3() throws Exception{
		System.out.println("ExceptionController test3()...");
		int a=1;
		if(a==1) {
			throw new SQLException("SQL异常测试");//指明是SQLException,就走error/error_sql.jsp
		}
		return "test";
	}
	//用@ExceptionHandler注解的形式进行处理异常(不推荐用),@ExceptionHandler可以有多个
	/*@ExceptionHandler(value={IOException.class}) //发现是IOException
	public String exp(Exception ex,HttpServletRequest request) {  
		request.setAttribute("ex", ex);  
		return "error/error_io";  		//就跳转到error/error_io.jsp
	} 
	@ExceptionHandler(value={SQLException.class}) //发现是SQLException
	public String exp1(Exception ex,HttpServletRequest request) {  
		request.setAttribute("ex", ex);  
		return "error/error_sql";  		//就跳转到error/error_sql.jsp
	}
	@ExceptionHandler(value={IOException.class,SQLException.class}) 
	public String exp(Exception ex,HttpServletRequest request) {  
		request.setAttribute("ex", ex);  
		return "error/error_io";   //都走error/error_io
	}  */
}

在这里插入图片描述

页面中:
1.如果使用jsp的脚本显示信息
<!-- 因为spring中修改了异常的默认名字,所以这里是ex -->
	<% Exception ex = (Exception)request.getAttribute("ex"); %> 
	<H2>Exception: <%= ex.getMessage()%></H2> 
	<P/> 
	<% ex.printStackTrace(new java.io.PrintWriter(out)); %> 
2.如果是EL显示错误信息
	<div>${ex }</div>
	<div>${ex.message }</div>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值