Java/J2EE and SOA (348 Blogs) Become a Certified Professional

Creating an Online Quiz Application Using JSP Servlet

Last updated on Jun 05,2023 185.3K Views


In this post we’ll cover the steps in creating an interactive online quiz application using JSP Servlet technology. We’ll look at how to parse XML files, how to handle sessions and keep track of user interaction using session management.

Creating an online quiz application

Below are some of the snapshots of the end application:

Registration Page

Before taking a quiz, a user have to first register and login. To register one can directly click on the register menu or a link to registration page is provided on the login page to create an account.

Login Page

When a user clicks, an exam user is directly redirected  to the login page, if the user is not logged in.

Login Page

User Home Page

Home page is the landing page of the application from where a user can take any quiz by clicking on the quiz. On the home page, if the user is logged in his name is also shown and a logout link is provided to logout from the application.

Home Page

Quiz Screens

On starting a quiz, a user is presented with the first question of the quiz with the next and finish button. Note that the previous button is not shown when the user is on first question and next button is not shown when the user is in the last question.

Quiz Screen

Quiz Screen

Quiz Result

After clicking on the finish button the user is presented with exam results, showing the name of quiz; time when the quiz was started and the number of questions that the user answered correctly.

Quiz Result

How This Quiz Application Works?

Well, it works as you expect it to work. To take a quiz, a user must be logged in. If the user is not logged in, the user will automatically be redirected to the login page, where the user can login. If the user is not already registered to the application, he has to create an account first. After successfully logging in to the application, the user can take any of the quiz by clicking on it. Now, the user will be presented with the first question of the quiz. To move through the quiz questions, the user is provided with the next and previous buttons. The quiz can be finished at any time by clicking on the finish button.

Let’s get started on building the application

Below is the snapshot of the project structure in Eclipse IDE.

Project Structure

Eclipse Project Structure

Creating the Home Page

Home page is pretty straightforward. We have a menu and 8 images displayed in a table format with two rows; each row containing 4 images. On the home page we also make a check, whether the user is logged in or not. If the user is logged in we also display the username and provide a logout link.

 Creating Menu for Home Page

< div id='cssmenu'>
< ul>
   < li class=''>< a href='${pageContext.request.contextPath}'>< span>Home< /span>< /a>< /li>
   < li>< a href='${pageContext.request.contextPath}/login'>< span>Login< /span>< /a>< /li>
   < li>< a href='${pageContext.request.contextPath}/register'>< span>Register< /span>< /a>< /li>
   < li class='#'>< a href='#'>< span>Submit a Question< /span>< /a>< /li>
   < li class='#'>< a href='#'>< span>Feedback< /span>< /a>< /li>
   < li>< a href='#'>< span>Contribute< /span>< /a>< /li>
   < li>< a href='#'>< span>Contact us< /span>< /a>< /li>
< /ul>
< /div>

Checking whether the user is logged in or not

< c:if test='${not empty sessionScope.user}'>

< div style="position:absolute;top:70px;left:1100px">
Logged as < a href="#" class="button username">${sessionScope.user}< /a>
< /div>

< div style="position:absolute;top:70px;left:1300px">
< a href='${pageContext.request.contextPath}/logout'>Logout< /a>
< /div>

< /c:if>

Showing the quiz images on home page

< div style="position:absolute;left:120px;top:60px">
< table cellpadding="0" cellspacing="50">

< tr>
< td>< a href="takeExam?test=java">< img height="200" width="200" src="${pageContext.request.contextPath}/images/java.png"/>< /a>< /td>
< td>< a href="takeExam?test=javascript">< img height="200" width="200" src="${pageContext.request.contextPath}/images/javascript.png"/>< /a>< /td>
< td>< a href="takeExam?test=sql">< img height="200" width="200" src="${pageContext.request.contextPath}/images/sql-logo.png"/>< /a>< /td>
< td>< a href="takeExam?test=python">< img height="200" width="200" src="${pageContext.request.contextPath}/images/python.jpg"/>< /a>< /td>
< /tr>

< tr>
< td>< a href="takeExam?test=css">< img height="200" width="200" src="${pageContext.request.contextPath}/images/css.jpg"/>< /a>< /td>
< td>< a href="takeExam?test=php">< img height="200" width="200" src="${pageContext.request.contextPath}/images/php-logo.jpg"/>< /a>< /td>
< td>< a href="takeExam?test=linux">< img height="200" width="200" src="${pageContext.request.contextPath}/images/logo-linux.png"/>< /a>< /td>
< td>< a href="takeExam?test=mongodb">< img height="200" width="200" src="${pageContext.request.contextPath}/images/mongodb_logo.png"/>< /a>< /td>
< /tr>

