1. 程式人生 > >spring mvc 可以配置統一的錯誤跳轉頁面

spring mvc 可以配置統一的錯誤跳轉頁面

首先在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}