jyotsna
jyotsna

Reputation: 61

Inserting survey data to mySql database in jsp/servlet

I have created survey form and trying to insert multiple question at a time in database but it showing null pointer error.I have dynamically created the field

jsp file: here, I am creating survey question on clicking show priview button it is added to preview div.By this i am creating multiple questions then submitted to database by clicking on save button

    <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 I am trying to save data which are part of preview div in jsp file

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

Upvotes: 1

Views: 308

Answers (1)

Swati
Swati

Reputation: 28522

In your jsp code you have not added any inputs which will identify whether the select-type is single,short or multiple .Now to add that simply when user will select any option from dropdown you can just append a hidden input with the radios or checkboxes.

Some changes you need to make in jsp and jquery :

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

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

Now , in your servlet code do below changes :

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

(Above codes are already tested with database and working fine)

Upvotes: 1

Related Questions