JSP表单在插入数据库时​​返回空值

时间:2016-11-12 15:07:04

标签: java mysql eclipse jsp servlets

我有这个JSP表单,我从上一页插入了一些值。

    <script language="javascript" type="text/javascript">
var i = 1;
function addRow() {
    var tbl = document.getElementById('table1');
    var lastRow = tbl.rows.length;
    var iteration = lastRow - 1;
    var row = tbl.insertRow(lastRow);
    var firstCell = row.insertCell(0);
    var el = document.createElement('input');

    el.type = 'text';
    el.name = 'name_' + i;
    el.id = 'name_' + i;
    el.size = 10;
    el.maxlength = 10;
    firstCell.appendChild(el);

    // alert(i);
    i++;
    frm.h.value = i;
    //  alert(i);
}
</script>
<form action="CreateAssignments" method="post"
enctype="multipart/form-data">
<center>
<table id="table1">
<tr>
<td>
<p>Degree :</p>
</td>
<td><label><%=request.getParameter("degree")%> </label> <input type="hidden" name="degree"
            value="<%=request.getParameter("degree")%>" /></td>
        <td></td>
        <td>
            <p>Course :</p>
        </td>
        <td><label><%=request.getParameter("course")%> </label><input
            type="hidden" name="course"
            value="<%=request.getParameter("course")%>" /></td>

    </tr>
    <tr>
        <td>
            <p>Stream :</p>
        </td>
        <td><label><%=request.getParameter("stream")%> </label><input
            type="hidden" name="stream"
            value="<%=request.getParameter("stream")%>" /></td>
        <td></td>
        <td>
            <p>Section :</p>
        </td>
        <td><label><%=request.getParameter("section")%> </label><input
            type="hidden" name="section"
            value="<%=request.getParameter("section")%>" /></td>
    </tr>
    <tr>
        <td>
            <p>Semester :</p>
        </td>
        <td><label><%=request.getParameter("semester")%></label><input
            type="hidden" name="semester"
            value="<%=request.getParameter("semester")%>" /></td>
        <td></td>
        <td>
            <p>Paper Code :</p>
        </td>
        <td><label><%=request.getParameter("papercode")%></label><input
            type="hidden" name="papercode"
            value="<%=request.getParameter("papercode")%>" /></td>
    </tr>
    <tr>
        <td><p>
                <input type="button" value="Add Questions" onclick="addRow();" />
            </p></td>


    </tr>
    <tr>
        <td><p>Start Date:</p></td>
        <td><p>
                <input type="date" name="startdate" />
            </p></td>
    </tr>
    <tr>
        <td><p>End Date:</p></td>
        <td><p>
                <input type="date" name="enddate" />
            </p></td>

    </tr>
    <tr>
        <td><p>Assignment Name:</p></td>
        <td><p>
                <input type="text" name="assname" />
            </p></td>
    </tr>
    <tr>
        <td><p>Upload File</p></td>
        <td><p>
                <input type="file" name="fileupload" value="" />
            </p></td>
    </tr>
    <tr>
        <td><p></p></td>
        <td></td>
<tr>
</table>
<p>
<input type="submit" value="Create" />
</p>
</center>
</form>

