spring mvc 可以配置统一的错误跳转页面

来源:互联网 发布:骨朵网络影视数据查询 编辑:程序博客网 时间:2024/04/30 02:52

首先在spring.xml里面配置

    <!-- 配置使用SimpleMappingExceptionResolver 来映射异常 -->
     <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
         <property name="exceptionAttribute" value="ex"></property>         <!-- 配置异常属性值,在页面可以直接用ex打印   默认值是exception-->
         <property name="exceptionMappings">
             <props>
                 <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>  <!-- 这里配置是报错异常跳转的页面,这个可以自己将异常传入页面上,可以不用modelandview带key和value传入到jsp页面 -->
             </props>
         </property>
     </bean>


编写如下代码

package com.ao.test;
import java.io.IOException;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import com.ao.dao.EmployeeDao;
import com.ao.entities.Employee;
@Controller
public class SpringMVCTest {
    @Autowired
    private EmployeeDao employeeDao;
    @RequestMapping("testSimpleMappingExceptionResolver")                                      //如果当真正的错误的时候,会报java.lang.ArrayIndexOutOfBoundsException异常
    public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
        String [] vals=new String[10];
        System.out.println(vals[i]);
        return "success";
    }

}


当报了异常的时候就可以在jsp页面上进行直接打印

${ex}

0 0
原创粉丝点击