1. Web. Xml to write a full-text interceptor
WEBROOT---web-inf----WEB. Xml
<filter><filter-name>struts2</filter-name><filter-class> org.apache.struts2.dispatcher.ng.filter.strutsprepareandexecutefilter</filter-class></filter ><filter-mapping><filter-name>Struts2</filter-name><url-pattern>/*< /url-pattern></filter-mapping>
2. Write a File Upload page
Webroot--e folder under-----upload.jsp
<body> <form action= "${pagecontext.request.contextpath}/fileuploadaction" method= "POST" enctype= " Multipart/form-data "> User name:<input type=" text "name=" username "><br/> file: <input type= "File" Name= "File1" ><br/> <input type= "Submit" value= "Upload" > </form> </body>
3. project file under Struts.xml
<struts> <!--II. General profile: Introducing all other profiles-- <include file= "Cn/itcast/e_fileupload/upload.xml" ></include> </struts>
4. Project SRC under Build package: Cn.itcast.e_fileupload under new Upload.xml
<?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><Packageextends= "Struts-default" abstract= "false" >< Action name= "Fileuploadaction" class= "Cn.itcast.e_fileupload.fileupload" ><result name= " Success ">/e/success.jsp</result></action></Package ></struts>
5. New Fileupload.java under Cn.itcast.e_fileupload
PackageCn.itcast.e_fileupload;ImportJava.io.File;Importorg.apache.commons.io.FileUtils;ImportOrg.apache.struts2.ServletActionContext;ImportCom.opensymphony.xwork2.ActionSupport; Public classFileUploadextendsactionsupport{PrivateFile file1; PrivateString File1filename; The variable is fixed in the form "File1" + FileName (note case)PrivateString File1contexttype; The variable is in a fixed format Public voidsetFile1 (File file1) { This. file1 =File1; } Public voidsetfile1filename (String file1filename) { This. File1filename =File1filename; } Public voidSetfile1contexttype (String file1contexttype) { This. File1contexttype =File1contexttype; } @Override PublicString Execute ()throwsException {String path=servletactioncontext.getservletcontext (). Getrealpath ("/upload"); File Desfile=NewFile (path,file1filename); Fileutils.copyfile (File1, desfile); returnSUCCESS; }}
Java File Upload struts2.0 implementation