springmvc處理局部異常和全局異常


springmvc通過HandlerExceptionResolver(是一個接口,在spring-webmvc依賴下)處理程序異常,包括處理器異常、數據綁定異常以及處理器執行時發生的異常。HandlerExceptionResolver僅有一個接口方法,如下

當發生異常時,springmvc會調用resolverException()方法,並轉到ModelAndView對應的視圖中,作為一個異常處理報告頁面反饋給用戶。

局部異常處理

局部異常處理僅能處理指定controller中的異常,使用@ExceptionHandler注解(在spring-web依賴下)實現,@ExceptionHandler可以指定多個異常,代碼如下

@RequestMapping(value = "exlogin.html", method = RequestMethod.GET)
public String exLogin(@RequestParam String userCode, @RequestParam String userPassword){
    User user = userService.selectUserByUserCodeAndUserPassword(userCode, userPassword);
    if (null == user){
        throw new RuntimeException("用戶名或者密碼不正確!");
    }
    return "redirect:/user/main.html";
}

@ExceptionHandler({RuntimeException.class})
public String handlerException(RuntimeException e, HttpServletRequest request){
    request.setAttribute("e", e);
    return "error";
}

在異常處理方法handlerException()中,把異常提示信息放入HttpServletRequest對象中

展示頁面輸出相應的異常信息${e.message},輸出自定義的異常信息

全局異常處理

全局異常處理可使用SimpleMappingExceptionResolver來實現。它將異常類名映射為視圖名,即發生異常時使用對應的視圖報告異常。然后在springmvc-servlet.xml中配置全局異常。

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="java.lang.RuntimeException">error</prop>
        </props>
    </property>
</bean>

 

指定當控制器發生RuntimeException異常時,使用error視圖顯示異常信息。當然也可以在<props>標簽內自定義多個異常。

error.jsp頁面中的message顯示,需修改為${exception.message}來拋出異常信息。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM