如何使用servlet

时间:2015-06-09 04:43:31

标签: java servlets

我想使用以下代码通过servlet从select选项中检索所选值。

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();
}

我的html代码用于选择选项

             <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>

选择该选项后,我获得了空值,我在这里看到了很多解决方案。但是找不到解决方案。

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)

2 个答案:

答案 0 :(得分:0)

这里是Porblem,因为您发布的是加密类型为multipart的表单

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

此代码失败:

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

您需要从multipart本身中提取。尝试使用getPart()

使用此方法从部件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();
}

所以你最终会得到:

String val = getValue(request.getPart("voucherType"));

答案 1 :(得分:-1)

试试这个 - 在doPost中调用doGet来检查参数是否在请求范围内可用..

//处理POST方法请求的方法。

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>");
}