文件上傳
Struts 2框架提供了內置支持處理文件上傳使用基于HTML表單的文件上傳。上傳一個文件時,它通常會被存儲在一個臨時目錄中,他們應該由Action類進行處理或移動到一個永久的目錄,以確保數據不丟失。
請注意,服務器有一個安全策略可能會禁止寫到目錄以外的臨時目錄和屬于web應用的目錄。
在Struts中的文件上傳是通過預先定義的攔截文件上傳攔截器這是可通過org.apache.struts2.interceptor.FileUploadInterceptor類的defaultStack中的一部分。仍然可以使用在struts.xml中設置各種參數,我們將在下面看到。
創建視圖文件:
讓我們開始創建我們認為這將需要瀏覽和上傳選定的文件。因此,讓我們創建一個純HTML上傳表單,允許用戶上傳文件 index.jsp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <%@ taglib prefix= "s" uri= "/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <title>File Upload</title> </head> <body> <form action= "upload" method= "post" enctype= "multipart/form-data" > <label for = "myFile" >Upload your file</label> <input type= "file" name= "myFile" /> <input type= "submit" value= "Upload" /> </form> </body> </html> |
在上面的例子中值得注意幾點說明。首先,表單的enctype屬性設置為multipart/ form-data。這應該是設置為使得處理文件上傳文件上傳。下一個點值得注意的是表單的 action方法上傳和文件上傳字段的名稱 - myFile。我們需要這些信息創建操作方法和struts配置。
接下來讓我們創建一個簡單的 jsp 文件的success.jsp 結果顯示我們的文件上傳的情況下成功。
1
2
3
4
5
6
7
8
9
10
|
<%@ page contentType= "text/html; charset=UTF-8" %> <%@ taglib prefix= "s" uri= "/struts-tags" %> <html> <head> <title>File Upload Success</title> </head> <body> You have successfully uploaded <s:property value= "myFileFileName" /> </body> </html> |
下面將結果文件error.jsp 可能會有一些錯誤,在上傳文件:
1
2
3
4
5
6
7
8
9
10
|
<%@ page contentType= "text/html; charset=UTF-8" %> <%@ taglib prefix= "s" uri= "/struts-tags" %> <html> <head> <title>File Upload Error</title> </head> <body> There has been an error in uploading the file. </body> </html> |
創建action類:
接下來讓我們創建一個Java類稱為 uploadFile.java 這會處理上傳文件,該文件存儲在一個安全的位置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
package com.yiibai.struts2; import java.io.File; import org.apache.commons.io.FileUtils; import java.io.IOException; import com.opensymphony.xwork2.ActionSupport; public class uploadFile extends ActionSupport{ private File myFile; private String myFileContentType; private String myFileFileName; private String destPath; public String execute() { /* Copy file to a safe location */ destPath = "C:/apache-tomcat-6.0.33/work/" ; try { System.out.println( "Src File name: " + myFile); System.out.println( "Dst File name: " + myFileFileName); File destFile = new File(destPath, myFileFileName); FileUtils.copyFile(myFile, destFile); } catch (IOException e){ e.printStackTrace(); return ERROR; } return SUCCESS; } public File getMyFile() { return myFile; } public void setMyFile(File myFile) { this .myFile = myFile; } public String getMyFileContentType() { return myFileContentType; } public void setMyFileContentType(String myFileContentType) { this .myFileContentType = myFileContentType; } public String getMyFileFileName() { return myFileFileName; } public void setMyFileFileName(String myFileFileName) { this .myFileFileName = myFileFileName; } } |
uploadFile.java是一個非常簡單的類。重要的是要注意的是使用FileUpload攔截器隨著參數Intercetpor 確實為我們解決所有繁重工作。文件上傳攔截器,使三個參數,默認情況下提供。它們被命名為以下模式:
[your file name parameter] - 這是實際的文件的上載。在這個例子中是 "myFile"
[your file name parameter]ContentType - 這是被上傳的文件,該文件的內容類型。在這個例子中是 "myFileContentType"
[your file name parameter]FileName - 這是被上傳的文件的名稱。在這個例子中是 "myFileFileName"
這三個參數是為我們提供的,這要歸功于Struts的攔截器。所有我們需要做的是在我們的Action類,這些變量是自動連線我們以正確的名稱創建三個參數。所以,在上面的例子中,我們有三個參數的操作方法簡單地返回“success”,如果一切順利,否則返回“error”。
配置文件:
以下是Struts2的配置屬性可以控制文件上傳過程:
為了改變這些設置,可以使用恒定的標簽在應用程序 struts.xml文件,像我一樣改變要上傳的文件的最大大小。讓我們有我們的在struts.xml如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> < struts > < constant name = "struts.devMode" value = "true" /> < constant name = "struts.multipart.maxSize" value = "1000000" /> < package name = "helloworld" extends = "struts-default" > < action name = "upload" class = "com.yiibai.struts2.uploadFile" > < result name = "success" >/success.jsp</ result > < result name = "error" >/error.jsp</ result > </ action > </ package > </ struts > |
由于FileUpload攔截器是攔截器defaultStack的一部分,我們并不需要明確地配置。但可以添加<interceptor-ref>標簽到<action>里面。文件上傳攔截器需要兩個參數:(a)maximumSize及(b)allowedTypes。maximumSize參數設置允許的最大文件大小(默認為約2MB)。allowedTypes參數接受的內容是一個逗號分隔的列表(MIME)類型,如下所示:
1
2
3
4
5
6
7
8
|
< action name = "upload" class = "com.yiibai.struts2.uploadFile" > < interceptor-ref name = "basicStack" > < interceptor-ref name = "fileUpload" > < param name = "allowedTypes" >image/jpeg,image/gif</ param > </ interceptor-ref > < result name = "success" >/success.jsp</ result > < result name = "error" >/error.jsp</ result > </ action > |
以下是web.xml文件中的內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<? xml version = "1.0" encoding = "UTF-8" ?> < web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0" > < display-name >Struts 2</ display-name > < welcome-file-list > < welcome-file >index.jsp</ welcome-file > </ welcome-file-list > < filter > < filter-name >struts2</ filter-name > < filter-class > org.apache.struts2.dispatcher.FilterDispatcher </ filter-class > </ filter > < filter-mapping > < filter-name >struts2</ filter-name > < url-pattern >/*</ url-pattern > </ filter-mapping > </ web-app > |
現在右鍵點擊項目名稱,并單擊 Export > WAR File 創建一個WAR文件。然后部署此WAR在Tomcat 的webapps目錄下。最后,啟動Tomcat服務器和嘗試訪問URL http://localhost:8080/HelloWorldStruts2/upload.jsp。這會給出以下畫面:
現在選擇一個文件的“Contacts.txt”使用“瀏覽”按鈕,然后點擊上傳按鈕,將文件上傳,應該看到頁面。可以檢查上傳的文件保存在 C:apache-tomcat-6.0.33work.
請注意,使用FileUpload攔截刪除上傳的文件自動所以需要編程在一些位置上保存上傳的文件被刪除之前。
錯誤消息:
fileUplaod攔截器使用幾個默認的錯誤消息鍵:
驗證框架
現在,我們將看看如何的Struts驗證框架。在Struts的核心有驗證框架,協助應用程序的運行規則來執行驗證執行之前的操作方法。
通常是使用Javascript來實現客戶端驗證。但不應單獨依賴于客戶端驗證。最佳實踐表明,驗證應引入各級應用程序框架。現在,讓我們來看看兩種方式添加驗證我們的Struts項目。
在這里,我們將采取一個例子,Employee 將被捕獲的姓名和年齡使用一個簡單的頁面,我們將會把兩個驗證,以確保使用總是進入一個名字和年齡應該是在28和65之間。所以,讓我們先從主JSP頁面的例子。
創建主頁面:
讓我們寫主JSP頁面文件的index.jsp,這將被用來收集上述員工的相關信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <%@ taglib prefix= "s" uri= "/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <title>Employee Form</title> </head> <body> <s:form action= "empinfo" method= "post" > <s:textfield name= "name" label= "Name" size= "20" /> <s:textfield name= "age" label= "Age" size= "20" /> <s:submit name= "submit" label= "Submit" align= "center" /> </s:form> </body> </html> |
在index.jsp使用Struts的標簽,我們還沒有涉及,但我們將研究這些標簽相關的章節。但現在,假設 s:textfield 標簽打印一個輸入字段s:submit打印一個提交按鈕。我們已經使用label屬性標簽,每個標簽每個標簽創建。
創建視圖:
我們將使用JSP文件的success.jsp將調用的情況下定義的動作返回SUCCESS。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<%@ page language= "java" contentType= "text/html; charset=ISO-8859-1" pageEncoding= "ISO-8859-1" %> <%@ taglib prefix= "s" uri= "/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > <html> <head> <title>Success</title> </head> <body> Employee Information is captured successfully. </body> </html> |
創建動作:
因此,讓我們定義一個小小的動作類Employee,然后添加一個方法稱為validate(),如下所示在Employee.java文件。請確保操作類擴展ActionSupport類,否則validate方法將不會被執行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package com.yiibai.struts2; import com.opensymphony.xwork2.ActionSupport; public class Employee extends ActionSupport{ private String name; private int age; public String execute() { return SUCCESS; } public String getName() { return name; } public void setName(String name) { this .name = name; } public int getAge() { return age; } public void setAge( int age) { this .age = age; } public void validate() { if (name == null || name.trim().equals( "" )) { addFieldError( "name" , "The name is required" ); } if (age < 28 || age > 65 ) { addFieldError( "age" , "Age must be in between 28 and 65" ); } } } |
如在上面的例子所示,“Name”字段的驗證方法檢查是否有一個值,或不。如果沒有值已經提供,我們添加一個帶有自定義錯誤消息“Age”字段的字段錯誤。其次,我們檢查,如果輸入的值是在28和65之間或不為“Age”字段,如果這個條件不符合我們以上驗證字段添加一個錯誤。
配置文件:
最后,讓我們把所有東西一起使用struts.xml的配置文件如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> < struts > < constant name = "struts.devMode" value = "true" /> < package name = "helloworld" extends = "struts-default" > < action name = "empinfo" class = "com.yiibai.struts2.Employee" method = "execute" > < result name = "input" >/index.jsp</ result > < result name = "success" >/success.jsp</ result > </ action > </ package > </ struts > |
以下是web.xml文件中的內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<? xml version = "1.0" encoding = "UTF-8" ?> < web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0" > < display-name >Struts 2</ display-name > < welcome-file-list > < welcome-file >index.jsp</ welcome-file > </ welcome-file-list > < filter > < filter-name >struts2</ filter-name > < filter-class > org.apache.struts2.dispatcher.FilterDispatcher </ filter-class > </ filter > < filter-mapping > < filter-name >struts2</ filter-name > < url-pattern >/*</ url-pattern > </ filter-mapping > </ web-app > |
現在,右鍵點擊項目名稱,并單擊Export > WAR File創建一個WAR文件。然后部署此WAR在Tomcat的webapps目錄下。最后,啟動Tomcat服務器和嘗試訪問URL http://localhost:8080/HelloWorldStruts2/index.jsp。這會給出以下畫面:
現在不輸入任何所需信息,只需點擊“Submit ”按鈕。將看到以下結果:
輸入所需的信息,但輸入了錯誤的From字段,讓我們說“test”和年齡為30,最后點擊“Submit ”按鈕。將看到以下結果:
此驗證是如何工作的?
當用戶按下提交按鈕時,Struts2會自動執行的驗證方法,如果任何一個if語句里面的方法列出,Struts 2調用addFieldError方法。如果有任何錯誤已加入Struts 2將不會進行調用execute方法。而Struts 2框架將返回輸入作為調用該行動的結果。
因此,驗證失敗時Struts2返回輸入,Struts 2框架將重新顯示index.jsp文件。因為我們使用了Struts 2的表單標簽,Struts2中會自動添加錯誤消息,只是上面的形式提交。
這些錯誤消息是我們addFieldError方法調用中指定的。addFieldError方法有兩個參數。首先是表單字段名錯誤,第二個是錯誤信息,上面顯示該表單字段。
1
|
addFieldError("name","The name is required"); |
要處理的返回值輸入,我們需要添加以下的結果,以我們的動作節點在struts.xml。
1
|
< result name = "input" >/index.jsp</ result > |
基于XML的驗證:
在進行驗證的第二個方法是通過將一個xml文件的動作類。Struts2的基于XML驗證的驗證提供了更多的選擇,如電子郵件驗證,整數范圍驗證,表單驗證字段,表達式驗證,正則表達式驗證,需要驗證,驗證所需的字符串,字符串長度的驗證等。
XML文件需要被命名為'[action-class]'-validation.xml。所以,在我們的例子中,我們創建一個文件,名為 Employee-validation.xml包含以下內容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> < validators > < field name = "name" > < field-validator type = "required" > < message > The name is required. </ message > </ field-validator > </ field > < field name = "age" > < field-validator type = "int" > < param name = "min" >29</ param > < param name = "max" >64</ param > < message > Age must be in between 28 and 65 </ message > </ field-validator > </ field > </ validators > |
上面的XML文件會被保存在CLASSPATH 沿著類文件。讓我們有我們的雇員動作類沒有validate()方法如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package com.yiibai.struts2; import com.opensymphony.xwork2.ActionSupport; public class Employee extends ActionSupport{ private String name; private int age; public String execute() { return SUCCESS; } public String getName() { return name; } public void setName(String name) { this .name = name; } public int getAge() { return age; } public void setAge( int age) { this .age = age; } } |
其余的設置將保持,因為它是我前面的例子,現在,如果運行應用程序,它會產生相同的結果是什么,我們在前面的例子:
xml文件來存儲配置的優點是允許的驗證從應用程序代碼的分離。可以讓開發人員編寫的代碼和業務分析師建立驗證xml文件。要注意的是另一件事是默認提供的驗證類型。有大量的驗證,默認情況下,使用Struts。常見的驗證包括驗證日期,正則表達式驗證字符串長度的驗證。檢查以下鏈接更多細節 Struts - 基于XML的校驗.