Here is my servlet class
package com.zaggle;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FirstServlet
*/
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public FirstServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String[] data;String val=null,name;
name=request.getParameter("excelsheet");
System.out.println(name);
response.setContentType("text/html");
UploadExcel ex= new UploadExcel();
data=ex.procedure(name);
System.out.println(name);
request.setAttribute("val", data);
System.out.println(val);
String destination="/NewFile1.jsp";
RequestDispatcher rd=getServletContext().getRequestDispatcher(destination);
//doGet(request, response);
rd.forward(request, response);
}
}
Here is my normal java class which I am using in servlet class
package com.zaggle;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.RestoreAction;
import org.apache.poi.hssf.record.formula.functions.Goto;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class UploadExcel {
public String[] procedure(String filename) {
// Scanner scanner = new Scanner(System.in);
//System.out.println("Please enter a filename with extention to upload");
String fileName = "C:\\"+filename;//+scanner.nextLine();
String[] dataHolder = ReadCSV(fileName);
// printCellDataToConsole(dataHolder);
return dataHolder;
}
public static void printCellDataToConsole(Vector dataHolder) {
// TODO Auto-generated method stub
for(int i=0;i<dataHolder.size();i++)
{
Vector column=(Vector)dataHolder.elementAt(i);
for (int j = 0; j < column.size(); j++) {
HSSFCell myCell = (HSSFCell) column.elementAt(j);
String stringCellValue = myCell.toString();
System.out.print(stringCellValue + "\t");
}
System.out.println();
}
}
public static String[] ReadCSV(String fileName) {
// TODO Auto-generated method stub
Vector cellVectorHolder = new Vector();
String[] col = null;
try {
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector column = new Vector();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
column.addElement(myCell);
}
col=column.toString().split(" ");
cellVectorHolder.addElement(column);
}
} catch(IOException ie)
{
System.err.println("Please enter a valid input");
}
catch (Exception e) {
e.printStackTrace();
}
//return cellVectorHolder;
return col;
}
}
When i run I am getting the error like this
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoClassDefFoundError: org/apache/poi/poifs/filesystem/POIFSFileSystem
com.zaggle.UploadExcel.ReadCSV(UploadExcel.java:52)
com.zaggle.UploadExcel.procedure(UploadExcel.java:24)
com.zaggle.FirstServlet.doPost(FirstServlet.java:42)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Why am I getting this error. Can anyone help me?
It looks like you've forgotten to include the POI library on the CLASSPATH (e.g. It's not referenced by your web app). You can include this lib under WEB-INF/lib (in your WAR archive or in the exploded directory format) or it can sit elsewhere in your app server/web server CLASSPATH.
you are getting the exception in this line
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
You are trying to use a library that is not included in your project.
Make sure that import org.apache.poi library in in the web-inf/lib directory
Your POI jars are not in the classpath.You can include this lib under WEB-INF/lib..
Also check could be that your version of jars is different than those expected.
Make sure apache-poi.jar under WEB-INF/lib.
Optional : Based on the your web server or application server, put apache-poi.jar into server-home/lib(depend on server). It is not best solution.
Note
Now, you are developing web application, don't use uploaded file with specific path (eg: C:\....). If so, the program will find out the upload file on local machine Web Server is running. First you have to upload file as byte[] or InputStream or use other third party lib. After that, you have to change HSSFWorkbook.
Related
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SSEServlet
*/
#WebServlet("/SSE")
public class SSE extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
PrintWriter printwriter = response.getWriter();
File file= new File("/home/user/Documents/new.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
long length = randomAccessFile.length();
String temp;
int foundLine = 0;
while (length > 0 && foundLine < 10) {
randomAccessFile.seek(length--);
if (randomAccessFile.read() == 10) {
foundLine++;
}
}
while(true)
while((temp = randomAccessFile.readLine()) != null)
{
printwriter.println(temp);
response.flushBuffer();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
In my code I am trying to get the last 10 lines and also the one that is written to file dynamically after tht 10 lines but while running my pgm am only getting the last 10 lines and not the ones written after that....in short am not able to watch the file dynamically is there any solution for this
There is a servlet that accepts files from the client and stores them in a folder.
It is now necessary to list the files from this folder and create links to them (that is, click on the file name and it's downloaded from you).
Now just output a list of files in the form of text. How to create links to them? I read that for this it is enough to expose the headers, but how this is done and has not been found.
Sample Code:
public class FileListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileListServlet() {
super();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String param = "/dirs";
PrintWriter w = res.getWriter();
res.setContentType("text/html");
String root="/dirs";
java.io.File dir = new java.io.File(root);
File[] fileList = dir.listFiles();
w.println("<H2><FONT COLOR=TEAL>" + "Total number of files in the choosen directory - " +
fileList.length + "</FONT></H2>");
w.println("<H3><FONT COLOR=PURPLE>" +
"Directory path - " + param + "</FONT></H3><HR>");
w.println("<TABLE BORDER=0 CELLSPACING=5>");
for(int i = 0; i < fileList.length; i++)
printName(fileList[i], w);
w.println("</TABLE><HR>");
}
private void printName(File name, PrintWriter output)
{
String type = name.isDirectory()
? " (Directory)" : " (File)";
output.println("<TR><TD>" + type + "</TD><TD><FONT COLOR=BLUE>"
+ name.getName() + "</FONT></TD></TR>");
}
public String getServletInfo()
{
return "This servlet shows a content of a directory" +
"mentioned in dirToShow parameter or property.";
}
}
I solved my problem. In case someone needs it or someone knows a more beautiful way.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
response.setContentType("text/html");
File currentFolder = new File(".");
File workingFolder = new File(currentFolder, "Sorted files");
String root = workingFolder.getAbsolutePath();
java.io.File dir = new java.io.File(root);
File[] fileList = dir.listFiles();
printWriter.println("<H2><FONT COLOR=TEAL>" + "Total number of files in the choosen directory - " +
fileList.length + "</FONT></H2>");
printWriter.println("<H3><FONT COLOR=PURPLE>" +
"Directory path - " + root + "</FONT></H3><HR>");
printWriter.println("<TABLE BORDER=0 CELLSPACING=5>");
for(int i = 0; i < fileList.length; i++) {
printName(fileList[i], printWriter);
}
printWriter.println("</TABLE><HR>");
}
private void printName(File file, PrintWriter output)
{
System.out.println(file.getName());
output.println("<tr><td><a href=\"https://Upload/DownloadServlet?name="
+file.getName()+"\">" + file.getName() + "</a></td></tr>" );
}
public String getServletInfo()
{
return "This servlet shows a content of a directory" +
"mentioned in dirToShow parameter or property.";
}
}
And DownloadServlet
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class DownloadServlet
*/
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DownloadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
String fileType = "multipart/form-data";
response.setContentType(fileType);
response.setHeader("Content-disposition", "attachment; filename=" + name);
File currentFolder = new File(".");
File workingFolder = new File(currentFolder, "Sorted files");
String root = workingFolder.getAbsolutePath();
File file = new File(root + File.separator + name);
OutputStream output = response.getOutputStream();
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[4096];
int lenght;
while( ( lenght = input.read(buffer) ) > 0 ) {
output.write(buffer, 0, lenght);
}
input.close();
output.flush();
output.close();
response.getOutputStream().flush();
response.getOutputStream().close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
My servlet lets user upload a file, I've created a button to view the uploaded file.
now, on click of that button I want the uploaded file to open. How do I do this on the JSP side or servlet.java side?
it is located in WEB-INF/Uploads/my.txt folder.
=====================================EDIT=========================================
Based on answers below, I've modified my code and I'm pasting the same here for more answers,
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ServletContext context = getServletContext();
String path = context.getRealPath("/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/Uploads/Config.txt");
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
String firstline = br.readLine();
System.out.println(firstline);
}
PS: This is not working, still looking for answers.
Thank You!
You can do this by using the ServletContext:
ServletContext#getResourceAsStream()
As far as I know the classLoader can only access WEB-INF/classes and WEB-INF/lib but not WEB-INF/Uploads. Try to put the file in the classes sub-folder.
try to do the following :
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/WEB-INF/Uploads/my.txt");
then read the URL content like the following :
BufferedReader br = new BufferedReader(new InputStreamReader(
is));
int value=0;
// reads to the end of the stream
while((value = br.read()) != -1)
{
// converts int to character
char c = (char)value;
// prints character
System.out.println(c);
}
and please give me some feedback
Hope That Helps .
if it is a image file then u can do following using jstl tag
<img src="<c:url value='Uploads/yourImg.png' />">
Assuming you web-inf file in the src folder you can try folloing
File f = new File("src/web-inf/Uploads/YourFile.txt");
If the file name is not fixed then use <form> in jsp to get the file name from the jsp page
In Java class: If you need to direct access then you have to extends HttpServlet like
public class FileReader extends HttpServlet {
....
....
....
public void readAFile(){
ServletContext servletContext=super.getServletContext();
InputStream initFileStream = servletContext.getResourceAsStream("/WEB-INF/<path>");
//TODO : according to your need
}
{
Tested Servlet
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class STest
*/
#WebServlet("/STest")
public class STest extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public STest() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
process();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
process();
}
private void process() throws IOException {
ServletContext servletContext=super.getServletContext();
InputStream initFileStream = servletContext.getResourceAsStream("/WEB-INF/test.txt");
BufferedReader reader=new BufferedReader(new InputStreamReader(initFileStream));
StringBuffer stringAll=new StringBuffer();
while(reader.ready()){
stringAll.append(reader.readLine());
}
System.out.println(stringAll);
}
}
In your Servlet class, you can use the following code :
ServletContext context = getServletContext();
String path = context.getRealPath("/WEB-INF/Uploads/my.txt");
Then the path should be correct. And then you can use a normal FileReader :
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
String firstline = br.readLine();
System.out.println(firstline);
...
I am trying to upload a file to web server and read the same. file uploading is working and the file is uploaded but when i call some methods to manipulate saved file the method is not getting called.
in the following file i call readFile method from post method.
I am using tomcat 7.0. Please save me from this. the code is :
package org.slingemp.fileupload;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slingemp.bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Servlet implementation class Fileupload
*/
#WebServlet("/Fileupload")
public class Fileupload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Fileupload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("file upload started....Antony");
// TODO Auto-generated method stub
List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
// Change upload with your directory
HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(
new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(Fileupload.class.getName()).log(
Level.SEVERE, null, ex);
// Change above line replace FileUploadExample with your
// file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
}
/*
* If you want to pass some other data from JSP page.
* You can access then in this way. For each field you
* have do create if like below. if
* (fileItemTemp.getFieldName
* ().equals("Name of other field like:Firstname")) {
* String Firstname = fileItemTemp.getString(); }
*/
} else {
fileItem = fileItemTemp;
}
}
if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;
// If you want to limit the file size. Here 30MB file size
// is allowed you can change it
//if (filesize > 30.0) {
// Pass error message in session.
//setNotification _sN = new setNotification();
//_sN.setError("File size can't be more than 30MB");
//session.setAttribute("error", _sN);
//} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../accesscarddata/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"),fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("accesscardDatafileNname", _fileName);
session.setAttribute("error", _sN);
}
//}
}
//SELECT * FROM leave_application WHERE from_date >= '2004-01-01' AND to_date <'2004-01-30' and emp_id=128
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("before calling readFile");
readFile(request,response);
System.out.println("after calling readFile");
response.sendRedirect("index.jsp");
}
protected void readFile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("readFile is called..");
Map employeeMap = null;
String fileName = "",employeeAttendanceFilePath="";
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
HttpSession session = request.getSession(true);
if(session.getAttribute("accesscardDatafileNname") != null)
fileName = (String) session.getAttribute("accesscardDatafileNname");
employeeAttendanceFilePath = _uploadDir+fileName;
System.out.println("File Path : "+employeeAttendanceFilePath);
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(employeeAttendanceFilePath);
// Create an excel workbook from the file system.
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);// gets the first sheet on workbook
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
//count=count+1;
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
session.setAttribute("sheetData", sheetData);
processEmployeeAttendance(request,response);
System.out.println("employeeMap : "+employeeMap);
if(session.getAttribute("employeeMap")!=null)
employeeMap = (LinkedHashMap) session.getAttribute("sheetData");
Iterator<Map.Entry> entries = employeeMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
protected void processEmployeeAttendance(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("processEmployeeAttendance is called...");
String tempEmpid="",strdepartment="";
int j=1;
List sheetData =null;
HttpSession session = request.getSession(true);
if(session.getAttribute("sheetData")!=null)
sheetData = (ArrayList) session.getAttribute("sheetData");
Map employeeMap = new LinkedHashMap();
Map tempEmployeeMap = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
HSSFCell employeeid = (HSSFCell) list.get(0);
HSSFCell department = (HSSFCell) list.get(3);
HSSFCell date = (HSSFCell) list.get(5);
strdepartment = department.getRichStringCellValue().getString();
if(!tempEmpid.equals("")){
if(tempEmpid.equals(employeeid.getRichStringCellValue().getString()) && !(employeeid.getRichStringCellValue().getString().equals("EmpID") || date.getRichStringCellValue().getString().equals("Date") || department.getRichStringCellValue().getString().equals("Department"))){
if(!(strdepartment.equals("Temporary Card") || strdepartment.equals("Contractor"))){
employeeMap.put(employeeid.getRichStringCellValue().getString()+"_"+j,date.getRichStringCellValue().getString());
// System.out.println("j value : "+j+":"+employeeid.getRichStringCellValue().getString()+"_"+j+","+date.getRichStringCellValue().getString());
j++;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
j=0;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
}
// System.out.println("");
}
session.setAttribute("employeeMap", employeeMap);
}
}
I wanted to put it as a comment, but somehow I am unable to comment.
My suggestion would be to debug the code using your IDE. Put breakpoints at relevant positions and see where its going.
how to update file to tomcat 5.5.
i tried with the follwoing code but the code does not run with tomcat5.5 and shows
Tomcat version 5.5 only supports J2EE 1.2, 1.3, and 1.4 Web module
the code is:
package org.slingemp.fileupload;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slingemp.bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Servlet implementation class Fileupload
*/
#WebServlet("/Fileupload")
public class Fileupload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Fileupload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("file upload started....");
// TODO Auto-generated method stub
List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
System.out.println("_uploadDir :"+_uploadDir);
// Change upload with your directory
HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(
new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(Fileupload.class.getName()).log(Level.SEVERE, null, ex);
// Change above line replace FileUploadExample with your
// file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
System.out.println("optionalFileName : "+optionalFileName);
}
/*
* If you want to pass some other data from JSP page.
* You can access then in this way. For each field you
* have do create if like below. if
* (fileItemTemp.getFieldName
* ().equals("Name of other field like:Firstname")) {
* String Firstname = fileItemTemp.getString(); }
*/
} else {
fileItem = fileItemTemp;
}
}
if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;
// If you want to limit the file size. Here 30MB file size
// is allowed you can change it
//if (filesize > 30.0) {
// Pass error message in session.
//setNotification _sN = new setNotification();
//_sN.setError("File size can't be more than 30MB");
//session.setAttribute("error", _sN);
//} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../accesscarddata/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"),fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("accesscardDatafileNname", _fileName);
session.setAttribute("error", _sN);
}
//}
}
//SELECT * FROM leave_application WHERE from_date >= '2004-01-01' AND to_date <'2004-01-30' and emp_id=128
}
} catch (Exception e) {
e.printStackTrace();
} finally{
}
System.out.println("before calling readFile");
readFile(request,response);
System.out.println("after calling readFile");
response.sendRedirect("index.jsp");
}
protected void readFile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("readFile is called..");
Map employeeMap = null;
String fileName = "",employeeAttendanceFilePath="";
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
HttpSession session = request.getSession(true);
if(session.getAttribute("accesscardDatafileNname") != null)
fileName = (String) session.getAttribute("accesscardDatafileNname");
employeeAttendanceFilePath = _uploadDir+fileName;
System.out.println("File Path : "+employeeAttendanceFilePath);
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(employeeAttendanceFilePath);
// Create an excel workbook from the file system.
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);// gets the first sheet on workbook
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
//count=count+1;
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
session.setAttribute("sheetData", sheetData);
processEmployeeAttendance(request,response);
System.out.println("employeeMap : "+employeeMap);
if(session.getAttribute("employeeMap")!=null)
employeeMap = (LinkedHashMap) session.getAttribute("sheetData");
Iterator<Map.Entry> entries = employeeMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
protected void processEmployeeAttendance(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("processEmployeeAttendance is called...");
String tempEmpid="",strdepartment="";
int j=1;
List sheetData =null;
HttpSession session = request.getSession(true);
if(session.getAttribute("sheetData")!=null)
sheetData = (ArrayList) session.getAttribute("sheetData");
Map employeeMap = new LinkedHashMap();
Map tempEmployeeMap = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
HSSFCell employeeid = (HSSFCell) list.get(0);
HSSFCell department = (HSSFCell) list.get(3);
HSSFCell date = (HSSFCell) list.get(5);
strdepartment = department.getRichStringCellValue().getString();
if(!tempEmpid.equals("")){
if(tempEmpid.equals(employeeid.getRichStringCellValue().getString()) && !(employeeid.getRichStringCellValue().getString().equals("EmpID") || date.getRichStringCellValue().getString().equals("Date") || department.getRichStringCellValue().getString().equals("Department"))){
if(!(strdepartment.equals("Temporary Card") || strdepartment.equals("Contractor"))){
employeeMap.put(employeeid.getRichStringCellValue().getString()+"_"+j,date.getRichStringCellValue().getString());
// System.out.println("j value : "+j+":"+employeeid.getRichStringCellValue().getString()+"_"+j+","+date.getRichStringCellValue().getString());
j++;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
j=0;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
}
// System.out.println("");
}
session.setAttribute("employeeMap", employeeMap);
}
}
when i run this code in tomcat 7 it says this error when uploading the file :
java.io.FileNotFoundException: D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\Fileupload\accesscarddata\C:\Users\anthony.savarimut\Desktop\Map Iterate\SampleData.xls (The filename, directory name, or volume label syntax is incorrect)
Please save me form this.
You are running the tomcat in workspace. Please change location to where tomcat installed. I assuming that your are running with eclipse, click on server and set the location.