0

I am tring to retrieve the selected value from select option through servlets using the following code.

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        // set location for saving uploaded file
        UploadBean upb = new UploadBean();

        upb.setFolderstore(UPLOAD_DIR);
        upb.setFilesizelimit(1073741824);
        upb.setOverwrite(true);

        MultipartFormDataRequest nreq = new MultipartFormDataRequest(request);

        // completed file uploading
        upb.store(nreq);

        Hashtable<?, ?> ht = nreq.getFiles();// gives the uploaded file
        Enumeration<?> e = ht.elements();
        while (e.hasMoreElements()) {
            upfile = (UploadFile) e.nextElement();
            upfile1 = (UploadFile) e.nextElement();
            uploadFilePath = UPLOAD_DIR + File.separator;
            File fileSaveDir = new File(uploadFilePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdirs();
            }
            file = UPLOAD_DIR + File.separator + upfile.getFileName();
            file1 = UPLOAD_DIR + File.separator + upfile1.getFileName();
            filePath = new File(file).getAbsolutePath();
            filePath1 = new File(file1).getAbsolutePath();
        }
        doGet(request, response);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String val = getValue(request.getPart("voucherType"));
    System.out.println(val);
    Connection con = new DBConnection().getConn();
    File file1 = new File(filePath);
    File file = new File(filePath1);
    uploadMasterFile(file, con);
    uploadRawFile(file1, con);

}
private String getValue(Part voucherTypes) {
    StringBuilder value = new StringBuilder();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(voucherTypes.getInputStream(), "UTF-8"));
        char[] buffer = new char[1024];
        int length;
        while(-1 != (length = reader.read(buffer))) {
            value.append(buffer, 0, length);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return value.toString();
}

My html code is for the select option is

             <form method="post" action="fileUpload" enctype="multipart/form-data">
        <table border="0">
            <tr>
                <td>Master data:</td>
                <td><input type="file" name="master" size="50" /></td>
            </tr>
            <tr>
                <td>Input data:</td>
                <td><input type="file" name="raw" size="50" /></td>
            </tr>
            <tr>
                <td>Voucher type:</td>
                <td><select name="voucherType" onchange="java_script_:show(this.options[this.selectedIndex].value)">
                        <option value="checklistEmp">ChecklistForEmployees</option>
                        <option value="checklistDoc">ChecklistForDoctors</option>
                        <option value="checklistHos">ChecklistForHospitals</option>
                        <option value="medOrg">MedicalPaymentVoucherOriginal</option>
                        <option value="medDup">MedicalPaymentVoucherDuplicate</option>
                        <option value="ledgEmp">LedgerForEmployees</option>
                        <option value="ledgDoc">LedgerForDoctors</option>
                        <option value="ledgHos">LedgerForHosipitals</option>
                        <option value="ExpAll">ExpensesForAllEmployees</option>
                        <option value="Expgrt15">ExpensesForAllEmployeesGrt15k</option>
                </select></td>
            </tr>
            <tr>
                <td>
                    <div id="optionyes" style="visibility: hidden">
                        From date: <input type="text" id="txtFrom" /><br><br>To date: <input type="text" id="txtTo" />
                    </div>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Submit">
                </td>
            </tr>
        </table>
    </form>

I am getting null value after selecting the option, i have seen many solutions across here. But does not find the solution.

java.lang.NullPointerException
at org.stc.medical.fileupload.FileUploadServlet.getValue(FileUploadServlet.java:87)
at org.stc.medical.fileupload.FileUploadServlet.doGet(FileUploadServlet.java:102)
at org.stc.medical.fileupload.FileUploadServlet.doPost(FileUploadServlet.java:78)
user3459021
  • 21
  • 1
  • 5
  • How are you submitting the form a "GET" or "POST". If the form is submitted as a get request the form parameters will be available in HttpRequest object. Looking at your code you are submitting as a post so you need to populate a form object. – Waqar Jun 09 '15 at 04:47
  • @Waqar using post method – user3459021 Jun 09 '15 at 04:48
  • in the doPost you will not get request attributes. Refer to my answer – Waqar Jun 09 '15 at 04:52
  • The answer is in the duplicate link. Stop fiddling around in code like a headless chicken based on poor answers and take time to carefully read the duplicate link. Everything a web developer need to know about dealing with muitipart/form-data requests in JSP/Servlet is outlined there. – BalusC Jun 09 '15 at 05:53

2 Answers2

0

Porblem here is, since your are posting the form with encrypt type multipart

 <form method="post" action="fileUpload" enctype="multipart/form-data">

This code fails:

String val=request.getParameter("voucherType");

You need to extract from the multipart itself. Try using getPart().

Use this method to get the string value from the part, more in detail:

private static String getValue(Part part) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
    StringBuilder value = new StringBuilder();
    char[] buffer = new char[1024];
    int length;
    while(-1 != (length = reader.read(buffer))) {
        value.append(buffer, 0, length);
    }
    return value.toString();
}

So you will end up with:

String val = getValue(request.getPart("voucherType"));
Community
  • 1
  • 1
  • If you copypaste code snippets from elsewhere instead of writing off top of head, it would be much appreciated if you honestly link the source where you found the code snippet, instead of doing off as it were yours. See also the cc-by-sa license at bottom of this page. – BalusC Jun 09 '15 at 05:11
  • @Arvind tried your answer, but getting null value. Updated my question – user3459021 Jun 09 '15 at 05:25
  • @user3459021, kindly see my updates and do verify from the browser console in the naigation tab whether the parameter is being sent or not. –  Jun 09 '15 at 05:28
  • @Arvind getting null pointer exception at `BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));` – user3459021 Jun 09 '15 at 05:37
  • @user3459021, it seems to me that the Part itself is null, kindly verify the parameter being sent from the web browser console, in the naviagtion tab. –  Jun 09 '15 at 05:47
  • @Arvind It is not printing any value in console – user3459021 Jun 09 '15 at 05:50
  • @user3459021, can you post the snap shot of web browser console? –  Jun 09 '15 at 05:51
-1

Try this - In your doPost call a doGet to check if the parameters are available in request scope..

// Method to handle POST method request.

public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        String val=request.getParameter("voucherType");

        // Get writer from res
        PrintWriter pw=response.getWriter();
        pw.println("<h1> You selected "+val+"</h1>");
}
Waqar
  • 428
  • 4
  • 17