詳解Java的Struts架構中上傳檔案和用戶端驗證的實現_java

來源:互聯網
上載者:User

檔案上傳

Struts 2架構提供了內建支援處理檔案上傳使用基於HTML表單的檔案上傳。上傳一個檔案時,它通常會被儲存在一個臨時目錄中,他們應該由Action類進行處理或移動到一個永久的目錄,以確保資料不丟失。

請注意,伺服器有一個安全性原則可能會禁止寫到目錄以外的臨時目錄和屬於web應用的目錄。

在Struts中的檔案上傳是通過預先定義的攔截檔案上傳攔截器這是可通過org.apache.struts2.interceptor.FileUploadInterceptor類的defaultStack中的一部分。仍然可以使用在struts.xml中設定各種參數,我們將在下面看到。

建立視圖檔案:
讓我們開始建立我們認為這將需要瀏覽和上傳選定的檔案。因此,讓我們建立一個純HTML上傳表單,允許使用者上傳檔案 index.jsp:

<%@ 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 結果顯示我們的檔案上傳的情況下成功。

<%@ 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 可能會有一些錯誤,在上傳檔案:

<%@ 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 這會處理上傳檔案,該檔案儲存體在一個安全的位置:

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如下:

<?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)類型,如下所示:

  <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檔案中的內容:

<?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,這將被用來收集上述員工的相關資訊。

<%@ 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。

<%@ 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方法將不會被執行。

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的設定檔如下:

<?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檔案中的內容:

<?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方法有兩個參數。首先是表單欄位名錯誤,第二個是錯誤資訊,上面顯示該表單欄位。

addFieldError("name","The name is required");

要處理的傳回值輸入,我們需要添加以下的結果,以我們的動作節點在struts.xml。

<result name="input">/index.jsp</result>

基於XML的驗證:
在進行驗證的第二個方法是通過將一個xml檔案的動作類。Struts2的基於XML驗證的驗證提供了更多的選擇,如電子郵件驗證,整數範圍驗證,表單驗證欄位,運算式驗證,Regex驗證,需要驗證,驗證所需的字串,字串長度的驗證等。

XML檔案需要被命名為'[action-class]'-validation.xml。所以,在我們的例子中,我們建立一個檔案,名為 Employee-validation.xml包含以下內容:

<!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()方法如下:

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。常見的驗證封裝括驗證日期,Regex驗證字串長度的驗證。檢查以下連結更多細節 Struts - 基於XML的校正.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.