vendredi 29 mai 2020

Question not fetching from db and not displaying result

i was trying to develop web application of MCQ test using jsp and servlet. question id is fetching on test screen for students but question not showing. instead it shows test name. also after submit test it not generate results. I checked database but it is fine. below is code!

testscreen.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="java.util.ArrayList, com.bmpl.examviral.quiz.*"%>
<%@page import="java.util.HashMap, com.bmpl.examviral.quiz.*"%>
<%@page import="java.util.Map, com.bmpl.examviral.quiz.*"%>
<%@page import="com.bmpl.examviral.quiz.model.dto.QuestionDTO"%>
<%@page import="com.bmpl.examviral.quiz.model.dto.TestDTO"%>
<%@page import="com.bmpl.examviral.quiz.model.dto.UserDTO"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%          
        ArrayList<QuestionDTO> questionlist = (ArrayList<QuestionDTO>)request.getAttribute("questionList");
        TestDTO testdto = (TestDTO)request.getAttribute("testDetails");
        UserDTO userdto = (UserDTO)request.getAttribute("userdetails");
        session.setAttribute("testDetails", testdto);
        session.setAttribute("userdetails", userdto);
        String testName = (String)request.getAttribute("testName");
        int testDuration = (Integer)request.getAttribute("testDuration");
        int dataSize = questionlist.size();
        HashMap<Integer, String[]> map = new HashMap<Integer, String[]>();
        HashMap<Integer, String[]> quesmap = new HashMap<Integer, String[]>();
        int quesNum[] = new int[dataSize];
        String quesArr[] = new String[dataSize];
        String optionAArray[] = new String[dataSize];
        String optionBArray[] = new String[dataSize];
        String optionCArray[] = new String[dataSize];
        String optionDArray[] = new String[dataSize];       
        String option1[] = new String[dataSize];
        String option2[] = new String[dataSize];
        String option3[] = new String[dataSize];
        String option4[] = new String[dataSize];
        String ques1[] = new String[dataSize];
        String ques2[] = new String[dataSize];
        String ques3[] = new String[dataSize];
        String ques4[] = new String[dataSize];
        String ques5[] = new String[dataSize];
        int keys[] = new int[dataSize];
        int quesKeys[] = new int[dataSize];     
        for(int i=0,j=i+1,k=j+1,l=k+1; i<dataSize;i++){
            QuestionDTO quesSet = questionlist.get(i);
            quesNum[i] = quesSet.getQuesNo();
            quesArr[i] =quesSet.getQuestion();
            for(String s: quesArr){
                System.out.println("New Array "+s);

            }
            optionAArray[i]= quesSet.getOptionA();
            optionBArray[i]= quesSet.getOptionB();
            optionCArray[i]= quesSet.getOptionC();
            optionDArray[i]= quesSet.getOptionD();          
            System.out.println("Question No is "+quesNum[i]);
            System.out.println("Question "+(i+1)+" is "+quesArr[i]);
            System.out.println("Option A Array is "+optionAArray[i]);
            System.out.println("Option B Array is "+optionBArray[i]);
            System.out.println("Option C Array is "+optionCArray[i]);
            System.out.println("Option D Array is "+optionDArray[i]);
            map.put(keys[i], optionAArray);
            option1 = map.get(keys[i]);
            System.out.println("Keys of I "+option1[i]);
            map.put(keys[j], optionBArray);
            option2 = map.get(keys[j]);
            System.out.println("Keys of J "+option2[j]);
            map.put(keys[k], optionCArray);
            option3 = map.get(keys[k]);
            System.out.println("Keys of K "+option3[k]);
            map.put(keys[l], optionDArray);
            option4 = map.get(keys[l]);
            System.out.println("Keys of L "+option4[l]); 
        }

%>    
<!DOCTYPE html5>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome to <%= testName %> test</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Allerta+Stencil">
<link rel="icon" href="../../favicon.ico">
<link href="css/fontawesome.min.css" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- Custom css -->
<link rel="stylesheet" href="css/testscreen.css">
<script src="js/timer.js"></script>
</head>

