Tuesday, 7 January 2014

Sample Onlinetest Project using Servlet and JSP

Online test consist of three screens
1. LoginPage.jsp
2. Exam.jsp
3. scoreDisplay.jsp

After successfull Login Questions will be displayed 5 questions atlast we can submit the exam.The scoreDisplay screen is shown with correct answers.

Database Screen shots:onlinetest
users
question

answer
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 >
  <welcome-file-list>
    <welcome-file>LoginPage.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Sample</servlet-name>
    <servlet-class>com.DAO.LohinServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Sample</servlet-name>
    <url-pattern>/loginverify</url-pattern>
  </servlet-mapping>
   <servlet>
    <servlet-name>Sample1</servlet-name>
    <servlet-class>com.DAO.AnsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Sample1</servlet-name>
    <url-pattern>/arrverify</url-pattern>
  </servlet-mapping>
</web-app>
 
LoginPage.jsp 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Login Page</title>
  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script type="text/javascript"> 
  $(document).ready(function(){
 localStorage.clear();
 })
 </script>
</head>

<body bgcolor="#E6E6FF">
<h3>
<center>
<h2>Login</h2>
<form action="loginverify" method="get">
<br/> Username:<input type="text"  name="uname"/>
<br/>Password:<input type="password"  name="pswd"/>
<br/><input type="submit" value="submit" />
<br/><a href="register.jsp" >Register Here</a>
</form>
</center>
</h3>
</body>
</html>
 
LohinServlet.java 
package com.DAO;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.Beans.Users;

public class LohinServlet extends HttpServlet {

/**
 * 
 */
 private static final long serialVersionUID = -6423051009614465001L;
   /**
   * Constructor of the object.
   */
   public LohinServlet() {
 super();
   }
   /**
   * Destruction of the servlet. <br>
   */
   public void destroy() {
 super.destroy(); // Just puts "destroy" string in log
 // Put your code here
   }
   /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   * 
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
   public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
   throws ServletException, IOException {
   response.setContentType("text/html");  
         PrintWriter out = response.getWriter();  
  Users users=new Users();
  users.setUsername(request.getParameter("uname"));
  users.setPassword(request.getParameter("pswd"));
  Integer bvalue=0;
 try {
   bvalue = LoginDAO.validateLogin(users);
 } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
 }
 if(bvalue!=0){
  users.setUserId(bvalue);
  Integer uidVal=users.getUserId();
  HttpSession session=request.getSession();
  session.setAttribute("CurrentSessionUser", users);
  response.sendRedirect("Exam.jsp?i=0&uidVal="+uidVal); 
 }else{
   out.print("<center>");  
          out.print("Sorry UserName or Password Error!");  
   RequestDispatcher rd=
          request.getRequestDispatcher("/LoginPage.jsp");  
   rd.include(request, response);  
   //response.sendRedirect("LoginPage.jsp?");
 }
 }
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
  System.out.println("In Inits");
 }

}


LoginDAO.java 

package com.DAO;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.Beans.Users;
import com.Connection.ConnectionProvider;


public class LoginDAO {

 public static Integer validateLogin(Users users) throws Exception{
  Connection con=ConnectionProvider.getConn();
  Boolean exist;
  int uid=0;
  try {
    java.sql.PreparedStatement ps=
     con.prepareStatement(
     "select * from Users where username=? and password=?");
    ps.setString(1,users.getUsername());
    ps.setString(2,users.getPassword());
    ResultSet rs=ps.executeQuery();
    while(rs.next()){
    uid=rs.getInt("USER_ID");
    }
    return uid;
  }catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   throw e;
  }
}
}
 
 Exam.jsp
<%@ page language="java"
  contentType="text/html; 
  charset=windows-1256" 
  pageEncoding="UTF-8"
  import="com.DAO.QuestionDAO" 
  import="com.Beans.Users" %>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Exam</title>
 <script type="text/javascript" src="js/jquery.min.js"></script>
 <script type="text/javascript"> 
 var myAns = new Array();
var ival="<%= request.getParameter ("i") %>";
var uidVal="<%= request.getParameter ("uidVal") %>";
$(document).ready(function(){

if(ival=="0")
   document.getElementById('butPrevious').disabled = true; 
else if(ival=="4")
  document.getElementById('butNext').disabled = true; 
if(ival>=0 && ival<5){
    var cell = document.getElementById(localStorage.getItem(ival));
    cell.style.background = "green";
 }
    var selectedOpt="selectedOpt";
    var val=localStorage.getItem(ival);
    document.getElementById(selectedOpt+val.charAt(3)).checked = true;
})

function openPrevoius()
 {
 if(ival>0){
   ival--;
   window.location.href = 
   "http://localhost:8400/OLTest/Exam.jsp?i="+ival+"&uidVal="+uidVal;
  }
 }
 function openNext()
 {
   if(ival<5){
   ival++;
   }
   if(ival!=null){
     if(ival<5)
     window.location.href = 
    "http://localhost:8400/OLTest/Exam.jsp?i="+ival+"&uidVal="+uidVal;
    }
}

