When using the servlet upload, because the request inside sometimes contains both parameter information and file information, it will be very cumbersome to take out, so we can according to request the principle of extracting parameters, The equivalent of customizing a request to implement the separation of our file uploads and other parameter extraction.
I. Relationship and dependencies
Before you introduce this question, you need to understand a few concepts
Class A{ private B b;}
- depend on the relationship
The following code explains that the method in a requires class B to participate as a parameter
Class A{ publicvoidf(B b);}
Speaking of this reminds of the decorator mode, both can be said to be a decorator mode of implementation of it. The next thing to do is to use decorator mode to solve.
Two. Implement 1.HttpServletRequest
From the class structure diagram, we can see that HttpServletRequest implements two interfaces, here we focus on httpservletrequestwrapper.
The Find API will find that Httpservletrequestwrapper manages the method of httpservletrequest inside the lock call, so we just need to customize a class , inherit Httpservletrequestwrapper, and then use the custom class to create the req to implement the custom request.
2. Custom Multipartrequestwrapper
Need to introduce two upload package before customizing
Before customizing, it is important to note that uploading data may have a multivalued phenomenon, such as a CheckBox, which is an array. In addition to the previous file upload using the traditional method traditional API, which is replaced by the streaming API, This approach is faster than the traditional way.
ImportOrg.apache.commons.fileupload.FileItemIterator;ImportOrg.apache.commons.fileupload.FileItemStream;ImportOrg.apache.commons.fileupload.FileUploadException;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload;ImportOrg.apache.commons.fileupload.util.Streams;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletRequestWrapper;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.util.Arrays;ImportJava.util.HashMap;ImportJava.util.Map;/** * Created by nl101 on 2016/3/8. * * Public class multipartrequestwrapper extends httpservletrequestwrapper { //collection of storage parameters Privatemap<string,string[]> params =NewHashmap<> ();Private StaticString PATH ="e:\\temp\\";//Set upload path Public Multipartrequestwrapper(HttpServletRequest request) {Super(request); SetParams (Request);//Parse the request and deposit it in map}/** * Upload files by Streamingapi * * Private void SetParams(HttpServletRequest request) {//Get upload file type if(Servletfileupload.ismultipartcontent (Request)) {//Create Servletfileupload instancesServletfileupload fileUpload =NewServletfileupload ();Try{//Resolve request requests to return iterator instances of FileitemstreamFileitemiterator iter = fileupload.getitemiterator (request); InputStream is =NULL;//output stream //Iterative removal while(Iter.hasnext ()) {Fileitemstream item = Iter.next ();//Get file streamString name = Item.getfieldname ();//Returns the name value of the label in the formis = Item.openstream ();//Get the output stream of the corresponding form if(Item.isformfield ()) {//If the non-file domain, set into map, here to pay attention to multi-value processingSetformparam (Name,is);//If not file upload, process}Else{if(Is.available () >0){//If the content of the output stream is greater than 0String fname = Item.getname ();//Get file nameStreams.copy (IS,NewFileOutputStream (Path+fname),true);//copy content to upload pathParams.put (Name,NewString[]{fname});//Set the file name into request} } } }Catch(Fileuploadexception e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); } }Else{params = Request.getparametermap ();//If it is not a file upload request, set the map directly} }/** * Processing non-uploaded forms * @param name * @param is */ Private void Setformparam(String name, InputStream is) {Try{if(Params.containskey (name)) {//Determine if the current value name has been storedString[] values = params.get (name);//Remove values that have been storedValues = arrays.copyof (values,values.length+1);//Extend the current arrayvalues[values.length-1] = Streams.asstring (IS);//Add new valueParams.put (name,values);//re-add to map}Else{Params.put (name,NewString[]{streams.asstring (IS)});//Direct deposit in Parameters} }Catch(IOException e) {E.printstacktrace (); } }/** * Returns the parameter map collection, the custom uploads the file, the upload succeeds returns the file name * @return * / @Override PublicMap<string,string[]>Getparametermap() {returnParams }/** * Remove parameters from Request * @param name * @return * * @Override PublicStringGetParameter(String name) {string[] values = params.get (name);if(values!=NULL) {returnvalues[0]; }return NULL; }/** * Remove multiple parameter values from the request, such as the checkbox's value * @param name * @return * * @Override PublicString[]getparametervalues(String name) {string[] values = params.get (name);if(values!=NULL) {returnValues }return NULL; }}
3. Use a custom request
It's easy to use, just wrap the req in the servlet that handles the upload.
ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJava.io.IOException;/** * Created by nl101 on 2016/3/9. * * Public class uploadservlet extends httpservlet { @Override protected void DoPost(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {req =NewMultipartrequestwrapper (req);//re-packagingReq.getparameter ("username");//Then you can handle the request as usual.Req.getparameter ("File");//Then you can handle the request as usual.}}
Don't forget to configure the Web. xml file
<servlet> <servlet-name>Uploadservlet</servlet-name> <servlet-class>Com.servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Uploadservlet</servlet-name> <url-pattern>/upload.do</url-pattern> </servlet-mapping>
4,jsp Test
<%@ page contenttype="Text/html;charset=utf-8" language="java" %><html> <head> <title>Upload Test</title> </head> <body> <form Action="Upload.do" method="POST" enctype=" Multipart/form-data "> <table Border="1"> <tr> <TD>User name:<input name="username" type="text"></td> </tr> <tr> <TD>Upload:<input type="file" name="file"></td> </tr> <tr> <TD><input type="Submit" value="Upload"></td> </tr> </table> </form> </body></html>
So click Upload, you can complete the upload, and our processing or as usual through the Req.getparameter ("username"), so that the use of worry too much.
servlet file upload based on Httpservletrequestwrapper