天天看點

SpringMVC(12):異常處理(局部異常和全局異常)

18/1/15

    SpringMVC 通過 HandlerExceptionResolver 處理程式異常,包括:處理器異常、資料綁定異常、處理器執行發生的異常。HandlerExceptionResolver 僅僅隻有一個接口方法。當發送異常時,SpringMVC 調用 resolveException () 方法,并轉到ModelAndView 對應的視圖中,作為一個異常報告頁面回報給使用者。對于異常,一般分為局部和全局。

一、局部異常處理

【1】修改UserController.java,添加以下方法:

//局部異常
  @RequestMapping(value="exlogin",method=RequestMethod.GET)
  public String exlogin(@RequestParam String userName,@RequestParam String userPassword) throws SQLException{
    User user = userService.login(userName, userPassword);
    if(null == user){
      throw new RuntimeException("使用者名或者密碼不正确!");
    }
    return "redirect:frame";
  }
  
  //局部異常
  @ExceptionHandler(value={RuntimeException.class})
  public String handlerException(RuntimeException e, HttpServletRequest req){
    req.setAttribute("e", e);
    return "error";
  }      

exlogin方法處理使用者登入請求,若登入失敗,則抛出一個RuntimeException ,它會被處于同一個處理器類中的handlerException 方法捕獲。@ExceptionHandler 可以指定多個異常,這裡示例指定一個。handlerException 方法:把異常提示資訊放入HttpServletRequest 對象中,并傳回邏輯視圖名error。

【2】在login.jsp 添加${e.message};

二、全局異常處理

【1】注釋掉局部異常,然後在springmvc-servlet.xml 配置檔案配置全局異常:

<!-- 全局異常處理 -->
    <bean class="org.springframework.web.servlet.handler
          .SimpleMapperExceptionResolver">
      <property name="exceptionMappings">
        <props>
          <prop key="java.lang.RuntimeException">error</prop>
        </props>
      </property>
    </bean>      

全局異常用 SimpleMapperExceptionResolver 來實作,它将異常類名映射為視圖名,即發生異常時,會使用對應的視圖報告異常。

【2】在login.jsp 添加${exception.message};

【3】運作結果:

SpringMVC(12):異常處理(局部異常和全局異常)

繼續閱讀