[go: up one dir, main page]

0% found this document useful (0 votes)
24 views17 pages

AJP Lab Programs Part 2

The document contains Java servlet code for three different functionalities: a HelloServlet that displays 'Hello World' and the current date, a LoginServlet that validates user login credentials and responds accordingly, and a VisitCountServlet that tracks the number of times a user has visited the servlet using cookies. Additionally, it includes a KBC game servlet that presents multiple-choice questions, tracks the user's score, and prevents backtracking. Each servlet is implemented with appropriate methods for handling HTTP requests and responses.

Uploaded by

ramanathan.dsm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views17 pages

AJP Lab Programs Part 2

The document contains Java servlet code for three different functionalities: a HelloServlet that displays 'Hello World' and the current date, a LoginServlet that validates user login credentials and responds accordingly, and a VisitCountServlet that tracks the number of times a user has visited the servlet using cookies. Additionally, it includes a KBC game servlet that presents multiple-choice questions, tracks the user's score, and prevents backtracking. Each servlet is implemented with appropriate methods for handling HTTP requests and responses.

Uploaded by

ramanathan.dsm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

7. Create Servlet That Prints ‘Hello World’ and Today’s Date.

HelloServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
* Servlet implementation class HelloServlet
*/
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

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

/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");

// Get the current date and time


SimpleDateFormat formatter = new
SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
Date date = new Date();

// Get the response's writer


PrintWriter out = response.getWriter();

// Print Hello World and current date to the HTML response


out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("<p>Today's date and time is: " +
formatter.format(date) + "</p>");
out.println("</body></html>");
}

/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}}
8. Create Servlet for login page, if the username and password is correct then
prints message “Hello username” else a message”login failed”

Login.html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Login Form</title>

</head>

<body>

<h2>Login Form</h2>

<form action="LoginServlet" method="post">

<label for="username">Username:</label>

<input type="text" id="username" name="username"


required><br><br>

<label for="password">Password:</label>

<input type="password" id="password" name="password"


required><br><br>

<input type="submit" value="Login">

</form>
</body>
</html>

LoginServlet.java

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

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

/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();

String correctUsername = "Ram";


String correctPassword = "Roever123";
if (username.equals(correctUsername) &&
password.equals(correctPassword)) {
out.println("<html><body>");
out.println("<h1>Hello, " + username + "!</h1>");
out.println("</body></html>");
} else {
out.println("<html><body>");
out.println("<h1>Login failed. Invalid username or
password.</h1>");
out.println("</body></html>");
}

}
}
9. Create Servlet that uses cookies to store the number of times a user has
visited the servlet.

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
* Servlet implementation class VisitCountServlet
*/
public class VisitCountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

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

/**
* @see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Get all cookies from the request


Cookie[] cookies = request.getCookies();
int visitCount = 0;
boolean found = false;

// Check if there's already a cookie for visit count


if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("visitCount")) {
visitCount = Integer.parseInt(cookie.getValue());
found = true;
break;
}
}
}

// If no visitCount cookie is found, this is the first visit


if (!found) {
visitCount = 1;
} else {
// Increment visit count if cookie exists
visitCount++;
}

// Create or update the visitCount cookie


Cookie visitCountCookie = new Cookie("visitCount",
Integer.toString(visitCount));
visitCountCookie.setMaxAge(60 * 60 * 24 * 365); // Cookie will
expire in 1 year
response.addCookie(visitCountCookie);

// Display the visit count to the user


out.println("<html><body>");
out.println("<h1>Welcome!</h1>");
out.println("<p>You have visited this page " + visitCount + "
times.</p>");
out.println("</body></html>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

}
10. Create a Servlet for demo of KBC game. There will be continuous two or
three pages with different MCQs. Each correct answer carries Rs. 10000. At
the end as per user’s selection of answers total prize he won should be
declared. User should not be allowed to backtrack.

import jakarta.servlet.ServletException;

import jakarta.servlet.annotation.WebServlet;

import jakarta.servlet.http.HttpServlet;

import jakarta.servlet.http.HttpServletRequest;

import jakarta.servlet.http.HttpServletResponse;

import jakarta.servlet.http.HttpSession;

import java.io.IOException;

import java.io.PrintWriter;

/**

* Servlet implementation class KBCServlet

*/

public class KBCServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

// Array of questions

private String[] questions = {


"Q1: What is the capital of India?",

"Q2: Who is known as the Father of the Nation in India?",

"Q3: What is the currency of Japan?"

};

// Array of answer options

private String[][] options = {

{"New Delhi", "Mumbai", "Kolkata", "Chennai"},

{"Mahatma Gandhi", "Jawaharlal Nehru", "Subhas Chandra Bose",


"Bhagat Singh"},

{"Yen", "Dollar", "Rupee", "Pound"}

};

// Array of correct answers (indices corresponding to the options array)

private int[] correctAnswers = {0, 0, 0}; // Correct answer index for each
question

/**

* @see HttpServlet#HttpServlet()

*/

public KBCServlet() {

super();
// TODO Auto-generated constructor stub

/**

* @see HttpServlet#doGet(HttpServletRequest request,


HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

// TODO Auto-generated method stub

// Get the current session or create a new one

HttpSession session = request.getSession(true);

// Get the current question number

Integer currentQuestion = (Integer)


session.getAttribute("currentQuestion");

if (currentQuestion == null) {

currentQuestion = 0;

session.setAttribute("currentQuestion", currentQuestion);

session.setAttribute("score", 0);

// Generate the MCQ form for the current question

response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<html><body>");

out.println("<h1>Welcome to KBC Game!</h1>");

// If all questions have been answered, show the final score

if (currentQuestion >= questions.length) {

int score = (Integer) session.getAttribute("score");

out.println("<h2>Congratulations! You've completed the


game.</h2>");

out.println("<h3>Total prize: Rs. " + score + "00</h3>");

session.invalidate(); // End the session

} else {

// Display the current question and options

out.println("<h2>" + questions[currentQuestion] + "</h2>");

out.println("<form method='post' action='KBCServlet'>");

for (int i = 0; i < options[currentQuestion].length; i++) {

out.println("<input type='radio' name='answer' value='" + i + "'


required> " + options[currentQuestion][i] + "<br>");

out.println("<input type='submit' value='Submit Answer'>");

out.println("</form>");

}
out.println("</body></html>");

/**

* @see HttpServlet#doPost(HttpServletRequest request,


HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

// Get the session

HttpSession session = request.getSession(false);

// Get the current question number

Integer currentQuestion = (Integer)


session.getAttribute("currentQuestion");

// Get the user's selected answer

int selectedAnswer = Integer.parseInt(request.getParameter("answer"));

// Get the current score from the session

int score = (Integer) session.getAttribute("score");

// Check if the answer is correct

if (selectedAnswer == correctAnswers[currentQuestion]) {
score += 1; // Each correct answer adds Rs. 10,000

// Update the session with the new score and increment the question
number

session.setAttribute("score", score);

currentQuestion++;

session.setAttribute("currentQuestion", currentQuestion);

// Redirect back to the same servlet to display the next question

response.sendRedirect("KBCServlet");

You might also like