tags:

views:

104

answers:

2
Q: 

JSP - Quiz

I am developing a Quiz module. I have stored all the questions,its options and other details in a array of vectors.

I want to display the first question to the user and when he submits it only then the second question should be displayed on the page...and so on... ie on the click of submit an event should occur such that the counter gets incremented and the value in vector array is displayed... How am i supposed to do this..

A: 

if you don't want the page to reload, i would have your JSP write javascript to reflect the vectors. For instance,

Vector questions = <some Vector of Question objects>;
int size = questions.size();
%><script>
    var questions[] = new Array(<%= size %>);
<%
  for(int a =0; a < size; a++){
      Question myQ = (Question)questions.get(a);
      %>questions[<%= a %>] = '<%= myQ.getQuestionText() %>';<%
  }
%></script>

Then, you can write an onclick="displayNextQuestion();" for the submit button where the javascript function would alter the HTML of the page to display the next question, and its form field, etc.

adam
A: 

Pass the current step as a hidden input value.

E.g. in JSP:

<input type="hidden" name="step" value="${step}">

And in Servlet's doGet() (which is been invoked for initial display):

int step = 1;
Question firstQuestion = questionDAO.find(step);
request.setAttribute("step", step);
request.setAttribute("question", question);

and in Servlet's doPost() (which processes each form submit):

int currentStep = Integer.valueOf(request.getParameter("step"));
int nextStep = currentStep++;
Question nextQuestion = questionDAO.find(nextStep);
request.setAttribute("step", nextStep);
request.setAttribute("question", nextQuestion);

Alternatively you can also make the 'step' some 'id' of the question so that you don't need to set an extra attribute for 'step', but just can do something like:

<input type="hidden" name="id" value="${question.id}">

Good luck.

BalusC