< /table>
< /div>

Creating the User Registration Page

There is nothing fancy in the registration page; just an HTML form awaiting the user to provide his name, email and password. Once we get that, we pass this to RegistrationController servlet to create an account.

Note: We are not doing any validation like password should contain 8 characters with at least one uppercase character, one number and special symbol. We will do that in upcoming posts, when we extend this application.

Registration Code

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		String username=request.getParameter("username");
		String email=request.getParameter("email");
		String password=request.getParameter("password");

		Connection con=DatabaseConnectionFactory.createConnection();

		try
		{
		 Statement st=con.createStatement();
		 String sql = "INSERT INTO users values ('"+username+"','"+password+"','"+email+"')";
		 		System.out.println(sql);
		 st.executeUpdate(sql);
		}catch(SQLException sqe){System.out.println("Error : While Inserting record in database");}
		try
		{
		 con.close();	
		}catch(SQLException se){System.out.println("Error : While Closing Connection");}
        request.setAttribute("newUser",username);
		RequestDispatcher dispatcher=request.getRequestDispatcher("/WEB-INF/jsps/regSuccess.jsp");
		dispatcher.forward(request, response);		
	}

Dive into the world of full stack development and unleash your creativity with our Full Stack Developer Course.

Getting Database Connection

In this application we have used MySQL database to store user credentials. To get a connection to database we have defined a static method createConnection in DatabaseConnectionFactory class, where all database specific information is stored.

We have just users’ table under quiz database.

Users’ table

create table users(username varchar(50),email varchar(50),password varchar(50))

If you are working with some other database like Oracle you have to change the properties of the DatabaseConnectionFactory class accordingly.

DatabaseConnectionFactory.java

public class DatabaseConnectionFactory {

	private static String dbURL="jdbc:mysql://localhost/quiz";
	private static String dbUser="root";
	private static String dbPassword="";

	public static Connection createConnection()
	{
		 Connection con=null;
		try{
			try {
				   Class.forName("com.mysql.jdbc.Driver");
				}
				catch(ClassNotFoundException ex) {
				   System.out.println("Error: unable to load driver class!");
				   System.exit(1);
				}			
		     con = DriverManager.getConnection(dbURL,dbUser,dbPassword);
		   }
		  catch(SQLException sqe){ System.out.println("Error: While Creating connection to database");sqe.printStackTrace();}
		return con;
	}

}

Creating the Login Page

Login page is very much similar to registration page where we are providing two input fields asking user to provide a username and password. Once we get the username and password entered by the user we pass it to LoginController to authenticate user.

Login Validation Code

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

		String username=request.getParameter("username");
		String password=request.getParameter("password");				
		Connection con=DatabaseConnectionFactory.createConnection();		
		ResultSet set=null;
		int i=0;
		try
		{
		 Statement st=con.createStatement();
		 String sql = "Select * from  users where username='"+username+"' and password='"+password+"' ";
		 		System.out.println(sql);
		 set=st.executeQuery(sql);
		 while(set.next())
		 {
			 i=1;
		 }
		 if(i!=0)
		 {   HttpSession session=request.getSession();
		     session.setAttribute("user",username);
			 RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/jsps/home.jsp");
			 rd.forward(request, response);

		 }
		 else
		 {   request.setAttribute("errorMessage","Invalid username or password");
			 RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/jsps/login.jsp");
			 rd.forward(request, response);
		 }
		}catch(SQLException sqe){System.out.println("Error : While Fetching records from database");}
		try
		{
		 con.close();	
		}catch(SQLException se){System.out.println("Error : While Closing Connection");}
	}

MainController for the Application

It is the MainController where we have written the code to redirect the user to appropriate page according to the incoming request url.