<body>
    <div class="row header">
        <div class="col-lg-12">
            <div class="logo">
                <img src="images/logo.jpg" alt="">
            </div>
           <h1>Welcome to exam viral<br><span data-shadow-text="Text-Shadow">Java Programming</span><br> test</h1>
       </div>           
    </div>
    <div class="row quespage" ng-show="questionPage" id="quesdiv">
        <div class="col-lg-4 sidepanel">
            <div class="timestatus w3-container w3-allerta">
                <p>Total Time:<span id="totaltime"><c:out value="${testDuration}"></c:out></span></p>
                <p id="showtime" class="w3-xlarge">Time Left: <span id="time"></span> Minutes</p>
            </div>
            <div class="card">
                  <img src="images/newdp.png" alt="John" style="width:100%">
                  <h2>Samarth Parashar</h2>
                  <p class="title">Student</p>
                  <p class="iname">MERI College</p> 
                  <p><button>Contact</button></p>
            </div>

        </div>
        <div class="col-lg-8 quesdiv">
            <form action="Test?noofquestions=<%= dataSize%>&testName=<%= testName%>" method="post">
                        <%
                            for(int i=0;i<keys.length;i++){

                        %>  
                        <div class="panel panel-primary">
                        <div class="panel-heading">
                            <input type="hidden" name="que<%=i%>" value="<%= quesArr[i]%>"/>
                            <h3 class="panel-title"><%= quesNum[i] %>&nbsp &nbsp <%= quesArr[i]%><br></h3>
                        </div>
                        <div class="panel-body">
                            <table>
                                <tbody>

                                    <tr>
                                        <td>A</td>
                                        <td><input type="radio" name="options<%= i %>" value="optionA" required>&nbsp <%= option1[i] %></td>
                                    </tr>
                                    <tr>
                                        <td>B</td>
                                        <td><input type="radio" name="options<%= i %>" value="optionB" required>&nbsp <%= option2[i] %></td>
                                    </tr>
                                    <tr>
                                        <td>C</td>
                                        <td><input type="radio" name="options<%= i %>" value="optionC" required>&nbsp <%= option3[i] %></td>
                                    </tr>
                                    <tr>
                                        <td>D</td>
                                        <td><input type="radio" name="options<%= i %>" value="optionD" required>&nbsp <%= option4[i] %></td>
                                    </tr>                               
                                </tbody>
                            </table>

                        </div>
                    </div>

                <%  
                    }
                %>
            <input class="btn btn-primary submitBtn" id="submitButton" type="submit" value="Submit">
            <input type="reset" class="btn btn-success" value="Reset">
            </form>
            <a class="btn btn-primary" href="logout.jsp">Logout</a>
      </div>
    </div>
</body>
</html>

testcontroller.java test servlet page

package com.bmpl.examviral.quiz.controller.testcontrollers;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bmpl.examviral.quiz.commonutils.Result;
import com.bmpl.examviral.quiz.model.dao.QuestionDAO;
import com.bmpl.examviral.quiz.model.dao.ResultDAO;
import com.bmpl.examviral.quiz.model.dto.QuestionDTO;
import com.bmpl.examviral.quiz.model.dto.ResultDTO;
import com.bmpl.examviral.quiz.model.dto.TestDTO;
import com.bmpl.examviral.quiz.model.dto.UserDTO;

/**
 * Servlet implementation class TestController
 */
@WebServlet("/Test")
public class TestController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    int rows=0;
    /*String optionArray[] = new String[4];
    String quearr[] = new String[6];*/
    QuestionDAO quesdao = new QuestionDAO();
    QuestionDTO quesdto = new QuestionDTO();
    ResultDTO resultdto = new ResultDTO();
    ResultDAO resultdao = new ResultDAO();
    int dbresult=0;

    /*int correctAnsCounter=0;
    int incorrectAnsCounter=0;*/

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        int correctAnsCounter=0;
        int incorrectAnsCounter=0;
        HttpSession session = request.getSession();
        TestDTO testdto = (TestDTO)session.getAttribute("testDetails");
        UserDTO userdto = (UserDTO)session.getAttribute("userdetails");
        int totalMarks = testdto.getTotalMarks();
        System.out.println("Total Marks "+totalMarks);
        String testName = request.getParameter("testName");
        String arr = (String)request.getAttribute("arr");
        System.out.println("String in controller"+arr);
        System.out.println("Test name is "+testName);
        rows = Integer.parseInt(request.getParameter("noofquestions"));
        Result result = new Result(rows, totalMarks);
        String optionArray[] = new String[rows];
        String quearr[] = new String[rows];
        System.out.println("No of questions are "+rows);
        for(int i=0;i<rows;i++){

            quearr= request.getParameterValues("que"+i);
            optionArray[i] = (String)request.getParameter("options"+i);
            String userSelectedOption = optionArray[i];
            if(userSelectedOption==null){
                System.out.println("Getting Null Value");               
            }else{  
                System.out.println("Option selected by user of Question "+(i+1)+" is "+userSelectedOption);
                for(String s: quearr){
                    System.out.println("question "+ s);
                    QuestionDTO quesdto = quesdao.getDataComp(s, testName);
                    String correctAns = quesdto.getCorrectAnswer();
                    System.out.println("Correct Ans is "+correctAns);
                    int cmp = correctAns.compareTo(userSelectedOption);
                    if(cmp == 0){
                        correctAnsCounter++;
                        System.out.println("Answer is correct");
                    }else{
                        incorrectAnsCounter++;
                        System.out.println("Answer is not correct");
                    }
                }
            }
        }
        result.countCorrectAns(correctAnsCounter);
        float percentage = result.calculatePercentage();
        System.out.println("User Get "+percentage+" percentage");
        System.out.println("No of correct answer is "+correctAnsCounter);
        System.out.println("No of incorrect answer is "+incorrectAnsCounter);
        resultdto.setUsername(userdto.getUsername());
        resultdto.setMarks(percentage);
        resultdto.setEmail(userdto.getEmail());
        resultdto.setTestName(testName);
         try {
            dbresult = resultdao.insertResultData(resultdto);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        request.setAttribute("percentage", percentage);
        request.setAttribute("correctAnswers", correctAnsCounter);
        request.setAttribute("incorrectAnswers", incorrectAnsCounter);
        request.setAttribute("testName", testName);
        request.setAttribute("userdetails", userdto);
        request.setAttribute("noofques", rows);
        RequestDispatcher rd = request.getRequestDispatcher("result.jsp");
        rd.forward(request, response);
    }

}


