Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for read data from file.
Previous Home Next

In this servlet program, a data can be read from file, put on hard drive of system.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <servlet>
      <servlet-name>ReadFileServlet</servlet-name>
      <servlet-class>r4r.Servlet.ReadFileServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>ReadFileServlet</servlet-name>
      <url-pattern>/ReadFileServlet</url-pattern>
  </servlet-mapping>
  <session-config>
        <session-timeout>
            30
        </session-timeout>
   </session-config>
</web-app>

Index.jsp

<%-- 
    Document   : index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
     <meta http-equiv="Content-Type" 
	   content="text/html; charset=UTF-8">
     <title>r4r.co.in-servlet</title>
    </head>
    <body>
     <form>
     <h1>Access Servlet by servlet's Name!</h1>
     <a href="ReadFileServlet">ReadFileServlet</a>
     </form>
    </body>
</html>

Servlet Program

/*
 * Save as a ReadFileServlet.java
 */
package r4r.Servlet;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import java.util.zip.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import Acme.JPM.Encoders.GifEncoder;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
/**
 *
 * @author R4R
 */
public class ReadFileServlet extends HttpServlet {

    private final static int MAX_SIZE = 1 * 1024 * 1024; //1 MB size

    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>" + getServletInfo() + "</title>");
  out.println("</head>");
  out.println("<body>");
  out.println("<h1>Servlet ReadFileServlet at "
           + request.getContextPath() + "</h1>");
  out.println("<form action=\"ReadFileServlet\" method=\
               "POST\" enctype=\"multipart/form-data\">");
  out.println("Select File:<input type=\"file\" name=\
                "myFile\" value=\"\" width=\"60\"/><br/>");
  out.println("<input type=\"submit\" value=\"Process Request\" />");
  out.println("<input type=\"reset\" value=\"Reset\"/>");
  out.println("</form>");
  out.println("</body>");
  out.println("</html>");
   } finally {
  out.close();
   }
    }

    @Override
    protected void doGet(HttpServletRequest request,
	 HttpServletResponse response)throws ServletException,IOException
	{
   processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request,
	 HttpServletResponse response)throws ServletException,IOException
	{
   response.setContentType("multipart/x-mixed-replace;boundary=End");
   ServletOutputStream out = response.getOutputStream();

   try {
  //check the request make from "multipart/form-data"
  boolean isMultipartContent = 
	   ServletFileUpload.isMultipartContent(request);
  if (isMultipartContent) {
 DiskFileItemFactory factory = new DiskFileItemFactory();
 ServletFileUpload fileUpload = new ServletFileUpload(factory);
 fileUpload.setSizeMax(MAX_SIZE);  //set size boundation

 //store the incomming request into list
 java.util.List<FileItem> items = fileUpload.parseRequest(request);
 Iterator<FileItem> it = items.listIterator();
 while (it.hasNext()) {
FileItem fileItem = it.next();

/*match incoming request Content type and 
invoke appropriate method for handel request*/

if (fileItem.getContentType().equals("text/plain")
	|| fileItem.getContentType().equals("application/octet-stream")
   || fileItem.getContentType().equals("application/msword")
	|| fileItem.getContentType().equals("text/html")) {
    handleTextFile(out, response, fileItem);
} else if (fileItem.getContentType().equals("application/x-zip-compressed")) 
	{
    handleCompressedFile(out, response, fileItem);
} else if (fileItem.getContentType().equals("image/gif") 
	|| fileItem.getContentType().equals("image/pjpeg")
   || fileItem.getContentType().equals("image/x-png")) {
    handleImageFile(out, response, fileItem);
} else if (fileItem.getContentType().equals("application/pdf")) {
    handlePdfFile(out, response, fileItem);
} else {
    response.sendError
	(HttpServletResponse.SC_BAD_REQUEST, "File formate not reconized");
}
 }
  } else {
 response.sendError
	 (HttpServletResponse.SC_BAD_REQUEST, "Request must be multipart");
  }
   } catch (Exception ex) {
  Logger.getLogger(ReadFileServlet.class.getName()).log(Level.SEVERE,
"An Exception is generated while processing request", ex);
   } finally {
  out.flush(); //free resource
  out.close();
   }
    }

    @Override
    public String getServletInfo() {
   return "r4r.co.in-ReadFileServlet";
    }

    /* -- Method capable to handle plane file -- */
    private void handleTextFile
(ServletOutputStream out, HttpServletResponse response, FileItem fileItem)
  throws FileNotFoundException, IOException {
   StringBuffer sb = new StringBuffer();
   FileReader fr = new FileReader(fileItem.getName()); //read incoming file
   BufferedReader br = new BufferedReader(fr, MAX_SIZE);
   int ch;
   while ((ch = br.read()) > -1) {
  sb.append((char) ch); //covert into character
   }
   //send response to client browser
   response.setContentType("text/html;charset=UTF-8");
   out.println(sb.toString());
    }

    /* -- Method capable to handle compressed file -- */
    private void handleCompressedFile
	(ServletOutputStream out,
		HttpServletResponse response, FileItem fileItem)
  throws FileNotFoundException, IOException {
   StringBuffer sb = new StringBuffer();
   File compressFile = new File(fileItem.getName());

   ZipInputStream zipInStream =
	   new ZipInputStream(new FileInputStream(compressFile));
   ZipEntry zipEntry = zipInStream.getNextEntry();
   if (zipEntry.getSize() == 0) {
  out.println
("Zip folder contain more than one file, .zip folder must be Extract first");
   } else {
  out.println("File name inside zip folder : <b>" 
	  + zipEntry.getName() + "</b><br>");
  InputStreamReader isr = new InputStreamReader(zipInStream);
  char[] cs = new char[MAX_SIZE]; //make a array
  while ((isr.read(cs, 0, cs.length)) > -1) {
 sb.append(cs);
  }
  //send response to client browser
  response.setContentType("text/html;charset=UTF-8");
  out.println(sb.toString());
   }
    }

    /* -- Method capable to handle image file -- */
    private void handleImageFile
	(ServletOutputStream out, HttpServletResponse response, FileItem fileItem)
  throws InterruptedException, IOException {
   Frame frame = new Frame(); //create a frame
   frame.addNotify();
   Image image = Toolkit.getDefaultToolkit().getImage(fileItem.getName());
   MediaTracker mt = new MediaTracker(frame);
   mt.addImage(image, 0);
   mt.waitForAll();

   //read valid image 
   int height = image.getHeight(frame);
   int width = image.getWidth(frame);
   if (height <= 0 || width <= 0) {
  response.sendError
	  (HttpServletResponse.SC_NO_CONTENT, "Not a valid image for read");
   }
   //image must be converted into gif format before send it on client browser
   response.setContentType("image/gif");
   GifEncoder encoder = new GifEncoder(image, out);
   encoder.encode();
    }

    /* -- Method capable to handle PDF file -- */
    private void handlePdfFile(ServletOutputStream out, 
		HttpServletResponse response, FileItem fileItem)
  throws FileNotFoundException, IOException {
   File pdfFile = new File(fileItem.getName()); //get the imcoming file
   BufferedInputStream bis =
	   new BufferedInputStream(new FileInputStream(pdfFile), MAX_SIZE);
   PdfReader reader = new PdfReader(bis); //read file 
   int n = reader.getNumberOfPages(); 
      //read number of page associated with file
   for (int i = 1; i <= n; i++) {
  String string = PdfTextExtractor.getTextFromPage(reader, i);
  //send response to client browser
  response.setContentType("text/plain");
  out.println(string);
   }
    }
}
Output of Program
Previous Home Next