function openSubmit(id)
{
   var theOpts = document.getElementsByName("selectedOpt");
   for(var i=0;i<theOpts.length;i++){
   if(theOpts[i].checked){
     theOpts[i].value;
     var cell = document.getElementById(id);
     cell.style.background = "green";
     if(ival=="0"){
       localStorage.clear();
     }
     localStorage.setItem(  ival,id );
     if(ival=="4"){
     for(var i=0;i<5;i++){
       myAns[i]=localStorage.getItem(i);
     }
  }
  }else{
     theOpts[i].value;
     var opt="opt";
     var cell = document.getElementById(opt+i);
     cell.style.background = "#E6E6FF";
  }
 }
}
function clickSubmit(){


var uidVal="<%= request.getParameter ("uidVal") %>";
var arr=new Array();

for(var i=0;i<5;i++){
arr[i]=localStorage.getItem(i);
}
    arr;
    var json = arr;
$.ajax({
            url:"arrverify",
            type:"POST",
            dataType:'json',
            data: {json:json,uid:uidVal},
            success: function(data){
             window.location.href = "scoreDisplay.jsp";
            } 


        });
  
}

</script>

</head>

<body bgcolor="#E6E6FF">
<center>
 
 <% Users currentUser =
 (Users)(session.getAttribute("CurrentSessionUser"));%> 
 <br/>Welcome <%= currentUser.getUsername() %>
 <%= currentUser.getUserId() %>

<form method="post" id="frm">
  <center>
  <table border="1" width="30%" cellpadding="5" id="tableId">
  <jsp:useBean id="Quest" class="com.Beans.Question" scope="application"/>
  <jsp:useBean id="QuestDAO" class="com.DAO.QuestionDAO" scope="application" />
  <jsp:useBean id="AnswerDAO" class="com.DAO.AnswerDAO" scope="application" />
   <% java.util.List<com.Beans.Question> list =  
   new java.util.ArrayList<com.Beans.Question>(); %>
   <%  int i= Integer.parseInt(request.getParameter("i"));
   if(i==0){
 list=QuestDAO.getQuestions();
 session.setAttribute("list",list);
   }else{
  list= (java.util.List<com.Beans.Question>)session.getAttribute("list");
    }
    %>
         
  <thead>
  <tr>
      <th id="ram"  ><%= request.getParameter("i") %></th>
      <th ><%=  list.get(i).getQuestion() %></th>
  </tr>
  </thead>
  <tbody>
  <tr>
      <td id="opt0" onclick="openSubmit('opt0')">
      <input type="radio" id="selectedOpt0" name="selectedOpt" > 
      <%=  list.get(i).getOpt1() %>
      </td>
      <td id="opt1" onclick="openSubmit('opt1')">
      <input type="radio" id="selectedOpt1" name="selectedOpt" > 
      <%=  list.get(i).getOpt2() %>
      </td>
   </tr>
   <tr>
      <td id="opt2" onclick="openSubmit('opt2')">
     <input type="radio" id="selectedOpt2" name="selectedOpt" > 
      <%=  list.get(i).getOpt3() %>
      </td>
      <td id="opt3" onclick="openSubmit('opt3')">
     <input type="radio" id="selectedOpt3" name="selectedOpt" > 
     <%=  list.get(i).getOpt4() %>
     </td>
   </tr>
   </tbody>
   </table>
   </center>
</form>
    <input type="button" value="Previous" name="Previous" 
          id="butPrevious" onclick="openPrevoius()" >
               &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="button" value="Submit" name="Submit" 
         id="butSubmit" onclick="clickSubmit()" >
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="button" value="Next" id="butNext" name="Next" 
           onclick="openNext()" />
        
</center>

</body>
</html>
  
 
 
AnsServlet:
package com.DAO;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

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

import org.json.JSONException;
import org.json.JSONObject;

import com.Beans.ResultDisplay;

/**
 * Servlet implementation class AnsServlet
 */