result.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="com.bmpl.examviral.quiz.model.dto.UserDTO"%>    
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    UserDTO userdto = (UserDTO)request.getAttribute("userdetails");
    int noofques = (Integer)(request.getAttribute("noofques"));
    int correctAnswers = (Integer)(request.getAttribute("correctAnswers"));
    int incorrectAnswers = (Integer)request.getAttribute("incorrectAnswers");
%>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student Result</title>
    <!-- Bootstrap library--->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!---- Custom css file ---->
    <link rel="stylesheet" href="css/result.css">
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

      // Load the Visualization API and the corechart package.
      google.charts.load('current', {'packages':['corechart']});

      // Set a callback to run when the Google Visualization API is loaded.
      google.charts.setOnLoadCallback(drawChart);

      // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Answers');
        data.addColumn('number', 'answers');
        data.addRows([
            ['Correct Answers', <%= correctAnswers %>],
            ['Incorrect Answers', <%= incorrectAnswers %>]
          ]);


        // Set chart options
        var options = {'title':'How many answers you give right or wrong',
                       'width':400,
                       'height':300};

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
    <!-- Disable Back button -->
    <script type="text/javaScript">
            function disableBackButton()
            {
            window.history.forward();
            }
            setTimeout("disableBackButton()", 0);
    </script>
</head>
<body onload="disableBackButton()">
    <div class="row header">
        <div class="col-lg-12">
          <img src="images/logo.jpg" alt="sitelogo">
             <h2 class="sitename">Exam Viral</h2>
            <h1 class="mainheading">View Student Result</h1>    
            <p class="welcome">Welcome <%= userdto.getUsername() %></p>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-2 col-md-2 col-sm-4 leftsidebar">
            <div class="card">
                  <img src="images/newdp.png" alt="John" style="width:100%">
                  <h2><%= userdto.getUsername() %></h2>
                  <p class="title">Student</p>
                  <p><%= userdto.getInstitutename() %></p>
                  <a href="#"><i class="fa fa-dribbble"></i></a> 
                  <a href="#"><i class="fa fa-twitter"></i></a> 
                  <a href="#"><i class="fa fa-linkedin"></i></a> 
                  <a href="#"><i class="fa fa-facebook"></i></a> 
                  <p><button>Contact</button></p>
            </div>
        </div>
        <div class="col-lg-6 col-md-6 col-sm-4 centerside">
            <div class="panel panel-success">
              <div class="panel-heading">
                    <h3 class="panel-title">Test Submitted Successfully</h3>
              </div>
              <div class="panel-body">
                <p>You Got <c:out value="${requestScope.percentage}"> Percentage</c:out></p>
                <p>Total questions are <%= noofques %></p>
                <p>You gave <c:out value="${requestScope.correctAnswers}"></c:out> correct Answers</p>
                <p>You gave <c:out value="${requestScope.incorrectAnswers}"></c:out> incorrect Answers</p>
              </div>
            </div>
            <a class="btn btn-primary" href="index.jsp">Home</a>
            <a class="btn btn-primary" href="login.jsp">Logout</a>
        </div>
        <div class="col-lg-4 col-md-4 col-sm-4 rightsidebar">
            <div id="chart_div"></div>
        </div>
    </div>
</body>
</html>

I think problem is in testscreen.jsp page line which is below

quesArr[i] =quesSet.getQuestion();
            for(String s: quesArr){
                System.out.println("New Array "+s);

            }

in above list questions are not getting in quesArr[i] help me




Aucun commentaire:

Enregistrer un commentaire