@WebServlet(urlPatterns = { "/login", "/register", "/takeExam", "/logout" })
public class MainController extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

		String applicationContextPath = request.getContextPath();

		if (request.getRequestURI().equals(applicationContextPath + "/")) {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/WEB-INF/jsps/home.jsp");
			dispatcher.forward(request, response);
		} else if (request.getRequestURI().equals(
				applicationContextPath + "/login")) {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/WEB-INF/jsps/login.jsp");
			dispatcher.forward(request, response);
		} else if (request.getRequestURI().equals(
				applicationContextPath + "/register")) {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/WEB-INF/jsps/register.jsp");
			dispatcher.forward(request, response);
		} else if (request.getRequestURI().equals(
				applicationContextPath + "/takeExam")) {
			request.getSession().setAttribute("currentExam", null);

			String exam = request.getParameter("test");
			request.getSession().setAttribute("exam", exam);

			System.out.println(request.getSession().getAttribute("user"));
			if (request.getSession().getAttribute("user") == null) {
				request.getRequestDispatcher("/login").forward(request,
						response);

			} else {
				RequestDispatcher dispatcher = request
						.getRequestDispatcher("/WEB-INF/jsps/quizDetails.jsp");
				dispatcher.forward(request, response);
			}
		} else if (request.getRequestURI().equals(
				applicationContextPath + "/logout")) {
			request.getSession().invalidate();
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/WEB-INF/jsps/home.jsp");
			dispatcher.forward(request, response);
		}

	}

}

Implementing the Logout Functionality

Once the user clicks on logout, link session is invalidated and all the objects bind in the session are removed.

request.getSession().invalidate();

Storing the Quiz questions

Note that we have stored the questions in separate XML files, not in the database.

< quiz>
  < title>MongoDB Quiz (01/09/2015)< /title>
    < questions>    
      < question>
        < quizquestion>MongoDB is a < /quizquestion>
        < answer>Relational Database< /answer>
        < answer>Object Relational Database< /answer>
        < answer>Graph Database< /answer>
        < answer>Document Database< /answer>
        < correct>3< /correct>
      < /question>

      < question>
        < quizquestion>What is the name of MongoDB server ?< /quizquestion>
        < answer>mongoserver< /answer>
        < answer>mongod< /answer>
        < answer>mongodb< /answer>
        < answer>mongo< /answer>
        < correct>1< /correct>
      < /question>

      < question>
        < quizquestion>What is the name of MongoDB client ?< /quizquestion>
        < answer>mongo< /answer>
        < answer>mongod< /answer>
        < answer>mongodb< /answer>
        < answer>mongo-client< /answer>
        < correct>0< /correct>
      < /question>
< /questions>
< /quiz>

How to Read the Questions Stored in XML File

To read the questions from the XML file we create a document that represents the XML file containing quiz questions. Whenever the user clicks on the next or previous button we call the setQuestion(int i) method, giving the index of question that we want to read and at the same time that question is saved in an ArrayList of QuizQuestion.

How to Represent a Question?

QuizQuestion is the class that represents a single quiz question; each question will have a number, question statement, options and one correct option index.

QuizQuestion.java

public class QuizQuestion {

	int questionNumber;
	String question;
	String questionOptions[];
	int correctOptionIndex;

	public String getQuestion()
	{ 
		return question;
	}

	public int getQuestionNumber()
	{
		return questionNumber;
	}

	public void setQuestionNumber(int i)
	{
		questionNumber=i;
	}

	public int getCorrectOptionIndex()
	{
		return correctOptionIndex;
	}

	public String[] getQuestionOptions()
	{
		return questionOptions;
	}

	public void setQuestion(String s)
	{
		question=s;
	}
	public void setCorrectOptionIndex(int i)
	{
		correctOptionIndex=i;
	}
	public void setQuestionOptions(String[]s)
	{
		questionOptions=s;
	}

}

Note that since this is a web application, multiple users will be taking exams simultaneously. We have to make sure that one user’s exam does not get into another user’s exam. For example, one user might have just started Java exam and another user is on question 5 of SQL exam; we have to treat them as two separate exams. To do that we will maintain the state of each exam using session.

When the user clicks on start exam button to start the exam, we will create a new instance of exam passing the test type for eg. Java, PHP, CSS etc. So each user will have a different instance of Exam class (that represents an individual exam).

Let’s see what is there in the exam class

public class Exam {
	Document dom;
	public int currentQuestion=0;	

	public Map selections=new LinkedHashMap();
	public ArrayList questionList = new ArrayList(10);

	public Exam(String test) throws SAXException,ParserConfigurationException,IOException, URISyntaxException{
		dom=CreateDOM.getDOM(test);
	}

      // code
}

Note that to track the current question in the exam we have currentQuestion property in exam class.

Elevate your web development skills with our industry-relevant Node JS Course and stay ahead in the ever-evolving tech world.

Handling the Entire Exam

