Use annotations in struts2 to upload and download objects (1)

Source: Internet
Author: User

In struts2, the commons fileupload component is used to Easily upload and download files. commons fileupload saves HTTP data to a temporary folder, then struts uses the fileupload Interceptor to bind the file to the action instance, so that we can operate the browser to upload the file as a local file. However, most of these examples need to be configured in struts. XML, it is more troublesome, fortunately, struts2 provides the struts2-convention-plugin plug-in, you can use annotations in the program to configure action, making it more flexible.

The following describes how to upload objects using Annotations:

1. Add the dependent jar package

2. Configure the Struts. xml file. The struts file here basically does not need to be configured, as shown below:

<? XML version = "1.0" encoding = "UTF-8"?> <! Doctype struts public "-// Apache Software Foundation // DTD struts configuration 2.3 // en" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name = "struts. enable. dynamicmethodinvocation "value =" true "/> <constant name =" struts. devmode "value =" true "/> <constant name =" struts. convention. package. locators "value =" action "/> <! -- Specify the maximum number of bytes of files that can be uploaded. The default value is 2097152 (2 m). Use the struts constant to expand the default size of the uploaded files --> <constant name = "struts. multipart. maxsize "value =" 104857600 "> </constant> </struts>

3. Compile the File Upload action: fileuploadaction. Java

Package COM. figo. action; import Java. io. bufferedinputstream; import Java. io. bufferedoutputstream; import Java. io. file; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. inputstream; import Java. io. outputstream; import Org. apache. struts2.servletactioncontext; import Org. apache. struts2.convention. annotation. action; import Org. apache. struts2.convention. annotation. interceptorref; imp ORT Org. apache. struts2.convention. annotation. interceptorrefs; import Org. apache. struts2.convention. annotation. result; import Org. apache. struts2.convention. annotation. results; import COM. opensymphony. xwork2.actionsupport; @ action ("fileupload") @ interceptorrefs (value ={@ interceptorref ("fileuploadstack")}) @ results ({@ result (name = "success ", location = "/result. JSP ")}) public class fileuploadaction ext Ends actionsupport {Private Static final long serialversionuid = 572146812454l; Private Static final int buffer_size = 16*1024; // encapsulate the attributes of the uploaded file domain private file upload; // encapsulate the private string contenttype attribute of the upload file type; // encapsulate the private string filename attribute of the Upload File Name; private string storagefilename; // Private string storagepath; // since we are using <s: file name = "Upload "... /> the file itself will be // obtained through Getter /Setter of <file-tag-Name> Public file getupload () {return upload;} public void setupload (File Upload) {This. upload = upload;} Public String getfilename () {return filename;} public void setfilename (string filename) {This. filename = filename;} // since we are using <s: file name = "Upload "... /> the file name will be // obtained through getter/setter of <file-tag-Name> filenamepublic string getuploadfilename () {Return filename;} public void setuploadfilename (string filename) {This. filename = filename;} Public String getstoragefilename () {return storagefilename;} public void setstoragefilename (string storagefilename) {This. storagefilename = storagefilename;} // since we are using <s: file name = "Upload "... /> the content type will be // obtained through getter/setter of <file-tag-Name> contenttypepublic stri Ng getuploadcontenttype () {return contenttype;} public void setuploadcontenttype (string contenttype) {This. contenttype = contenttype;} Public String getcontenttype () {return contenttype;} public void setcontenttype (string contenttype) {This. contenttype = contenttype;} public void copy (File SRC, file DST) {try {inputstream in = NULL; outputstream out = NULL; try {In = new bufferedinputstream (New fileinpu Tstream (SRC), buffer_size); out = new bufferedoutputstream (New fileoutputstream (DST), buffer_size); byte [] buffer = new byte [buffer_size]; while (in. read (buffer)> 0) {out. write (buffer) ;}} finally {If (null! = In) {in. Close () ;}if (null! = Out) {out. close () ;}} catch (exception e) {e. printstacktrace () ;}} public static string getextention (string filename) {int Pos = filename. lastindexof (". "); Return filename. substring (POS) ;}@ overridepublic string execute () throws exception {// storagefilename = new date (). gettime () + getextention (filename); storagefilename = filename; system. out. println ("filename:" + filename); system. out. println ("contenttype:" + contenttype); system. out. println ("file:" + upload); file storagefile = new file (servletactioncontext. getservletcontext (). getrealpath ("/upload") + "/" + storagefilename); copy (upload, storagefile); Return success ;}}

Fileuploadaction is used to copy files uploaded by the browser to the upload folder of the Web application.

4. Compile the File Upload form page upload. jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><%@ taglib prefix="s" uri="/struts-tags"%><! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

Set the form submission method to post, and enctype to multipart/form-data. The <s: File/> flag binds the File Upload control to the upload attribute of the action.

5. Result. jsp:

<%@ page language="java" contentType="text/html;charset=utf-8"pageEncoding="utf-8"%><%@ taglib prefix="s" uri="/struts-tags"%><! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

6. Configure 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>Upload</display-name>    <filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>        <init-param>            <param-name>actionPackages</param-name>            <param-value>com.figo.action</param-value>       </init-param>  </filter><filter>         <filter-name>struts-cleanup</filter-name>         <filter-class>             org.apache.struts2.dispatcher.ActionContextCleanUp        </filter-class>     </filter> <filter-mapping>         <filter-name>struts-cleanup</filter-name>         <url-pattern>/*</url-pattern>     </filter-mapping> <filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>    <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

The focus is to add <init-param> to the filter, and the actionpackages is the package where the action file is located.

7. Page test:

File upload page:

File Upload result:

Because the test is carried out in the Eclipse project, the file is saved in the temporary file. If it is actually released, the uploaded file will be saved to the preset directory.

Note:

1. By default, struts2 can only upload files up to 2 MB. You can expand the default file upload size in struts. xml.

2. summarize common annotations as follows:

Namespace: Specify the namespace.

Parentpackage: Specifies the parent package.

Result: provides the action ing of action results (a result ing ).

Results: "result" annotation list.

Resultpath: Specify the base path of the result page.

Action: Specifies the access URL of the action.

Actions: "action" annotation list.

Exceptionmapping: Specifies the exception ing (ing a declaration exception ).

Predictionmappings: An array with an exception declared at the first level.

Interceptorref: the interceptor reference.

Interceptorrefs: the interceptor reference group.

Here is just an example of the effect, the program itself is very simple, mainly configuration, the next article introduces the download of the zero configuration file.

Source code download link: http://download.csdn.net/detail/sxwyf248/4462899

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.