Anna University Regional Campus, Coimbatore

Department of Computer Science and Engineering

Experiment 6A - Online Examination






AIM:

To write a Java servlet program to conduct an online examination and display the student mark list available in a database.

ALGORITHM:

  1. Create an HTML file with a form tag for login.
  2. The form tag should have action="http://localhost:8080/example/servlet/exam".
  3. Create two text boxes (Name & Seat Number) for user input.
  4. Define 5 questions in a True or False model and close all tags.
  5. Import the necessary packages and declare the servlet class.
  6. Declare the connection, statement, and result set objects for JDBC.
  7. Use methods to check the connection with the JDBC:ODBC driver.
  8. Insert data into the corresponding table using SQL queries.
  9. Update the database with executeUpdate() method.
  10. Display the results in a formatted HTML file after compilation.

PROGRAM:

HTML Form (login.jsp)

<html>
<head>
    <title>Login</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
        
    		font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    		background: linear-gradient(131deg, #2c3e56, #37495e); 
    		background-image: radial-gradient(circle, rgba(255, 255, 255, 0.3) 25%, rgba(0, 0, 0, 0.4) 60%); 
    		display: flex;
    		justify-content: center;
    		align-items: center;
    		height: 100vh;
    		margin: 0;
		}

        .Container {
            background-color: white;
            padding: 40px;
            width: 100%;
            max-width: 360px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        h2 {
            text-align: center;
            color: #333;
            font-size: 28px;
            margin-bottom: 30px;
            font-weight: 600;
        }
        form {
            display: flex;
            flex-direction: column;
        }
        input[type="text"],
        input[type="password"] {
            padding: 12px;
            margin-bottom: 18px;
            border: 2px solid #ccc;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }
        input[type="text"]:focus,
        input[type="password"]:focus {
            border-color: #6e7bff;
            outline: none;
        }
        button {
            background-color: #6e7bff;
            color: white;
            padding: 12px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        button:hover {
            background-color: #5a6cc9;
        }
        p {
            text-align: center;
            font-size: 14px;
            color: #e74c3c;
            margin-top: 10px;
        }
        .forgot-password {
            text-align: center;
            font-size: 14px;
            color: #777;
            margin-top: 20px;
        }
        .forgot-password a {
            color: #6e7bff;
            text-decoration: none;
            font-weight: 600;
        }
        .forgot-password a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <form action="login" method="post">
        <label>Username:</label>
        <input type="text" name="username" required><br><br>
        <label>Password:</label>
        <input type="password" name="password" required><br><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>
            

HTML Form (Exam.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List, java.util.Map" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Exam</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(#ff7e5f, #feb47b, #86a8e7, #5f78a3);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            color: #444;
        }

        .exam-container {
            background-color: #ffffff;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 950px;
            padding: 40px;
            box-sizing: border-box;
            overflow-y: auto;
        }

        h2 {
            text-align: center;
            font-size: 36px;
            color: red;
            margin-bottom: 30px;
            font-weight: 700;
            letter-spacing: 1px;
        }

        fieldset {
            border: 2px solid #3498db;
            margin-bottom: 25px;
            padding: 25px;
            background-color: #fafafa;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        legend {
            font-size: 22px;
            font-weight: 600;
            color: black;
            margin-bottom: 18px;
            padding-left: 10px;
            padding-right: 10px;
            text-align: center;
        }

        .options {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .option {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 18px;
        }

        input[type="radio"] {
            accent-color: #3498db;
            cursor: pointer;
        }

        label {
            font-size: 16px;
            color: #555;
        }

        .submit-btn {
            display: block;
            width: 100%;
            padding: 18px;
            background-color: #3498db;
            color: white;
            font-size: 20px;
            text-align: center;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            margin-top: 20px;
        }

        .submit-btn:hover {
            background-color: #2980b9;
        }

        .submit-btn:active {
            background-color: #1c5d85;
        }

        @media (max-width: 768px) {
            .exam-container {
                padding: 25px;
            }

            h2 {
                font-size: 30px;
            }

            .submit-btn {
                font-size: 18px;
                padding: 15px;
            }
        }

        @media (max-width: 480px) {
            h2 {
                font-size: 26px;
            }

            .submit-btn {
                font-size: 16px;
                padding: 12px;
            }
        }
    </style>
</head>
<body>
    <div class="exam-container">
        <h2>Online Exam</h2>
        <form action="result" method="post">
            <%
                List<Map<String, Object>> questions = (List<Map<String, Object>>) request.getAttribute("questions");
                for (Map<String, Object> question : questions) {
                    int id = (int) question.get("id");
                    String text = (String) question.get("question");
                    String[] options = (String[]) question.get("options");
            %>
                <fieldset>
                    <legend><%= text %></legend>
                    <div class="options">
                        <%
                            for (int i = 0; i < options.length; i++) {
                        %>
                            <div class="option">
                                <input type="radio" name="<%= id %>" value="<%= i + 1 %>" required>
                                <label for="<%= id %>_<%= i + 1 %>"><%= options[i] %></label>
                            </div>
                        <%
                            }
                        %>
                    </div>
                </fieldset>
            <% } %>
            <button type="submit" class="submit-btn">Submit Exam</button>
        </form>
    </div>
</body>
</html>
			

HTML Form (Result.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Examination Results</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(to bottom right, #fbc2eb, #a6c1ee); 
            color: #444;
            margin: 0;
            padding: 0;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        h2 {
            color: #4CAF50;
            font-size: 30px;
            margin-bottom: 20px;
            text-transform: uppercase;
            font-weight: 600;
        }

        .result-box {
            background-color: #ffffff;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            padding: 30px;
            max-width: 450px;
            width: 100%;
            text-align: center;
            box-sizing: border-box;
            transition: transform 0.3s ease-in-out;
        }

        .result-box:hover {
            transform: translateY(-10px); 
        }

        .score {
            font-weight: 700;
            font-size: 36px;
            color: #e74c3c;
            display: inline-block;
            margin-top: 15px;
        }

        .result-box p {
            font-size: 18px;
            color: #555;
            margin-top: 15px;
        }

        .username {
            font-weight: 600;
            color: #3498db;
        }

        .button-container {
            margin-top: 20px;
        }

        .back-btn {
            padding: 12px 24px;
            background-color: #3498db;
            color: white;
            font-size: 18px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .back-btn:hover {
            background-color: #2980b9;
        }
    </style>
</head>
<body>
    <div class="result-box">
        <h2>Examination Results</h2>
        <p>Hello, <span class="username"><%= session.getAttribute("username") %></span>,</p>
        <p>You have achieved a score of <span class="score"><%= request.getAttribute("score") %></span> points.</p>
        
        <div class="button-container">
			<button class="back-btn" onclick="window.location.href='login.jsp'">Go Back to Home</button>
        </div>
    </div>
</body>
</html>
			

Servlet Code (LoginServlet.java)

import java.io.IOException;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/examdb", "root", "password");
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username=? AND password=?")) {
            stmt.setString(1, username);
            stmt.setString(2, password);
            ResultSet rs = stmt.executeQuery();
            
            if (rs.next()) {
                HttpSession session = request.getSession();
                session.setAttribute("username", username);
                response.sendRedirect("exam.jsp");
            } else {
                response.sendRedirect("login.jsp?error=1");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
            

Servlet Code (ExamServlet.java)

<package com.exam.servlet;>

<import com.exam.dao.DBConnection;>
<import javax.servlet.*;>
<import javax.servlet.http.*;>
<import java.io.IOException;>
<import java.sql.*;>
<import java.util.*;>

<public class ExamServlet extends HttpServlet> {

    <private static final long serialVersionUID = 1L;>

    <@Override>
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Map<String, Object>> questions = new ArrayList<>();
        try (Connection conn = DBConnection.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM questions")) {

            while (rs.next()) {
                Map<String, Object> question = new HashMap<>();
                question.put("id", rs.getInt("id"));
                question.put("question", rs.getString("question"));
                question.put("options", new String[] {
                    rs.getString("option1"),
                    rs.getString("option2"),
                    rs.getString("option3"),
                    rs.getString("option4")
                });
                questions.add(question);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.setAttribute("questions", questions);
        RequestDispatcher dispatcher = request.getRequestDispatcher("exam.jsp");
        dispatcher.forward(request, response);
    }
}
		

Servlet Code (ResultServlet.java)

<package com.exam.servlet;>

<import com.exam.dao.DBConnection;>
<import javax.servlet.*;>
<import javax.servlet.http.*;>
<import java.io.IOException;>
<import java.sql.*;>

<public class ResultServlet extends HttpServlet> {
    
    <private static final long serialVersionUID = 1L;>

    <@Override>
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int score = 0;
        int totalQuestions = 0;
        HttpSession session = request.getSession(false); 
        String username = (String) session.getAttribute("username");

        try (Connection conn = DBConnection.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM questions")) {

            while (rs.next()) {
                totalQuestions++; 

                int questionId = rs.getInt("id");
                int correctOption = rs.getInt("correct_option");

                String userAnswer = request.getParameter(String.valueOf(questionId));

                if (userAnswer != null && Integer.parseInt(userAnswer) == correctOption) {
                    score++;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        request.setAttribute("score", score);
        request.setAttribute("totalQuestions", totalQuestions);
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement("INSERT INTO result (name, score) VALUES (?, ?)")) {
            
            stmt.setString(1, username); 
            stmt.setInt(2, score); 

            stmt.executeUpdate();
            
        } catch (SQLException e) {
            e.printStackTrace();
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher("result.jsp");
        dispatcher.forward(request, response);
    }
}
		

Java Code (DBConnection.java)

<package com.exam.dao;>

<import java.sql.Connection;>
<import java.sql.DriverManager;>
<import java.sql.SQLException;>

<public class DBConnection> {
    <private static final String URL = "jdbc:mysql://localhost:3306/onlineExam";>
    <private static final String USER = "root";>
    <private static final String PASSWORD = "";>

    <public static Connection getConnection() throws SQLException> {
        <try>
            <Class.forName("com.mysql.cj.jdbc.Driver");>
        </try>
        <catch (ClassNotFoundException e)> {
            e.printStackTrace();
        }
        <return DriverManager.getConnection(URL, USER, PASSWORD);>
    }
}
		

Sample Output:

Output Image 1 Output Image 2 Output Image 3 Output Image 4

RESULT:

Thus, the online examination system using servlets has been successfully developed and tested.