简体   繁体   中英

How to get meaningful data from formdata with Java?

I have a form like this :

  <form id="test" name="test" action="/pages/font/getFontTitle.jsp" method="POST" enctype="multipart/form-data">
    <div class="dialog">
      <table>
        <tbody>
          <tr class="prop"><td valign="top">Name</td><td><input type="text" name="name"></td></tr>
          <tr class="prop"><td valign="top"><input type="file" name="fname" size="62" value="" id="fname"/></td><td><span class="button"><s:submit/></span></td></tr>
        </tbody>
      </table>
    </div> 
  </form>

And my servlet look like this :

String contentType=request.getContentType(),Location="0.";
out.println("Done");
System.out.println("contentType = "+contentType);

  boolean isMultipart=ServletFileUpload.isMultipartContent(request);           // Check that we have a file upload request
  System.out.println("isMultipart = "+isMultipart);

  int formDataLength=request.getContentLength();                           // We are taking the length of Content type data
  byte dataBytes[]=new byte[formDataLength];
  System.out.println("dataBytes = "+dataBytes.length+"\n"+dataBytes.toString());

  java.util.Map<java.lang.String,java.lang.String[]> ParameterMap=request.getParameterMap();
  Iterator it=ParameterMap.entrySet().iterator();
  while (it.hasNext())
  {
    Map.Entry pair=(Map.Entry)it.next();
    System.out.println(pair.getKey()+" = "+(pair.getValue()).toString());
//    it.remove(); // avoids a ConcurrentModificationException
  }
  System.out.println("request = \n"+request.getParameterNames().toString());

  if (isMultipart)
  {
    FileItemFactory factory=new DiskFileItemFactory();
    ServletFileUpload upload=new ServletFileUpload(factory);
    List items=null;
Location+="1.";
    try { items=upload.parseRequest(request); }
    catch (FileUploadException e) { e.printStackTrace(); }
    Location+="2.";
    Iterator itr=items.iterator();
    Location+="3.";
    while (itr.hasNext()) 
    {
        Location+="4.";
      FileItem item=(FileItem)itr.next();
      if (item.isFormField())
      {
        String name=item.getFieldName(),value=item.getString();
        System.out.println("name = "+name+"  value = "+value);
        Location+="5.";
      }
      else
      {
        try
        {
          Location+="6.";
          String itemName=item.getName(),savedFilePath=itemName;
          File savedFile=new File(savedFilePath);
          System.out.println("savedFile = "+savedFile.getAbsolutePath());
          item.write(savedFile);
        }
        catch (Exception e) { e.printStackTrace(); }
      }
    }
  }
Location+="e.";

  out.println(" [ "+Location+" ]");
  out.flush();

The result I get was :

contentType = multipart/form-data; boundary=---------------------------15890672924370
isMultipart = true
dataBytes = 35909
[B@14d3ba9
name = [Ljava.lang.String;@187f9d7
request = 
java.util.Vector$1@23ca6e

dataBytes has a file in it, but it never got into the while (itr.hasNext()) loop, the jsp output was : Done [ 0.1.2.3.e. ] , Location 4,5,6 was never reached.

[1] Why ? [2] How to turn "dataBytes = [B@14d3ba9 " into something readable or a file ? [3] How to turn "name = [Ljava.lang.String;@187f9d7" into the original string value ? [4] I'm using "(pair.getValue()).toString()", but why it's not a readable string ?

The client will send the HTTP request body only once.

Your code is however trying to read the request body twice. The first time by the getParameterMap() call:

java.util.Map<java.lang.String,java.lang.String[]> ParameterMap=request.getParameterMap();

and the second time by Apache Commons FileUpload (which will face an empty request):

try { items=upload.parseRequest(request); }

This isn't going to work.

Use either the standard Servlet API methods, or Apache Commons FileUpload exclusively.

See also:

use should use servelt 3.0 spec and annotate your servlet accordingly and then usin can user request.getParts() with all the multi-part data. Read about it.

Subquestion 1,3,4: if you cannot use the file upload feature added in Servlet 3.0 I think you're better off using Commons Fileupload , more or less the de facto standard for uploading files to servlets. It's robust, well tested and just works.

Subquestion 2: the Javadoc for ServletRequest's getParameterMap states:

Returns: an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.

Emphasis added: the values returned are arrays of Strings, not Strings. That's why you get the strange output value. Try

System.out.println( pair.getKey()+" = "+ pair.getValue()[0] );

But also consider using a logger in your servlets, it's better practice than dumping stuff in System.out

ps: use the code formatting feature that's probaby available in your IDE, your code is pretty hard to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM