手工處理 Struts2 框架上傳的檔案

2021-04-20 03:39:25 字數 3029 閱讀 3196

手工處理 struts2 框架上傳的檔案

在使用了 struts2 框架的系統中,對於處理像下面這種表單上傳檔案時:

<

form

action="..."

enctype="multipart/form-data"

>

檔案:<

input

type="file"

name="upload"

>

<

br>

描述:<

input

type="text"

name="desc"

>

br>

<

input

type="submit"

value="提交"

>

form

>

自然而然的想法就是在 action 中宣告變數 file upload 和 string desc,請求提交到這個 action 後,在 execute() 方法中就能直接使用 upload 和 desc 了,它們已被 struts2 框架(

org.apache.struts2.interceptor.fileuploadinterceptor ***) 賦上了相應的值了。

因 為維護的是乙個古老的專案,請求都是直接提交給 jsp。在這個專案中套上了 struts2 已是不易了。原來專案是用的 jspsmartupload 來處理上傳檔案的,struts2 一上 jspsmartupload 便不能正常工作了,因為 struts2 的過濾器 org.apache.struts2.dispatcher.filterdispatcher 攔截的是所有的請求,在交把請求交給 jspsmartupload 之前請求 request 就已被處理過了,即使是把 struts2-core-2.x.x.jar 中的 struts-default.xml fileupload 取消了也是如此。

暫時又不想再新加乙個 action,宣告 upload:file 和 desc:string 直接接收引數,這樣改動的話實在是大,現在 struts.xml 和 struts.properties 檔案還是空的呢。所以姑且在原來那個 jsp 中處理吧。

最早做過 jsp 檔案上傳的人都知道,給 form 加上 enctype="multipart/form-data" 屬性後,request.getparameter("desc") 取輸入框的值就失靈了,因為頁面請求資料是以流的形式傳送給伺服器的,所以 jspsmartupload 用了它自己的 request, com.jspsmart.upload.smartupload.getrequest().getparameter("desc") 來接收文字框資料,但對於 struts2 處理過的 request jspsmartupload 就無能為力了。

那麼在 struts2 中的 jsp 如何獲取到 enctype="multipart/form-data" 表單傳遞過來的文字輸入和檔案呢?

·獲取文字框的值

對比一下不同時候 request 的具體實現類(tomcat 環境中)

form enctypemultipart/form-data

struts2

struts1org.apache.coyote.tomcat5

.coyoterequestfacade

無框架org.apache.coyote.tomcat5

.coyoterequestfacade

org.apache.coyote.tomcat5

.coyoterequestfacade

·獲取上傳來的檔案用就要對 request 作個轉型,才能呼叫到相應的方法

file files = mprequest.getfiles("upload");    //檔案現在還在臨時目錄中

string filenames = mprequest.getfilenames("upload");  

//然後就可以處理你的業務了

file files = mprequest.getfiles("upload"); //檔案現在還在臨時目錄中

string filenames = mprequest.getfilenames("upload");

//然後就可以處理你的業務了

最後,用了 struts2 來上傳檔案,最好在 web.xml 中加上 actioncontextcleanup 過濾器以避免一些未不預知的異常。

<

filter

>

<

filter-name

>struts-cleanup

filter-name

>

<

filter-class

>org.apache.struts2.dispatcher.actioncontextcleanup

filter-class

>

filter

>

<

>

<

filter-name

>struts-cleanup

filter-name

>

<

url-pattern

>/*

url-pattern

>

>

struts-cleanup

org.apache.struts2.dispatcher.actioncontextcleanup

/*網上有人說是要加 actioncontextcleanup 過濾器的,actioncontextcleanup 的**注釋是它易於同 sitemesh 的整合,至於為何與檔案上傳扯上關係,我以後也會關注的。

對了還要在專案中引入 commons-fileupload-x.x.x.jar 和 commons-io-x.x.jar 包,其他沒有什麼特別的配置,預設即可。相信本文的實用性不強,不會有人用 jsp 來處理這些事情,參考價值可能還有一些。

struts2框架上傳研究

本人系菜鳥,今天剛看了乙個ssh2的框架,感覺還是很神奇,裡面action裡的biz類居然不需要依賴注入,只需要名稱一樣就可以使用了,非常之神奇。問題1 一開始設定了乙個form,傳入後台發現死活呼叫不到我寫的方法。一直顯示 nosuchmethodexception 解決辦法 我錯誤的把biz當做...

Struts2框架中的處理http

請求在struts2框架中的處理大概分為以下幾個步驟 1 客戶端初始化乙個指向servlet容器的請求 2 這個請求經過一系列的過濾器 filter 這些過濾器中有乙個叫做actioncontextcleanup的可選過濾器,這個過濾器對於struts2和其他框架的整合很有幫助,例如 sitemes...

Struts2驗證框架

action配置中一定要設定input返回頁面 新增驗證只要建立驗證的xml檔案 在action同包下,建立 action類名 validation.xml 如 validateaction建立validateaction validation.xml 注意 1.要驗證的方法不能叫input.2.這...