HomeDocumentation > Reference > Samples > Java EE sample applications > fileupload-javaee6 - Annotation for servlets, filters,listeners and better file upload support in JavaEE 6
{scrollbar}

Application Overview

This sample demonstrates a better experience about file upload support in JavaEE 6, if a request is of type multipart/form-data and if the servlet handling the request is annotated using the @MultipartConfig, the HttpServletRequest can make available the various parts of the multipart request via getParts or getPart Method.

Also this sample introduces the annotation way to define servlets, filters and listeners for web application. A “metadata-complete” attribute which defines whether the web descriptor is complete, or whether the class files of the jar file should be examined for annotations and web fragments at deployment time. If the “metadata-complete” attribute in web application deployment descriptor web.xml is not specified or is set to “false”, the deploy tool will scan the class files of the application for annotations.

Application Content

fileupload-javaee6 application consists of following list of packages and classes.

org.apache.geronimo.samples.javaee6.fileupload

  • MessageFilter.java
  • OnlinePeopleList.java
  • showServlet.java

The list of web application files in the application is depicted in the following.

|- WEB_INF

+- web.xml

+- Geronimo-web.xml

|- index.html

|- header.html

|- selectFile.jsp

Application Implementation

web.xml defines the welcome-file of the web application. The “metadata-complete” attribute is set to false in this sample. So during deploying time, the deploy tool will scan all class files for annotations which may define servlets, filters or web listeners.

xmlweb.xml <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="false" id="fileupload-javaee6"> <description>fileupload-javaee6 Servlet Sample</description> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>

geronimo-web.xml describes information about the project (e.g. module's unique identification, any dependencies) inside the <sys:environment> tag. It is a good idea to give this module some sort of unique identification, so that it can later be referenced by some other deployable application. The path specified in the <context-root> tag will be the first segment of the URL used to access this web application. So to access this web application the url will be http://<hostname>:<port>/ fileupload-javaee6.

xmlgeronimo-web.xml <?xml version="1.0" encoding="UTF-8"?> web-app xmlns="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1" xmlns:naming="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:sys="http://geronimo.apache.org/xml/ns/deployment-1.2"> <sys:environment> <sys:moduleId> <sys:groupId>${pom.groupId}</sys:groupId> <sys:artifactId>fileupload-javaee6</sys:artifactId> <sys:version>${version}</sys:version> <sys:type>car</sys:type> </sys:moduleId> <sys:dependencies/> <sys:hidden-classes/> <sys:non-overridable-classes/> </sys:environment> <context-root>/fileupload-javaee6</context-root> </web-app>

selectFile.jsp provides a file upload widget, including a browsing button and a text box. The type of the request is “multipart/form-data”.The file you submitted will be in stream  .

htmlselectFile.jsp … <form action="showServlet" method="post" enctype="multipart/form-data"> … <input name="testFile" type="file"/> <br/> <input type="submit" value="Submit The File!" /> </form> …

OnlinePeopleListener.java uses annotation @WebListener() to define a web listener. It implements javax.servlet.ServletContextListener and javax.servlet.http.HttpSessionListener.

This web listener will detect current  online people. Each time a new session is created, onlineNumber increases.OnlineNumber decreases when the session is destroyed.

javaOnlinePeopleListener.java import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; @WebListener() public class OnlinePeopleListener implements ServletContextListener, HttpSessionListener { private int onlineNumber; private ServletContext context = null; public OnlinePeopleListener() { onlineNumber = 0; } public void sessionCreated(HttpSessionEvent se) { onlineNumber++; se.getSession().getServletContext().setAttribute("onLineNumber", new Integer(onlineNumber)); } public void sessionDestroyed(HttpSessionEvent se) { onlineNumber--; se.getSession().getServletContext().setAttribute("onLineNumber", new Integer(onlineNumber)); } }

MessageFilter.java implements javax.servlet.Filter and uses @WebFilter to define a filter in web application. The annotation also contains metadata about the filter being declared. The name of the filter is “MessageFilter”, the same as class name. The urlPatterns “/showServlet” attribute indicates all URLs to be filtered by this filter.Use getPart method to get access to each uploaded file.

MessageFilter.java will filter files larger than 10kb. As with the qualified files, part provides access to the headers, content type related with it and also the content via the getInputStream method.

javaMessageFilter.java @WebFilter(filterName = "MessageFilter", urlPatterns = { "/showServlet" }) public class MessageFilter implements Filter { private FilterConfig filterConfig; public MessageFilter() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String message = ""; HttpServletRequest httpServletRequest = null; if (request instanceof HttpServletRequest) { httpServletRequest = (HttpServletRequest) request; message += "<p>" + "Http Servlet Request content type: "+ httpServletRequest.getContentType() + "</p><br>"; } Collection<Part> parts = httpServletRequest.getParts(); if (!parts.isEmpty()) { int i = 0; for (Part apart : parts) { message += "<p>"+ (++i) + ". Name=" + apart.getName()+ ";ContentType=" + apart.getContentType() + ";Size="+ apart.getSize() + "</p><br>"; } } else { message += "<p><b>HttpServletRequest.getParts() returns an empty collection!</b></p><br>"; } Throwable problem = null; try { Part p = ((HttpServletRequest) request).getPart("testFile"); if (null != p) { String part = p.toString(); String pname = p.getName(); long size = p.getSize(); String contentType = p.getContentType(); if (size > 10000) { message += "The file size is "+ size+ "b, it's filterd because the file size is limited to 10 kb"; } else { message += "<font color=green><b>Part:</b> </font>"+ part + "<br><font color=green><b>Part Name:</b> </font>"+ pname + "<br><font color=green><b>Size:</b> </font>"+ size + "<br><font color=green><b>ContentType:</b> </font>"+ contentType + "<br><font color=green><b>HeadNames:</b> </font>"; for (String name : p.getHeaderNames()) { message += name + ";"; } java.io.InputStreamReader in = new java.io.InputStreamReader( p.getInputStream()); String content = ""; int c = in.read(); while (c != -1) { if (c == '\n') { content += "<br>"; } content += (char) c; c = in.read(); } if (content.equals("")) { message += "<br> Sorry, this is not a plain text, so we can not display it."; } else { message += "<br><font color=green><b>The text file content is:</b></font><br>"+ content; message += "<hr>"; } } } else { message += "<p><b>HttpServletRequest.getPart(String name) returns null!</b></p><br>"; } request.setAttribute("message", message); chain.doFilter(request, response); } catch (Throwable t) { problem = t; t.printStackTrace(); } } ... }