ExamController is the main control from where we control the exam. Here we save user selections (what user have answered for the question) in a Map. ExamController also lets user move through questions by clicking next and previous button, at the back end it is the ExamController which makes the function calls to retrieve questions and store user responses.

Submitting the Exam and Evaluating Exam Result

When the user clicks on finish button, ExamController calls the calculateResult() method passing the Exam object, calculateResult() compares user responses with correct option for the question and returns how many correct answers a user got.

public int calculateResult(Exam exam){
		int totalCorrect=0;
		Map<Integer,Integer> userSelectionsMap=exam.selections;		
		List userSelectionsList=new ArrayList(10);
		for (Map.Entry<Integer, Integer> entry :userSelectionsMap.entrySet()) {
			userSelectionsList.add(entry.getValue());
		}
		List questionList=exam.questionList;
		List correctAnswersList=new ArrayList(10);
		for(QuizQuestion question: questionList){
			correctAnswersList.add(question.getCorrectOptionIndex());
		}

		for(int i=0;i<selections.size();i++){
			System.out.println(userSelectionsList.get(i)+" --- "+correctAnswersList.get(i));
			if((userSelectionsList.get(i)-1)==correctAnswersList.get(i)){
				totalCorrect++;
			}
		}

		System.out.println("You Got "+totalCorrect+" Correct");	
		return totalCorrect;
	}

Note that until now each of our question has 4 options and there is no timer for the quiz. In the upcoming posts we are going to extend this online quiz application and will include the following functionalities :

1. Each quiz can have different number of questions

2. Each question can have different number of options

3. A question can have multiple correct options

4. Implementing a timer for the quiz

5. Maintaining a history of the user; like how many tests a user have taken in the past and his score

6. Randomizing the order of questions presented to the user

7. Giving the user option to review his answers before submitting the test for evaluation

8. A dropdown box to jump to any question in between the test rather then clicking next button multiple times.

As always you can download the code, change it as you like. That’s the best way to understand the code. If you have any question or suggestion please comment below.

Click on the Download button to download the code.

