在 jsp/servlet 中将调查数据插入 mySql 数据库

Posted

技术标签:

【中文标题】在 jsp/servlet 中将调查数据插入 mySql 数据库【英文标题】:Inserting survey data to mySql database in jsp/servlet 【发布时间】:2020-07-03 10:08:06 【问题描述】:

我已创建调查表并尝试在数据库中一次插入多个问题,但显示空指针错误。我已动态创建该字段

jsp 文件:在这里,我在单击显示 priview 按钮时创建调查问题,它被添加到预览 div。通过此我创建多个问题,然后通过单击保存按钮提交到数据库

    <form method="post" action="getSurvey">     
    <div id="section1">
        <div>
            <label for="surveyName" class="labelstyle">Enter Survey Title</label>
            <input type="text" id="surveyName" name="surveyName[]" >
        </div>
        <br>
        <div>
            <label for="surveyQuestion" class="labelstyle" >Enter Question </label>
            <input type="text" id="surveyQuestion" name="surveyQuestion[]" >
            <select name="answerType" id="answerType" class="selectPicker" >
                <option selected="selected">None</option>
                <option value="multiple">Multiple Choice type</option>
                <option value="single">Single Choice Type</option>
                <option value="short">Short Answer Type</option>
            </select>
        </div>
        <div id="newSurvey">
        
        </div>
        <div>
            <button type="button"  id="showPreview" name="showPreview" class="button">Show Preview</button>
        </div>
    </div>
    <div id="section2">     
        <div>
            <input type="submit" name="saveSurvey" id="saveSurvey" value="Save" class="button" >
        </div>
    
        <h2 class="heading1">Preview</h2>
        <div id="preview">
        
        </div>
    </div>
    </form>

jquery: to generate fields dynamically

        $(document).ready(function()
    var questionCounter=1;
    const $previewid = $('#preview');
    $("select.selectPicker").change(function()
        var option = $(this).children("option:selected").val();
        if(option=="multiple")
            $.fn.callMultiple();
        else if(option=="single")
            $.fn.callSingle();
        else if(option=="short")
            $.fn.callShort();
        else
            alert("Please select from options");
    );
    $.fn.callMultiple = function() 
        $('#newSurvey').empty();
        var selectType = $('#answerType').val();
        let newrow='<input type="checkbox" name="check1"><input type="text" id="t1" name="txt1[]"><br>'+
                    '<input type="checkbox" name="check2"><input type="text" id="t2" name="txt2[]"><br>'+
                    '<input type="checkbox" name="check3"><input type="text" id="t3" name="txt3[]"><br>'+
                    '<input type="checkbox" name="check4"><input type="text" id="t4" name="txt4[]"><br>';+
                    '<input type="hidden" name="stype[]" id="stype" value="'+selectType+'">';
        $('#newSurvey').append(newrow);
      
    $.fn.callSingle = function() 
        $('#newSurvey').empty();
        var selectType = $('#answerType').val();
        let newrow='<input type="radio" name="radioval"><input type="text" id="t1" name="txt1[]"><br>'+
        '<input type="radio" name="radioval"><input type="text" id="t2" name="txt2[]"><br>'+
        '<input type="radio" name="radioval"><input type="text" id="t3" name="txt3[]"><br>'+
        '<input type="radio" name="radioval"><input type="text" id="t4" name="txt4[]"><br>';+
        '<input type="hidden" name="stype[]" id="stype" value="'+selectType+'">';
        $('#newSurvey').append(newrow);
      
    $.fn.callShort = function() 
        $('#newSurvey').empty();
        var selectType = $('#answerType').val();
        let newrow='<input type="text" name="shortanswer[]" id="shortanswer">';+
        '<input type="hidden" name="stype[]" id="stype" value="'+selectType+'">';
        $('#newSurvey').append(newrow);
           
    
    $('#showPreview').on('click',function(e)
        questionCounter++;
        var title = $('#surveyName').val();
        var question = $('#surveyQuestion').val();
        var uprow='<br><center><input type="text" id="surveyName" name="surveyName[]" value='+title+' readonly></center><br>'+
        '&nbsp;<input type="text" id="surveyQuestion" name="surveyQuestion[]" value='+question+' readonly><br><br>';
        const $firstRow = $('#newSurvey').find("*");
        let $newrowhtml = $firstRow.clone(true);
        $('#section1').find(":input").val("");
        $previewid.prepend($newrowhtml);
        $previewid.prepend(uprow);
        $previewid.find(":input").attr('readonly','readonly');
    );
);

