The implementation of uploading files and client verification in the Java Struts Framework _java

Source: Internet
Author: User
Tags tomcat server

File Upload

The Struts 2 framework provides built-in support for handling file uploads using HTML forms based file uploads. When uploading a file, it is usually stored in a temporary directory, and they should be processed by the action class or moved to a permanent directory to ensure that the data is not lost.

Note that the server has a security policy that may prevent temporary directories that are not written to the directory and directories that belong to the Web application.

File uploads in struts are uploaded to the interceptor via a predefined intercept file that is part of the defaultstack that can be passed through the Org.apache.struts2.interceptor.FileUploadInterceptor class. You can still use the various parameters set in Struts.xml, which we'll see below.

To create a view file:
Let's start by creating what we think will require browsing and uploading selected files. So let's create a plain HTML upload form that allows users to upload files 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>
 
 

In the above example, it is worth noting a few notes. First, the Enctype property of the form is set to Multipart/form-data. This should be set to make the process file upload file upload. The next point worth noting is the form's action method upload and File upload field name-MyFile. We need this information to create action methods and struts configuration.

Next let's create a simple JSP file with success.jsp results that show our files uploaded in case of success.

<%@ page contenttype= "text/html; Charset=utf-8 "%>
<%@ taglib prefix=" s "uri="/struts-tags "%>
 
 

Following the result file error.jsp There may be some errors in uploading the file:

<%@ page contenttype= "text/html; Charset=utf-8 "%>
<%@ taglib prefix=" s "uri="/struts-tags "%>
 
 

To create an action class:
Next let's create a Java class called Uploadfile.java which processes the upload file, which is stored in a secure location:

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;
  The 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 is a very simple class. It is important to note that using the FileUpload interceptor with the parameter Intercetpor does solve all the heavy work for us. The file uploads the interceptor so that three parameters are provided by default. They are named the following pattern:

[Your file name parameter]-this is the actual upload of the file. In this case, it's "myFile."

[Your file name parameter] ContentType-This is the file that is uploaded, the content type of the file. In this case, it's "Myfilecontenttype."

[Your file name parameter] FileName-This is the name of the file being uploaded. In this case, it's "myfilefilename."

These three parameters are provided for us, thanks to the interceptors of struts. All we need to do is in our action class, these variables are automatically wired we create three parameters with the correct name. So, in the above example, we have three parameters of the operation method simply return to "success", if all goes well, otherwise return "error".

Configuration file:
The following are STRUTS2 configuration properties that control the file upload process:

To change these settings, you can use a constant label in the application Struts.xml file, as I change the maximum size of the file to upload. Let's have our struts.xml in the following:

<?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>

Since the FileUpload interceptor is part of the Interceptor Defaultstack, we do not need to explicitly configure it. But you can add <interceptor-ref> tags to <action> inside. The file upload interceptor requires two parameters: (a) MaximumSize and (b) allowedtypes. The MaximumSize parameter sets the maximum file size allowed (the default is about 2MB). The content accepted by the Allowedtypes parameter is a comma-delimited list (MIME) type, as follows:

  <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>