[buttonleads form_title=”Download Code” redirect_url=https://edureka.wistia.com/medias/akdu7ycjex/download?media_file_id=65416744 course_id=44 button_text=”Download Code”]

 

Got a question for us? Please mention it in the comments section and we will get back to you.

Related Posts:

Creating Online Quiz Application Part 2 – Implementing Countdown Timer

Creating Online Quiz Application Part 3 – Quiz Review Functionality

Get Started with Java/J2EE

Unveil the Magic of Java Course With Edureka!

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 4th May,2024

4th May

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th May,2024

25th May

SAT&SUN (Weekend Batch)
View Details
Comments
165 Comments
  • Ashish Jindal says:

    when i click on any of the pages like home,register,login or any page it occur error 404 not found
    and could you show me your web.xml in brief

    • EdurekaSupport says:

      Hey Ashish, there can be multiple reasons for ERROR 404, one of them could be the extra mapping for the servlets. SInce there are two ways to map servlet, one from the mapping file other using annotations, there might be a possibility that you have been mapping in both ways.
      So please remove the mapping tags from the XML file.
      Do let us know if this works. Cheers!

  • Ashish Jindal says:

    hey could you please help me to download jstl jar file both api and implementation file.when i download from jstl site there is no file in the repository
    So, please help me

  • Ashish Jindal says:

    hey can you tell me you have added only one xml file(quiz-1.xml). but there are lot of file exist in Quizes folder in online Exam project

    • EdurekaSupport says:

      Hey Asish, thanks for checking out our blog. The file web.xml is a resource file containing all the mapping related things, for example, how one servlet class will be mapped to a particular url. So, for any jsp- servlet project, you can handle all the mapping related things using only one xml file.

      Hope this helps. Cheers!

  • Ashish Jindal says:

    hey can anyone tell me where i put Questionxml file(which have various Subjects) in this project

    • EdurekaSupport says:

      Hey Ashish, thanks for checking out our blog. Since the Question.xml is a resource file, we can keep it in the root of the project directory or we can even create one folder or package and can keep the xml file inside of that. By right clicking on the xml file we can get the path from properties option, so wherever the resource file is kept in the project we can reach that.
      Hope this helps. Cheers!

  • Yashveer Gantis says:

    Sir,
    After clicking Start Test i’am getting error.
    Please help me

    • EdurekaSupport says:

      Hey Yashveer, thanks for checking out our blog. There can be multiple reasons for ERROR 500, one of them could be the extra mapping for the servlets. SInce there are two ways to map servlet, one from the mapping file other using annotations, there might be a possibility that you have been mapping in both ways.
      So please remove the mapping tags from the XML file.
      Please let us know if this works. Cheers!

  • Anjay says:

    HTTP Status 500 – Unable to compile class for JSP:

    type Exception report

    message Unable to compile class for JSP:

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: Unable to compile class for JSP:

    An error occurred at line: 16 in the jsp file: /exam.jsp
    Exam cannot be resolved to a type
    13:
    14:
    15:
    19: Current Question ${sessionScope.quest.questionNumber+1} / 10

    Stacktrace:
    org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:102)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:198)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:450)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:361)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:336)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:323)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:580)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:356)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    myquizz.ExamController.doPost(ExamController.java:113)
    myquizz.ExamController.doGet(ExamController.java:26)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

    note The full stack trace of the root cause is available in the Apache Tomcat/8.0.21 logs.
    Apache Tomcat/8.0.21

    How to resolve this Problem anyone who know please tell me…….

    • EdurekaSupport says:

      Hey Anjay, thanks for checking out our blog. This is an error which you are getting due to tomcat version incompatibility with jdk 1.8 . We recommend you to use apache tomcat 7.0.50 or above to solve this issue

      Hope this helps. Cheers!

      • Anjay says:

        I am already using apache-tomcat-8.0.21,but still above error occurs…

        • EdurekaSupport says:

          Hey Anjay, there might be a possibility that you’re using the old version of JSP container (version should be higher). Or You might have wrong servlet version in web.xml, for example JSP 2.1 goes hand in hand with Servlet 2.5, so your web.xml should at least be declared as per the Servlet 2.5 spec (you still need a Servlet 2.5 / JSP 2.1 capable servlet container for that).
          Or, you’ve duplicated the older versioned appserver-specific libraries into webapp’s /WEB-INF/lib, like servlet-api.jar, jsp-api.jar and so on. You should never do that. It will only result in classloading collisions. Get rid of them in your webproject and leave/untouch them there in the appserver. Please check the above points and let us know if the issue persists. Hope this helps. Cheers!

          • geet says:

            Hello sir i am also getting same error, and i have all this version update still

  • vamshi krishna says:

    here its asking about cloud foundry account

    • EdurekaSupport says:

      +Vamsi Krishna, thanks for checking out our blog. It should not ask for the cloud foundry account if you are doing it in your localhost. In case you want to make it as a live website online, you may need a cloud account or web hosting account. Hope this helps. Cheers!

  • Badrinarayanan S says:

    I’m getting this error. Can you help me over it??

    HTTP Status 404 –

    type Status report

    message

    description The requested resource is not available.

    Apache Tomcat/8.0.3

    • EdurekaSupport says:

      Hey Badrinarayanan, thanks for checking out our blog. With regard to the error your facing, please check your database connection. The values that you are trying to insert in the table from JSP are not loading in database.
      Do let us know if you are still getting the same error. Hope this helps. Cheers!

  • Suhail says:

    How can I change the code to make it take quiz from database instead of document? I’m using MySql database

    • EdurekaSupport says:

      Hey Suhail, thanks for checking out the blog. We can use jdbc connection to connect to sql in java. Then we have to create a table with quiz no id and quiz question. Later on we can fetch the question from the database.To establish the jdbc connection the following steps are required :Import JDBC Packages: Add import statements to your Java program to import required classes in your Java code.
      import java.sql.* ; // for standard JDBC programs
      import java.math.* ; // for BigDecimal and BigInteger support
      Register JDBC Driver: This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests.
      try {
      Driver myDriver = new oracle.jdbc.driver.OracleDriver();
      DriverManager.registerDriver( myDriver );
      }
      catch(ClassNotFoundException ex) {
      System.out.println(“Error: unable to load driver class!”);
      System.exit(1);
      }
      Database URL Formulation: This is to create a properly formatted address that points to the database to which you wish to connect.
      three overloaded DriverManager.getConnection() methods −
      getConnection(String url)
      getConnection(String url, Properties prop)
      getConnection(String url, String user, String password)
      Create Connection Object: Finally, code a call to the DriverManager object’sgetConnection( ) method to establish actual database connection.

      Hope this helps. Cheers!

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Creating an Online Quiz Application Using JSP Servlet

edureka.co