0

Facing problem in getparameter(filepath). It's sending the null value for Chrome and Firefox but working fine for IE. I found some links indicating that getparameter is not working fine with servlet 2.5 but my problem is still not resolved. If you have an alternative or suggestion you are most welcome for giving a reply.

Please see servlet and class file:

upload.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
            pageEncoding="ISO-8859-1"%>
        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            "http://www.w3.org/TR/html4/loose.dtd">
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>File Upload</title>
        </head>
        <body>
        <center>
            <h3>File Upload:</h3>
              Select a file to upload: 
              <form action = "ImportExcelServlet" method="post">

                 <input type = "file" name="file_path" size = "50" />
                 <br /></br>
                 <input type = "submit" value = "Upload File" />
              </form>
        </center>
            <form method="post" action="ImportExcelServlet">
                 <input type="submit" value="Import" />
            </form>
        </body>
        </html>

DataGrid.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
#customers {
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

#customers td, #customers th {
    border: 1px solid #ddd;
    padding: 8px;
}

#customers tr:nth-child(even){background-color: #f2f2f2;}

#customers tr:hover {background-color: #ddd;}

#customers th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: #4CAF50;
    color: white;
}
</style>
</head>
<body>
<%  
// retrieve your list from the request, with casting 
//ArrayList<Category> list = (ArrayList<Category>) request.getAttribute("servletName");
Object[][] excelData=(Object[][])request.getAttribute("data");%>
<table id="customers">
<%for(int i=0;i<excelData.length;i++){%><tr><%for(int j=0;j<excelData[0].length;j++){ if(i==0){ %>
<th>
<%=excelData[i][j]%>
</th>
<%}else{%>
<td>
<%=excelData[i][j]%>
</td>
<%}%>
<%}%>
</tr>
<%}%>
</table>
<iframe id="txtArea1" style="display:none"></iframe>
<script>
function fnExcelReport()
{
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById('customers'); // id of table

    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Grid.xlsx");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}
</script>
<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
</body>
</html>

ImportExcelSevlet.java

package test;

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;


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

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImportExcelServlet() {
        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

        //doGet(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub

        Object[][] excelData=null;

        String filepath=request.getParameter("file_path");
        excelData=ReadWriteExcel.readXLSXFile(filepath);
        request.setAttribute("data",excelData); 
        getServletConfig().getServletContext().getRequestDispatcher("/DataGrid.jsp").forward(request,response);
        response.getWriter().append("Served at: ").append(request.getContextPath());

    }

}

ReadWriteExcel.java

package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class  ReadWriteExcel {
public static Object[][] readXLSXFile(String filepath) throws IOException
{
    Object[][] excelData = null;
    try
    {
        FileInputStream file = new FileInputStream(new File(filepath));

        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);
        int x=sheet.getPhysicalNumberOfRows();
        int y=sheet.getRow(0).getPhysicalNumberOfCells();
        excelData=new Object[x][y];

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        int i=0;
        while (rowIterator.hasNext()) 
        {
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();
            int j=0;
            while (cellIterator.hasNext()) 
            {

                Cell cell = cellIterator.next();
                //Check the cell type and format accordingly
                switch (cell.getCellType()) 
                {
                    case Cell.CELL_TYPE_NUMERIC:
                        //System.out.print(cell.getNumericCellValue() + "\t");
                        excelData[i][j]=cell.getNumericCellValue();
                        break;
                    case Cell.CELL_TYPE_STRING:
                        //System.out.print(cell.getStringCellValue() + "\t");
                        excelData[i][j]=cell.getStringCellValue();
                        break;
                }
                j++;
            }
            i++;
            System.out.println("");
        }
        file.close();
}
rlandster
  • 7,294
  • 14
  • 58
  • 96
  • as per the code i understand that you want to read the uploaded file in your servlet and do further processing on the data, you should upload a file using `method = "post" enctype = "multipart/form-data">` not with only `method = "post"` – Rishal Apr 10 '18 at 09:53
  • but as per your servlet code first few lines you are more interested in file path only `String filepath=request.getParameter("file_path");` what you will do with it , you need the content not the file path. – Rishal Apr 10 '18 at 09:55
  • actually i need the path of the file for reading excel, and in the code file_path i get, which is uploaded by user and that path i am sending in class file using servlet – Gaurav Pandit Apr 10 '18 at 10:01
  • user will upload xls file only ryt? why you want to read the path, you have to read the data uploaded by the user not his/her local machine path , if you are designing any web application – Rishal Apr 10 '18 at 10:02
  • ya right....so i have to store that file on server and then fetch the data from there,but what if i want to read the path from my local machine? It's just a query and thanks for suggestion... – Gaurav Pandit Apr 10 '18 at 10:13
  • you dont have to store anything that will be available in the request/response data when user submit the form..refer tutorials on file upload using servlets and jsp – Rishal Apr 10 '18 at 14:36

0 Answers0