The following are the contents of the Web.xml file:

 <?xml version= "1.0" encoding= "UTF-8"?> <web-app "xmlns:xsi=" /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-f ile-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <fi lter-name>struts2</filter-name> <filter-class> Org.apache.struts2.dispatcher.FilterDispatcher &L t;/filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <u rl-pattern>/*</url-pattern> </filter-mapping> </web-app> 

Right-click the project name and click Export > War file to create a war document. This war is then deployed under Tomcat's WebApps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/upload.jsp. This will give you the following picture:

Now select a file "Contacts.txt" using the "Browse" button, then click the Upload button to upload the file, you should see the page. Can check uploaded files saved in c:apache-tomcat-6.0.33work.

Please note that using FileUpload to intercept deleted uploaded files automatically so needs to be programmed in some locations to save uploaded files before being deleted.

Error message:
The Fileuplaod interceptor uses several default error message keys:

Validation framework

Now, we'll look at how the Struts validation framework is. At the core of struts is a validation framework that assists the application's running rules to perform the methods of operation before validation is performed.

Typically, JavaScript is used to implement client-side validation. However, you should not rely on client-side validation alone. Best practices show that validation should introduce the application framework at all levels. Now, let's look at two ways to add validation to our struts project.

Here, we will take an example where the Employee will be captured by name and age using a simple page, we will put two validations to ensure that use always enters a name and age should be between 28 and 65. So let's start with the main JSP page example.

To create a master page:
Let's write the index.jsp of the main JSP page file, which will be used to collect information about the above employees.

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

In index.jsp using struts labels, we haven't covered them yet, but we'll look at the relevant chapters of these tags. But now, suppose the S:textfield label prints an input field s:submit print a Submit button. We have used the label attribute tag, each label is created for each tag.

To create a view:
We will use the success.jsp of the JSP file to return the action defined by the invocation to 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>
 
 

To create an action:
So let's define a small action class employee, and then add a method called Validate (), as shown in the Employee.java file. Make sure that the action class extends the Actionsupport class, otherwise the Validate method will not be executed.

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 < |-age >)
   {
     addfielderror (' age ', ' age must is in between ');}
  }


As shown in the example above, the validation method for the "Name" field checks for a value or not. If no value has been provided, we add a field error with the custom error message "Age" field. Second, we check if the value entered is between 28 and 65 or is not "age" field, if this condition does not conform to our validation field add an error.

Configuration file:
And finally, let's get everything together. The Struts.xml configuration file is as follows:

<?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>

The following are the contents of the Web.xml file:

 <?xml version= "1.0" encoding= "UTF-8"?> <web-app "xmlns:xsi=" /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-fil e-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <fil Ter-name>struts2</filter-name> <filter-class> Org.apache.struts2.dispatcher.FilterDispatcher ;/filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <ur l-pattern>/*</url-pattern> </filter-mapping> </web-app> 

Now, right click on the project name and click Export > War file to create a war document. This war is then deployed under Tomcat's WebApps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you the following picture:

Now do not enter any required information, just click the "Submit" button. You will see the following results:

Enter the required information, but enter the wrong from field, let's say "test" and age 30, and then click the "Submit" button. You will see the following results:

How does this validation work?
When the user presses the Submit button, Struts2 automatically executes the validation method, and if any of the methods inside the IF statement are listed, Struts 2 calls the Addfielderror method. If any errors have been added to struts 2, the Execute method will not be invoked. The Struts 2 framework will return input as the result of invoking the action.

Therefore, STRUTS2 returns input when the validation fails, and the Struts 2 framework will display the index.jsp file again. Because we use the form tab of Struts 2, the error message is automatically added in Struts2, which is submitted in the form above.

These error messages are specified in our Addfielderror method invocation. The Addfielderror method has two parameters. The first is the form field name error, and the second is the error message, which shows the form field.

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

To process the return value input, we need to add the following result to our action node in Struts.xml.

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

XML-based validation:
The second way to authenticate is by moving the action class of an XML file. STRUTS2 validation based on XML provides more choices, such as email verification, integer range validation, form validation fields, expression validation, regular expression validation, validation, validation of required strings, string length validation, and so on.

The XML file needs to be named ' [Action-class] '-validation.xml. So, in our example, we create a file named Employee-validation.xml that contains the following:

<! 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 being in
      between
     </message>
   </field-validator >
  </field>
</validators>

The above XML file will be saved in Classpath along the class file. Let's have our employee action Class no validate () method is as follows:

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;
  }
}

The rest of the settings will remain as it is in front of me, and now, if you run the application, it will produce the same result as we did in the previous example:

The advantage of the XML file to store the configuration is the separation of the allowed validation from the application code. Allows developers to write code and business analysts to establish validation XML files. The other thing to be aware of is the type of validation provided by default. There is a lot of validation, by default, using struts. Common validation includes validation dates, and regular expressions validate string lengths. Check the links below for more details Struts-xml-based checksum.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.