showServlet.java implements javax.servlet.http.HttpServlet and uses @WebServlet annotation to define a servlet in the web application.

This servlet displays the detail information of the file as followed:

javashowServlet.java @WebServlet(name = "showServlet", urlPatterns = {"/showServlet"}) public class showServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>File Upload System</title>"); out.println("</head>"); out.println("<body>"); out.println("<h2><font color=\"green\">A listener is dectecting online person number.</font></h2>"); out.println("<h3>Currently,there are " + "<font color=\"green\">" + getServletContext().getAttribute("onLineNumber") + "</font> people visiting this file upload system\!<br/><hr></h3>"); String message = request.getAttribute("message").toString(); if (message.indexOf("returns null\!") < 0) { out.println("<h2><font color=\"green\">Attributes and content of the file:</font></h2>"); } out.println(message + "<br/>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } ... }

Get Source Code

Please reference Samples General Information for information on obtaining and building the source for this and other samples.

Build the web application

Once all the sources get checked out the next step is to build fileupload-javaee6 sample.It requires Maven 2 for building the binaries.

From the < fileupload-javaee6_home> directory run the following command.

mvn clean install

This process will take a couple of minutes. The binaries will be generated in the corresponding target directory .

Deploy the web application

Deploying sample application is pretty straight forward as we are going to use the Geronimo Console.

  1. Scroll down to Deploy New from the Console Navigation panel.
  2. Load fileupload-javaee6-war-3.0-M1.war from fileupload-javaee6-war\target folder in to the Archive input box.
  3. Press Install button to deploy application in the server.

Test the web application

The app is visible at http://localhost:8080/fileupload-javaee6.

Select a file to be uploaded,note that the file should be less than 10kb,otherwise it will be filtered.

It displays current online people number and detail information of the file you submitted.