这个Java类将数据插入数据库。

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    session = request.getSession(true);

    String assignmentName = request.getParameter("assname");
    String startDate = request.getParameter("startdate");
    String endDate = request.getParameter("enddate");
    String course = request.getParameter("course");
    String degree = request.getParameter("degree");
    System.out.println("degree: "+degree);
    String semester = request.getParameter("semester");
    String paperCode = request.getParameter("papercode");
    String stream = request.getParameter("stream");
    String fileName = uploadFile(request, response);
    String question1=request.getParameter("name_1");
    String question2=request.getParameter("name_2");
    String question3=request.getParameter("name_3");
    String question4=request.getParameter("name_4");
    String question5=request.getParameter("name_5");
    String question6=request.getParameter("name_6");

    System.out.println("FILE NAME : " + fileName);

    try {
        PreparedStatement ps = connection.prepareStatement("insert into assignment_master values (?,?,?,?,?,?,?,?,?,?)");
        ps.setString(1, "2");
        ps.setString(2, assignmentName);
        ps.setString(3, degree);
        ps.setString(4, course);
        ps.setString(5, stream);
        ps.setString(6, semester);
        ps.setString(7, (String) session.getAttribute("employeeId"));
        ps.setString(8, fileName);
        ps.setString(9, startDate);
        ps.setString(10, endDate);

        ps.executeUpdate();
        PreparedStatement ps1 = connection
                .prepareStatement("select max(assignment_id) assignmentId from assignment_master");
        ResultSet rs = ps1.executeQuery();

        PreparedStatement ps2 = connection.prepareStatement("insert into assignment_subject(?,?)");
        ps2.setString(1, rs.getString("assignmentId"));
        ps2.setString(2, paperCode);
        ps2.executeUpdate();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private String uploadFile(HttpServletRequest request, HttpServletResponse response) {

    response.setContentType("text/html");
    // PrintWriter out = response.getWriter();

    // out.println("<html>");
    // out.println("<body>");
    String value = "";
    FileItemStream fileItemStream = null;
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        // out.println("Yes Multipart data");

        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                fileItemStream = itr.next();

                if (fileItemStream.isFormField()) {
                    // do field related work
                    String fieldName = fileItemStream.getFieldName();
                    InputStream is = fileItemStream.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    value = new String(b);
                    // out.println(fieldName + " : " + value);
                } else {
                    String path = getServletContext().getRealPath("/");
                    System.out.println("PATH : " + path);
                    if (FileUpload.processFile(path, fileItemStream, value)) {
                        System.out.println("File Uploaded Successfully");

                        // request.setAttribute("imagePath", path
                        // + fileItemStream.getName());
                        // RequestDispatcher gotoShowPage = request
                        // .getRequestDispatcher("showPage.jsp");
                        // gotoShowPage.forward(request, response);

                    } else {
                        // out.println("File Uploading failed ");
                        System.out.println("File Uploading failed ");
                    }

                }

            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }

    } else {
        // out.println("No Multipart data");
    }

    // out.println("</body>");
    // out.println("</html>");
    return fileItemStream.getName();
}

}

但是当我提交此表单并尝试插入数据时,我得到一个错误,说主键不能为空,当我调试时,我意识到实际上表单中的所有字段都返回空值。我还想知道来自动态文本框的访问数据并插入它们。

谢谢。

2 个答案:

答案 0 :(得分:0)

您的插入声明不正确。

insert into assignment_master values (?,?,?,?,?,?,?,?,?,?)

您必须为这些列命名:

insert into assignment_master(assignment_id, assignment_name, degree, course, stream, semester, employee_id, file_name, start_date, end_date) values (?,?,?,?,?,?,?,?,?,?)

在第二个插页中也是如此:

insert into assignment_subject(?,?)

必须指定列名。

如果未指定列名,则将为所有列分配其默认值。请参阅[3]了解MySQL。

假设您使用的是MySQL,请参阅INSERT语法:[1]

对于PostgreSQL,请参阅[2]。

[1] http://dev.mysql.com/doc/refman/5.7/en/insert.html

[2] https://www.postgresql.org/docs/current/static/sql-insert.html

[3] http://dev.mysql.com/doc/refman/5.7/en/insert.html#idm139777556167776

答案 1 :(得分:0)

每当您使用Multipart上传表单数据时,请求对象将转换为流,即特定的数据流。

在这种情况下,您不会将字段作为参数。它们随附文件数据。下面显示的代码 - 已显示在您显示的代码中处理:

if (fileItemStream.isFormField()) {
                        // do field related work
                        String fieldName = fileItemStream.getFieldName();
                        InputStream is = fileItemStream.openStream();
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        value = new String(b);
                        // out.println(fieldName + " : " + value);
                    }

您可以修改此代码以创建表单中存在的参数的散列图。代码可以是:

HashMap<String,String> myvaluemap = new HashMap();
if (fileItemStream.isFormField()) {
    String fieldName = fileItemStream.getFieldName();
    InputStream is = fileItemStream.openStream();
    byte[] b = new byte[is.available()];
    is.read(b);
    value = new String(b);
    myvaluemap.put(name,value);
                    }

我在最后测试了它。如果还需要任何进一步的帮助,请告诉我。

供您参考,您可以参考: this link。在处理上传的项目部分。这不是确切的事情,但提供了提示