servlet 我正在尝试将属于预览 div 一部分的数据保存在 jsp 文件中

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

    PrintWriter out = response.getWriter();
    String surveyTitle[] = request.getParameterValues("surveyName[]");
    String question[] = request.getParameterValues("surveyQuestion[]");
    String[] option1, option2, option3, option4, single;
    int row1=0,row2=0;
    int i;
    option1=option2=option3=option4=single=null;
    
    option1=request.getParameterValues("txt1[]");
    option2=request.getParameterValues("txt2[]");
    option3=request.getParameterValues("txt3[]");
    option4=request.getParameterValues("txt4[]");
    String selectType[]=request.getParameterValues("stype[]");
    out.println(selectType.length);
    for( i=0;i<selectType.length;i++)
        out.println(selectType[i]+" "+i);
    if(request.getParameterValues("shortanswer[]") != null)
    
        single=request.getParameterValues("shortanswer[]");
    
    for( i=0;i<single.length;i++)
        out.println(single[i]+" "+i);
    String[] op1,op2,op3,op4,ans;
    op1=op2=op3=op4=ans=null;
    int k=0,j=0;
    for(i=1;i<surveyTitle.length;i++)
    
        if((selectType[i].equals("multiple"))||selectType[i].equals("single"))
        
            op1[i]=option1[j];
            op2[i]=option2[j];
            op3[i]=option3[j];
            op4[i]=option4[j];
            ans[i]=null;
            j++;
        
        else if(selectType.equals("short"))
        
            op1[i]=null;
            op2[i]=null;
            op3[i]=null;
            op4[i]=null;
            ans[i]=single[k];
            k++;
        
        out.println(op1[i]+""+op2[i]+""+op3[i]+""+op4[i]+""+ans[i]);
    
    try 
    
        Class.forName(JDBC_Driver);
        con = DriverManager.getConnection(URL, username, password);
        for(i=1;i<surveyTitle.length;i++)
        
            if((selectType[i].equals("multiple"))||selectType[i].equals("single"))
            
                query1 ="insert into surveydetail (surveyTitle,questionName,optionOne,optionTwo,optionThree,optionFour,selectType) values (?,?,?,?,?,?,?)";
                pstmt1 = con.prepareStatement(query1);
                pstmt1.clearParameters();
                pstmt1.setString(1, surveyTitle[i]);
                pstmt1.setString(2, question[i]);
                pstmt1.setString(3, op1[i]);
                pstmt1.setString(4, op2[i]);
                pstmt1.setString(5, op3[i]);
                pstmt1.setString(6, op4[i]);    
                pstmt1.setString(7, selectType[i]);
                row1=pstmt1.executeUpdate();
               
            else if(selectType.equals("short"))
            
                query2 ="insert into surveydetail (surveyTitle,questionName,shortAnswer,selectType) values (?,?,?,?)";
                pstmt2 = con.prepareStatement(query2);
                pstmt2.clearParameters();
                pstmt2.setString(1, surveyTitle[i]);
                pstmt2.setString(2, question[i]);
                pstmt2.setString(3, ans[i]);
                pstmt2.setString(4, selectType[i]);
                row2=pstmt1.executeUpdate();
            
        
        if((row1>0)||(row2>0))
        
            response.sendRedirect("CreateSurveyView.jsp");
        
        else
        
            response.sendRedirect("Error.jsp");
        
     
    catch (Exception e) 
        // TODO Auto-generated catch block
        e.printStackTrace();
    
    

【问题讨论】:

它在哪里给你 null ? 在文本字段 txt 中,也不显示选择类型的值 在调试时,我正在获取除名称为 txt 的文本字段之外的所有元素的值,然后选择下拉列表。我不知道我在哪里犯错 因为在预览时您没有获得特定问题的选择值。当您单击预览时添加一些隐藏字段,以便选择类型也将与该问题一起添加 我添加了隐藏字段,但仍然没有显示任何值 【参考方案1】:

在您的 jsp 代码中,您没有添加任何 inputs 来识别选择类型是单、短还是多。现在添加,当用户从下拉列表中选择任何选项时,您只需附加一个 @987654322 @ 输入 radioscheckboxes

您需要在 jspjquery 中进行一些更改:

 <div id="section1">
       <!--other fields-->
 </div>
   <!--add form tag here-->
  <form method="post" action="getSurvey">
    <div id="section2">     
       <div>
           <input type="submit" name="saveSurvey" id="saveSurvey" value="Save" class="button" >
        </div>
        
          <h2 class="heading1">Preview</h2>
          <div id="preview">
        </div>
     </div>
  </form>

Jquery 代码

