struts的聲明式異常處理

情景

使用Struts封裝的下載文件的功能

當下載文件找不到的時候,struts獲取的InputStream爲null

這個時候,就會報500錯誤

java.lang.IllegalArgumentException : Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack. Check the tag specified for this action.  
       org.apache.struts2.dispatcher.StreamResult.doExecute(StreamResult.java:237)  
      .......

解決方案

因爲getInputSteam是struts自己完成的,所以我們不能再用try-catch了

這時候就要用到聲明式異常處理了

類似於web.xml中的error-page配置

聲明式異常處理

聲明式異常處理要用到兩個標籤exception-mappingresult

先放上剛剛解決方案的代碼

<package namespace="...">

<global-results>
<result name="notFound" type="redirect">notFound</result>
</global-results>

<action name="download" class="xxxx">

     <exception-mapping result="notFound" exception="java.lang.IllegalArgumentException"></exception-mapping>

....

</package>

當拋出異常,Struts就會檢查struts.xml裏面有沒有配置exception-mapping,檢查exception-mapping的class跟異常是否一樣,如果一樣就會找到exception-mapping的result,先檢查當前action內的result是否有匹配的(如果是<global-exeception-mapping>就直接檢查<global-results>),如果匹配上了,就執行result的內容,像正常的action返回result那樣

在這裏,就是返回了notFound的result,然後找到global-results裏有一個叫做notFound的result,然後執行重定向notFound,notFound是一個action

注意,如果result返回了一個action,那麼就要指定type="redirect"(默認的是dispatcher)

因爲處理聲明式異常的filter在接受action的後面,如果type是轉發請求的話,不會經過ActionFilter的處理,結果會報404

error-page

在web.xml中,可以針對某個error代碼(404、403、500。。。),去自定義錯誤頁面

demo

<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>

這時候,用戶亂輸入地址,就會被自動跳轉到index.html

查看原文:http://www.wewill.top/2016/06/02/struts%E7%9A%84%E5%A3%B0%E6%98%8E%E5%BC%8F%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章