Showing posts with label servlet3. Show all posts
Showing posts with label servlet3. Show all posts

Uploading file to particular directory

You can configure the File Upload support in servlet specification 3.0 so that it uploads files to particular directory on your server.


package com.webspherenotes.j2ee6.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
* Servlet implementation class HelloFileUploadAnnotationServlet
*/
@WebServlet("/hellofileupload")
@MultipartConfig(location="c:/temp/upload")
public class HelloFileUploadAnnotationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Entering HelloFileUploadAnnotationServlet.doPost()");
response.setContentType("text/html");
response.getWriter().println("Hello from FileUploadServlet");
Collection fileParts = request.getParts();
Iterator filePartIt = fileParts.iterator();
while(filePartIt.hasNext()){
Part filePart = filePartIt.next();
System.out.println("File Name " + filePart.getName());
System.out.println("File Size " + filePart.getSize());

System.out.println("File Content ");
BufferedReader fileReader =
new BufferedReader(new InputStreamReader(filePart.getInputStream()));
String line = null;
while(( line = fileReader.readLine()) != null){
System.out.println(line);
}
}
System.out.println("Exiting HelloFileUploadAnnotationServlet.doPost()");
}

}


In my case i am setting value of location to c:/temp/upload and then i tried uploading couple of files and now i can see that every time i upload a file a .tmp file gets created in c:/temp/upload

Setting limit on filesize to be uploaded

When your handling the file upload you might want to set limit on the file size that can be uploaded you can do that by setting value of maxFileSize. The value of maxFileSize is in bytes,

@WebServlet("/hellofileupload")
@MultipartConfig(maxFileSize=1000 )
public class HelloFileUploadAnnotationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Entering HelloFileUploadAnnotationServlet.doPost()");
response.setContentType("text/html");
response.getWriter().println("Hello from FileUploadServlet");
Collection fileParts = request.getParts();
Iterator filePartIt = fileParts.iterator();
while(filePartIt.hasNext()){
Part filePart = filePartIt.next();
System.out.println("File Name " + filePart.getName());
System.out.println("File Size " + filePart.getSize());

System.out.println("File Content ");
BufferedReader fileReader =
new BufferedReader(new InputStreamReader(filePart.getInputStream()));
String line = null;
while(( line = fileReader.readLine()) != null){
System.out.println(line);
}
}
System.out.println("Exiting HelloFileUploadAnnotationServlet.doPost()");
}

}


So in my sample application if i try to upload a file bigger than 1000 bytes it will throw a java.lang.IllegalStateException exception like this

[12/19/10 20:24:23:765 PST] 00000019 servlet E com.ibm.ws.webcontainer.servlet.ServletWrapper service
SRVE0068E: An exception was thrown by one of the service methods of the servlet [com.webspherenotes.j2ee6.servlet.HelloFileUploadAnnotationServlet]
in application [HelloServletAnnotationEAR]. Exception created : [java.lang.IllegalStateException:
SRVE8021E: The file being uploaded is too large.
at com.ibm.ws.webcontainer.srt.SRTServletRequest.parseMultipart(SRTServletRequest.java:3504)
at com.ibm.ws.webcontainer.srt.SRTServletRequest.prepareMultipart(SRTServletRequest.java:3413)
at com.ibm.ws.webcontainer.srt.SRTServletRequest.getParts(SRTServletRequest.java:3394)
at com.webspherenotes.j2ee6.servlet.HelloFileUploadAnnotationServlet.doPost(HelloFileUploadAnnotationServlet.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1133)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:708)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:435)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1012)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3598)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:303)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:950)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1624)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:197)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:445)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:504)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:301)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:275)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1618)
]

Handling file upload in Servlet 3.0

Ability to handle file upload is one of the common requirements for web application. Before Servlet Specification 3.0 if you wanted to handle file upload you would have to use external library such as Apache Commons File upload to handle the file upload.

But starting from Servlet Specification 3.0 you dont need external library instead there is a native support. I wanted to try this so i followed these steps


  1. First i did create a index.jsp file like this

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%@page
    language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <html>
    <head>
    <title>index</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    </head>
    <body>
    <form action="hellofileupload" method="post" enctype="multipart/form-data" >
    <table>
    <tr>
    <td>File</td>
    <td><input type="file" name="samplefile" /></td>
    </tr>
    <tr><td><input type="submit"></td></tr>
    </table>
    </form>

    </body>
    </html>


    If you want to upload a file to the server you will have to set form encoding type to multipart/form-data. The index.jsp will submit form to the hellofileupload url and thats where our HelloFileUploadAnnotationServlet will come in

  2. Next create a HelloFileUploadAnnotationServlet like this

    package com.webspherenotes.j2ee6.servlet;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Collection;
    import java.util.Iterator;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;

    /**
    * Servlet implementation class HelloFileUploadAnnotationServlet
    */
    @WebServlet("/hellofileupload")
    @MultipartConfig
    public class HelloFileUploadAnnotationServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    System.out.println("Entering HelloFileUploadAnnotationServlet.doPost()");
    response.setContentType("text/html");
    response.getWriter().println("Hello from FileUploadServlet");
    Collection fileParts = request.getParts();
    Iterator filePartIt = fileParts.iterator();
    while(filePartIt.hasNext()){
    Part filePart = filePartIt.next();
    System.out.println("File Name " + filePart.getName());
    System.out.println("File Size " + filePart.getSize());

    System.out.println("File Content ");
    BufferedReader fileReader =
    new BufferedReader(new InputStreamReader(filePart.getInputStream()));
    String line = null;
    while(( line = fileReader.readLine()) != null){
    System.out.println(line);
    }
    }

    System.out.println("Exiting HelloFileUploadAnnotationServlet.doPost()");
    }
    }

    In order to use the file upload first you will have to mark the Servlet using MultipartConfig annotation, indicating that instances of the Servlet expect requests that conform to the multipart/form-data MIME type.
    Then inside the doPost() method you can use the method of HttpServletRequest to get access to the uploaded file.

Whats new in Servlet Specification 3.0

The Servlet Specification 3.0 has lot of new features such as


  1. Annotations

  2. Web Fragments

  3. Defining new servlet/filter using ServletContext API

  4. Async Servlet support



I want to try some of the features and i am planning to blog about them