$(document).ready(function() 
  var questionCounter = 1;
  $("select.selectPicker").change(function() 
    //your codes
  );
  $.fn.callMultiple = function() 
    $('#newSurvey').empty();
    //added hidden input with name="answerType1[]" 
    var newrow = '<input type="hidden" name="answerType1[]" value="multiple"/>' +
      '<input type="checkbox" name="check1"><input type="text" id="t1_" name="txt1[]"><br>' +
      '<input type="checkbox" name="check2"><input type="text" id="t2" name="txt2[]"><br>' +
      '<input type="checkbox" name="check3"><input type="text" id="t3" name="txt3[]"><br>' +
      '<input type="checkbox" name="check4"><input type="text" id="t4" name="txt4[]"><br>';
    $('#newSurvey').append(newrow);
  
  $.fn.callSingle = function() 
    $('#newSurvey').empty();
    //added hidden input with name="answerType1[]"
    var newrow =  '<input type="hidden" name="answerType1[]" value="single"/>' +
      '<input type="radio" name="radioval"><input type="text" id="t1" name="txt1[]"><br>' +
      '<input type="radio" name="radioval"><input type="text" id="t2" name="txt2[]"><br>' +
      '<input type="radio" name="radioval"><input type="text" id="t3" name="txt3[]"><br>' +
      '<input type="radio" name="radioval"><input type="text" id="t4" name="txt4[]"><br>';
    $('#newSurvey').append(newrow);
  
  $.fn.callShort = function() 
    $('#newSurvey').empty();
    //added hidden input with name="answerType1[]" 
    var newrow = '<input type="hidden" name="answerType1[]" value="short"/>' + '<input type="text" name="txt[]" id="t1">';
    $('#newSurvey').append(newrow);
  
//other codes
);

现在,在您的 servlet 代码中进行以下更改:

 String surveyTitle[] = request.getParameterValues("surveyName[]");
 String question[] = request.getParameterValues("surveyQuestion[]");

 String[] option1, option2, option3, option4, answer;
 int row1 = 0, row2 = 0;
 int i;
 PreparedStatement pstmt1, pstmt2;
 option1 = option2 = option3 = option4 = answer = null;
 //if txt1[] not null get values
 if (request.getParameterValues("txt1[]") != null) 
  option1 = request.getParameterValues("txt1[]");
  option2 = request.getParameterValues("txt2[]");
  option3 = request.getParameterValues("txt3[]");
  option4 = request.getParameterValues("txt4[]");
 
 //if txt[] "short ans" is not null get value
 if (request.getParameterValues("txt[]") != null) 
  answer = request.getParameterValues("txt[]");

 
 //get select type
 String selectType[] = request.getParameterValues("answerType1[]");
 //for answer 
 int j = 0;

 try 
  Class.forName(JDBC_Driver);
  con = DriverManager.getConnection(URL, username, password);
  out.println(question.length); //seeing length of question
  //looping through question array
  for (i = 0; i < question.length; i++) 
   //chcking the selecttype
   if ((selectType[i].equals("multiple")) || (selectType[i].equals("single"))) 
    //insert
    String query1 = "insert into surveydetail (surveyTitle,questionName,optionOne,optionTwo,optionThree,optionFour,selectType) values (?,?,?,?,?,?,?)";
    pstmt1 = con.prepareStatement(query1);
    pstmt1.clearParameters();
    pstmt1.setString(1, surveyTitle[i]);
    pstmt1.setString(2, question[i]);
    pstmt1.setString(3, option1[i]);
    pstmt1.setString(4, option2[i]);
    pstmt1.setString(5, option3[i]);
    pstmt1.setString(6, option4[i]);
    pstmt1.setString(7, selectType[i]);
    out.println("  " + surveyTitle[i] + " " + question[i] + " " + option1[i] + "  " + option2[i] + " " + option3[i] + " " + option4[i] + " " + selectType[i]);
    row1 = pstmt1.executeUpdate();
    else if (selectType[i].equals("short")) 
    //insert
    String query2 = "insert into surveydetail (surveyTitle,questionName,shortAnswer,selectType) values (?,?,?,?)";
    pstmt2 = con.prepareStatement(query2);
    pstmt2.clearParameters();
    pstmt2.setString(1, surveyTitle[i]);
    pstmt2.setString(2, question[i]);
    pstmt2.setString(3, answer[j]);//here we will pass "j" value
    pstmt2.setString(4, selectType[i]);
    row2 = pstmt2.executeUpdate();
    out.println("  " + surveyTitle[i] + " " + question[i] + "  " + answer[j] + " " + selectType[i]);
    j++;
   
  
  if ((row1 > 0) || (row2 > 0)) 
   response.sendRedirect("CreateSurveyView.jsp");
   else 
     response.sendRedirect("Error.jsp");
  
  catch (Exception e) 
  // TODO Auto-generated catch block
  e.printStackTrace();
 

(上面的代码已经用数据库测试过并且工作正常)

【讨论】:

感谢 swati 我已经做到了,但感谢...寻求帮助

以上是关于在 jsp/servlet 中将调查数据插入 mySql 数据库的主要内容,如果未能解决你的问题,请参考以下文章

我可以在 jsp/servlet 或控制台应用程序中打开多少个数据库连接?

JSP+Servlet项目总结

JSP+Servlet项目总结

使用Jsp+Servlet+JavaBean技术做学生成绩管理系统

JSP/Servlet基础语法

使用Javaweb实现在线调查问卷系统