public class AnsServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#HttpServlet()
  */
  public AnsServlet() {
     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
     PrintWriter out=response.getWriter();
     String uid=request.getParameter("uid");
     String[] answers = request.getParameterValues("json[]");
     List<ResultDisplay> lisResult=new ArrayList<ResultDisplay>();
     try {
         lisResult=AnswerDAO.insertAns(answers,Integer.parseInt(uid));
     }catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
     }
     if(lisResult.size()>1){
 HttpSession session=request.getSession();
 session.setAttribute("resultOfUser", lisResult);
     try {
 JSONObject jobj = new JSONObject();
 String urlToRedirect = "scoreDisplay.jsp";
 jobj.put("url",urlToRedirect);
 response.getWriter().write(jobj.toString());
     }catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
     }
     }else{
 out.print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");  
        out.print("Sorry some error occured we will recover soon");  
 RequestDispatcher rd=request.getRequestDispatcher("/Exam.jsp");  
 rd.include(request, response);  
     }
     }
}
AnswerDAO.java 
package com.DAO; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.Beans.ResultDisplay; import com.Beans.Users; import com.Connection.ConnectionProvider; import com.mysql.jdbc.PreparedStatement; public class AnswerDAO { public static List<ResultDisplay> insertAns(String[] answers,int uid) throws Exception{ Connection con=ConnectionProvider.getConn(); String[] ans=new String[]{}; ans=answers; int result=0; String resultVal=""; List<ResultDisplay> lis=new ArrayList<ResultDisplay>(); try { for(int i=0;i<ans.length;i++){ String selectTableSQL = "SELECT "+ans[i]+" FROM question where QUESTION_ID=?"; java.sql.PreparedStatement preparedStatement1 = con.prepareStatement(selectTableSQL); preparedStatement1.setInt(1,(i+1)); ResultSet rs = preparedStatement1.executeQuery(); while (rs.next()) { resultVal = rs.getString(ans[i]); if(i==0){ String deleteTableSQL = "DELETE FROM answer where USER_ID=?"; java.sql.PreparedStatement preparedStatement2 = con.prepareStatement(deleteTableSQL); preparedStatement2.setInt(1,uid); int rs1 = preparedStatement2.executeUpdate(); } } String insertTableSQL = "INSERT INTO answer(ANSWER, QUESTION_ID, USER_ID) VALUES(?,?,?)"; java.sql.PreparedStatement preparedStatement = con.prepareStatement(insertTableSQL); preparedStatement.setString(1,resultVal); preparedStatement.setInt(2,(i+1)); preparedStatement.setInt(3,uid); result +=preparedStatement.executeUpdate(); System.out.println("Result"+result); if(result==5){ lis=AnswerDAO.result(uid); } } return lis; } catch (Exception e) { // TODO Auto-generated catch block throw e; } } public static List<ResultDisplay> result(int uid) throws Exception{ Connection con=ConnectionProvider.getConn(); List<ResultDisplay> resD=new ArrayList(); try { String qry= "select q.question,q.correctanswer,a.answer,a.user_id"+ "from question q,answer a where q.question_id=a.question_id and a.user_id=?"; java.sql.PreparedStatement preparedStatement=con.prepareStatement(qry); preparedStatement.setInt(1,uid); ResultSet rs = preparedStatement.executeQuery(); while(rs.next()){ ResultDisplay rd= new ResultDisplay(); rd.setQuestion(rs.getString("question")); rd.setCorrectanswer(rs.getString("correctanswer")); rd.setAnswer(rs.getString("answer")); rd.setUsers(rs.getInt("user_id")); resD.add(rd); } return resD; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw e; } } } 
 
 scoreDisplay.jsp
 
<%@page import="java.util.List"%>
<%@ page language="java"
  contentType="text/html; 
  charset=windows-1256" 
  pageEncoding="UTF-8"
  import="com.Beans.ResultDisplay" %>
<html>
<body bgcolor="#E6E6FF">
<center>
<% java.util.List<com.Beans.ResultDisplay> list = 
new java.util.ArrayList<com.Beans.ResultDisplay>(); %>
<%  list = (List<ResultDisplay>)(session.getAttribute("resultOfUser"));%> 
<table border="1" width="30%" cellpadding="5" id="tableId">
<thead>
   <tr>
   <th id="ram"  >Question</th>
   <th >Correct Answer</th>
   <th >Your Answer</th>
   </tr>
</thead>
<tbody>
  <tr>
  <td id="q0" ><%=  list.get(0).getQuestion() %></td>
  <td id="ca0" ><%=  list.get(0).getCorrectanswer()%></td>
  <td id="a0" ><%=  list.get(0).getAnswer() %></td>
  </tr>
  <tr>
  <td id="q1" ><%=  list.get(1).getQuestion() %></td>
  <td id="ca1" ><%=  list.get(1).getCorrectanswer() %></td>
  <td id="a1" ><%=  list.get(1).getAnswer() %></td>
  </tr>
  <tr>
  <td id="q2" ><%=  list.get(2).getQuestion()%></td>
  <td id="ca2" ><%=  list.get(2).getCorrectanswer() %></td>
  <td id="a2" ><%=  list.get(2).getAnswer()  %></td>
  </tr>
  <tr>
  <td id="q3" ><%=  list.get(3).getQuestion() %></td>
  <td id="ca3" ><%=  list.get(3).getCorrectanswer() %></td>
  <td id="a3" ><%=  list.get(3).getAnswer()  %></td>
  </tr>
  <tr>
  <td id="q4" ><%=  list.get(4).getQuestion() %></td>
  <td id="ca4" ><%=  list.get(4).getCorrectanswer() %></td>
  <td id="a4" ><%=  list.get(4).getAnswer()  %></td>
  </tr>
 </tbody>
</table>
</center>
</body>
</html>

5 comments:

saiful aizat said...

hi, thanks for the codes. is it possible for me to get the database file? because i wanted to see how you do the database. can u email to me at muhdsaifulaizat@gmail.com thanks

Unknown said...

where is com.Beans package

Anonymous said...

the given example is not clear. i am unable to understand and didn't get any proper output. so i am requesting you to please put some description and the related files thank you

Anonymous said...

can you kindly post the com.beans package and database structure

Unknown said...

Im creating a new project in which ul get all files to download.