0% found this document useful (0 votes)
5 views74 pages

Web Technology & Advanced Java

The document outlines practical assignments for the P.G Department of Computer Science at Dhanalakshmi Srinivasan Arts and Science College, focusing on Web Technology and Advanced Java. It includes tasks such as creating a simple calculator using RMI, various servlets for printing messages and dates, and a login page. Each assignment provides a detailed algorithm and program code for implementation during the academic year 2024-2025.

Uploaded by

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

Web Technology & Advanced Java

The document outlines practical assignments for the P.G Department of Computer Science at Dhanalakshmi Srinivasan Arts and Science College, focusing on Web Technology and Advanced Java. It includes tasks such as creating a simple calculator using RMI, various servlets for printing messages and dates, and a login page. Each assignment provides a detailed algorithm and program code for implementation during the academic year 2024-2025.

Uploaded by

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

DHANALAKSHMI SRINIVASAN ARTS AND SCIENCE (CO-EDUCATION) COLLEGE

(Affiliated to the University of Madras)

ECR, MAMALLAPURAM, Chennai-603104

P.G DEPARTMENT OFCOMPUTER SCIENCE

Web Technology & Advanced Java Practical

STUDENTNAME :

CLASS :

REGISTER NUMBER :

SEMESTER :
DHANALAKSHMI SRINIVASAN ARTS AND SCIENCE (Co-Education) COLLEGE
(Affiliated to University of Madras)

ECR, MAMALLAPURAM, CHENNAI-603104

REGISTERNUMBER :

DEPARTMENT : P.G COMPUTER SCIENCE

SUBJECT : PRACTICAL II- Web Technology & Advanced Java Practical

SUBJECT CODES :

This is to certify that this is a bonafide record of work done by


of FIRST semester in the
PRACTICAL II- Web Technology & Advanced Java Practical during the Academic
year 2024-2025.

Signature of Staff in-Charge Signature of the


HOD

Submitted for the Practical Examination held on

Internal Examiner External Examiner


Ex. No. Date Program Name Page No. Signature

Create a simple calculator application that


demonstrates the use of RMI. You are not
1
required to create GUI.

Create Servlet That Prints Hello World.


2

Create Servlet That Prints Today's Date


3

Create Servlet for login page, if the


username and password is correct then
4
prints message "Hello username" else a
message" login failed".
Create Servlet that uses cookies to store
the number of times a user has visited the
5
servlet.

Create a Servlet for demo of KBC game.


6

There will be continuous two or three


pages with different MCQs. Each correct
7 answer

Carries Rs. 10000. At the end as per user's


selection of answers total prize he won
8
should be declared. User should not be
allowed to backtrack.

Create a Servlet filter that calculates


server's response time and add it to
9
response when giving it back to client.
Create a jsp that prints hello world.
10

Create jsp that prints current date and


time.
11

Create a jsp that add and subtract two


numbers.
12

Create a jsp for login module.


13

Create a web page that prints 1 to 10


using JSTL
14

Create a custom JSP tag that prints


15 current date and time. Use this tag into
JSP page.
Ex no: 1 Calculator RMI
Date :

Aim:
To create a simple calculator application that demonstrates the use of
RMI. You are not required to create GUI.

Algorithm:

Step 1: Start the program:


Step 2:Calculatorrmi:

1. Import necessary packages: No need to import any packages since


UnicastRemoteObject and RemoteException are part of the java.rmi
package.
2. Define the CalculatorRmi class: Create a class named CalculatorRmi.
3. Extend UnicastRemoteObject: Extend the UnicastRemoteObject class
to make the CalculatorRmi class remotely accessible.
4. Implement CalculatorInterface: Implement the CalculatorInterface
interface to provide the required methods for the calculator functionality.
5. Define the constructor: Define a constructor for the CalculatorRmi
class. In this case, it's an empty constructor that also declares two integers
a and b, but this initialization 6.seems unnecessary as they are not used.
7. Implement arithmetic operations: Implement methods such as add, sub,
mul, and div to perform arithmetic operations. Each method takes two
integers as parameters and returns the result of the operation.
8. Handle remote exceptions: Declare that each method throws a
RemoteException to handle any remote communication issues.
9. Provide implementation: Write the actual implementation of each
arithmetic operation inside its respective method.

Step 3:CalciClient:

1. Import necessary packages: Import required classes from the java.rmi


and java.util packages.
2. Define the CalciClient class: Create a class named CalciClient.
3. Define the main method: Declare the main method with the signature
public static void main(String[] args) throws NotBoundException,
MalformedURLException, RemoteException.
4. Initialize Scanner object: Create a new Scanner object named sc to read
input from the user.
5. Use try-catch block: Use a try-catch block to handle exceptions.
6. Connect to the RMI server: Use Naming.lookup() to connect to the
RMI server located at "rmi://localhost:1099/Calculator".
7. Display menu options: Print a menu for the user to choose from.
8. Read user input: Read the user's choice using sc.nextInt().
9. Process user's choice: Based on the user's choice, perform the
appropriate calculation (add, sub, mul, div).
10. Display result: Print the result of the calculation.
11. Handle exceptions: Catch any exceptions that may occur during the
execution and handle them appropriately.
12. Close Scanner: Close the Scanner object after its use.

Step 4:CalciInterface:

1. Addition (add):
Step 1: Accept two integers, x and y, as input.
Step 2: Calculate the sum of x and y.
Step 3: Return the sum as the result.
2. Subtraction (sub):
Step 1: Accept two integers, x and y, as input.
Step 2: Calculate the result of subtracting y from x.
Step 3: Return the result as the output.
3. Multiplication (mul):
Step 1: Accept two integers, x and y, as input.
Step 2: Calculate the product of x and y.
Step 3: Return the product as the result.
4. Division (div):
Step 1: Accept two integers, x and y, as input.
Step 2: Check if y is zero. If yes, raise an exception (division by zero
error).
Step 3: Calculate the result of dividing x by y.
Step 4: Return the result as the output.

Step 5:CalculatorServer:
1. Import necessary packages: Import required classes from the
java.rmi.registry package.
2. Define the CalculatorServer class: Create a class named
CalculatorServer.
3. Define the main method: Declare the main method with the signature
public static void main(String[] args) throws RemoteException,
NotBoundException.
4. Create RMI registry: Use LocateRegistry.createRegistry(1099) to
create an RMI registry on port 1099.
5. Bind server object: Use r.rebind("Calculator", new CalculatorRmi()) to
bind an instance of CalculatorRmi to the RMI registry with the name
"Calculator".
6. Print server status: Print "Server is Running" to indicate that the server
is successfully running.
7. Handle exceptions: Catch any exceptions that may occur during the
execution and handle them appropriately.
stop the program:Finally,Run the code.
Program:

CalculatorRmi:

package CalculatorRmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class CalculatorRmi extends UnicastRemoteObject implements


CalculatorInterface{
public CalculatorRmi() throws RemoteException
{
int a,b;
}
public int add(int a , int b)throws RemoteException
{
return a+b;
}
public int sub(int a , int b)throws RemoteException
{
return a-b;
}
public int mul(int a , int b)throws RemoteException
{
return a*b;
}
public int div(int a , int b)throws RemoteException
{
return a/b;
}
}

CalciClient:

package CalculatorRmi;

import java.rmi.Naming;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import java.util.Scanner;

public class CalciClient {


public static void main(String[] args)throws
NotBoundException,MalformedURLException,RemoteException{
Scanner sc = new Scanner(System.in);

try {
CalculatorInterface c =
(CalculatorInterface)Naming.lookup("rmi://localhost:1099/Calculator");
System.out.println("Client is connected to server");
System.out.println("Please Enter Your Choice : \n"
+"1. add\n"
+"2. sub\n"
+"3. mul\n"
+"4. div\n");
int choice = sc.nextInt();
int x,y;
switch (choice)
{
case 1:
{
System.out.println("Enter x and y");
x=sc.nextInt();
y=sc.nextInt();
System.out.println(c.add(x, y));
break;
}
case 2:
{
System.out.println("Enter x and y");
x=sc.nextInt();
y=sc.nextInt();
System.out.println(c.sub(x, y));
break;
}
case 3:
{
System.out.println("Enter x and y");
x=sc.nextInt();
y=sc.nextInt();
System.out.println(c.mul(x, y));
break;
}
case 4:
{
System.out.println("Enter x and y");
x=sc.nextInt();
y=sc.nextInt();
System.out.println(c.div(x, y));
break;
}

} catch (Exception e) {
}

}
}

CalculatorInterface:

package CalculatorRmi;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface CalculatorInterface extends Remote {


public int add(int x, int y)throws RemoteException;
public int sub(int x, int y)throws RemoteException;
public int mul(int x, int y)throws RemoteException;
public int div(int x, int y)throws RemoteException;

CalculatorServer:

package CalculatorRmi;

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.NotBoundException;

public class
{
public static void main(String[] args) throws
RemoteException,NotBoundException{
/*
try {
Registry r =
java.rmi.registry.LocateRegistry.createRegistry(1099);
r.rebind("Calculator", new CalculatorRmi());
System.out.println("Server is Running");
} catch (Exception e) {
System.out.println("Server nt connected "+e);
}*/
Registry r = java.rmi.registry.LocateRegistry.createRegistry(1099);
r.rebind("Calculator", new CalculatorRmi());
System.out.println("Server is Running");

}
}
Output:

CalculatorServer:

run:
Server is Running

CalciClient:

run:
Client is connected to server
Please Enter Your Choice :
1. add
2. sub
3. mul
4. div

3
Enter x and y
10
5
50
BUILD SUCCESSFUL (total time: 14 seconds)

Result:
Thus the above program is executed successfully.
Ex.no: 2 Servlet to Hello World
Date:

Aim:
To create Servlet That Prints Hello World.

Algorithm:
Step1: User Interaction:
User opens the HTML page in a web browser.
Step2: Form Submission:
User clicks the "Go TO Servlet" button on the HTML page.
Step3: POST Request:
The form submits a POST request to the servlet endpoint "/hey".
Step4: Servlet Processing:
The servlet named "hey" receives the POST request.
Step5: Response Generation:
The servlet dynamically generates an HTML response with a
blinking "HELLO WORLD" text.
Step6: Response Sent:
The servlet sends the HTML response back to the user's web
browser.
Step7: Rendering:
The user's browser receives the response and renders the HTML
content.
The "HELLO WORLD" text is displayed with a blinking effect.
Program:

Index.html:

<html>
<head>
<title>Welcome</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
</head>
<body>
<form action="hey" method="post">
<input type ="submit" value="Go TO Servlet"/>
</form>
</body>
</html>

Hey.java:

package mypack;

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

@WebServlet(name = "hey", urlPatterns = {"/hey"})


public class hey extends HttpServlet {

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<html>");
out.println("<head>");
out.println("<title>hello world</title>");
out.println("<style>");
out.println(".blink {");
out.println("animation:blinker 1.5s linear infinite");
out.println("");
out.println("}");
out.println("@keyframes blinker{");
out.println("50%{");
out.println("opacity:0;");
out.println("}");
out.println("}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
out.println("<h1 class=blink> HELLO WORLD </h1>");
out.println("</body>");
out.println("</html>");

}
}

}
Output:

Result:
Thus the above program is executed successfully.
Ex.no: 3 Servlet to prints Today's Date
Date:

Aim:
To create Servlet That Prints Today's Date.

Algorithm:
Step1: start the program.
Step2: User Interaction:
User opens the HTML page in a web browser.
Step3: Form Submission:
User clicks the "Go TO Servlet" button on the HTML page.
Step4: POST Request:
The form submits a POST request to the servlet endpoint "/hey".
Step5: Servlet Mapping:
The servlet is mapped to the URL pattern "/currdate" using the
@WebServlet annotation.
Step6: Request Processing:
When a request is made to the "/currdate" endpoint, either via GET
or POST method, the servlet's doGet or doPost method is invoked,
respectively.
Step7: Processing Request:
Both doGet and doPost methods call the processRequest method to
handle the request.
Step8: Response Generation:
Inside the processRequest method, the servlet generates an HTML
response to display the current date and time.
It creates a java.util.Date object to get the current date and time.
The response includes a <marquee> element with a <h2> heading
displaying the current date and time in white text against a black
background.
Step9: Response Sent:
The servlet sends the HTML response back to the client's browser.
Step10: Rendering:
The browser receives and renders the HTML content.
The current date and time are displayed in a scrolling marquee
format on the webpage.
Step11: finally run and execute the program.
Program:

Index.html:

<html>
<head>
<title>Date and Time</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
</head>
<body>
<form action="currDate" method="post">
<input type="submit" value="Display Date and Time"/>
</form>
</body>
</html>

Currdate:

package mypack;

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

@WebServlet(urlPatterns = {"/currdate"})
public class currdate extends HttpServlet {

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
java.util.Date date = new java.util.Date();
out.println("<body style='background-color: black;'>");
out.println("<marquee><h2 style='color: white;'>" + "Current Date
and Time: " + date.toString() + "</h2></marquee>");
out.println("</body>");

}
}

}
Output:

Result:
Thus the above program is executed successfully.
Ex.no: 4 Servlet for login page
Date:

Aim:
To create Servlet for login page, if the username and password is
correct then prints message "Hello username" else a message" login
failed".

Algorithm:
Step1: start the pogram.
Step2: HTML Form Display:
The HTML page titled "Login Servlet" is displayed in a web
browser.
It contains a form with two input fields for username and password,
and a submit button labeled "Login".
Step3: Form Submission:
User enters their username and password in the input fields.
User clicks the "Login" button.
Step4: POST Request Sent:
The form submits a POST request to the servlet endpoint
"/LoginServlet".
Step5: Servlet Processing (POST):
The servlet named "LoginServlet" receives the POST request.
It invokes the doPost method to handle the request.
Step6: Parameter Retrieval:
Inside the doPost method, the servlet retrieves the values of the
"txtID" and "txtPass" parameters sent in the request.
These parameters correspond to the username and password entered
by the user.
Step7: Authentication:
The servlet checks if the provided username and password match
the expected values ("shafrin" and "S2803" respectively).
If the credentials match, it generates an HTML response welcoming
the user with a success message.
If the credentials don't match, it generates an HTML response
indicating a login failure.
Step8: Response Sent:
The servlet sends the HTML response back to the user's browser.
Step9: Rendering:
The browser receives and renders the HTML content.
Depending on the authentication result, the browser displays either
a success message or a login failure message.
Step10: finally run and stop the program.
Program:

Index.html:

<html>
<head>
<title> Login Servlet </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
</head>
<body>
<Form action="LoginServlet" method="post">
Enter the UserName:<input type="text" name="txtID"> <br>
Enter the Password:<input type="text" name="txtPass"><br>
<input type="submit" value="Login">
<input type="reset" value="Clear All">
</form>
</body>
</html>

LoginServlet:

package mypack;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String uname = request.getParameter("txtID");
String pwd = request.getParameter("txtPass");
if (uname.equals("shafrin") && pwd.equals("S2803")) {
out.println("<h1 style='color: white; background-color: black;'>
Welcome!!! " + uname + "...Login Successfully</h1>");
} else {
out.println("<h1 style='color: red; background-color: lightgrey;'>
Login Fail!!!</h1>");
}

}
}

}
Output:

Result:
Thus the above program is executed successfully.
Ex.no: 5 Servlet uses cookies
Date:

Aim:
To create Servlet that uses cookies to store the number of times a user
has visited the servlet.

Algorithm:
Step1:start the program.
Step2: HTML Display:
The HTML page displays a simple message "Welcome user" within
a <div> element.
Step3: Cookie Handling:
When a user visits the webpage, the servlet CookiesServlet is
invoked.
It creates a new cookie named "visit" with a value indicating the
number of visits.
The cookie is added to the response.
Step4: Cookie Value Retrieval:
The servlet retrieves the value of the "visit" cookie from the request.
It parses the value to an integer to determine the number of visits.
Step5: Message Generation:
If it's the user's first visit (value of "visit" cookie is 1), the servlet
generates a welcome message in black text on a sky blue background.
If it's not the first visit, the servlet generates a message indicating the
number of visits in sky blue text on a black background.
Step6: Increment Counter:
The counter variable i is incremented to keep track of the total
number of visits.
Step7: Response Sent:
The servlet sends the HTML response back to the user's browser.
Step8: Rendering:
The browser receives and renders the HTML content.
Depending on whether it's the user's first visit or not, the browser
displays the appropriate message with the correct styling.
Step9: finally run and execute the program.
Program:

Index.html:

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
</head>
<body>
<div>TODO</div>
</body>
</html>

CookiesServlet:

package mypack;

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

public class CookiesServlet extends HttpServlet {


static int i=1;

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

Cookie c = new Cookie("visit", String.valueOf(i));


response.addCookie(c);

int j = Integer.parseInt(c.getValue());
if (j == 1) {
out.println("<div style='color: black; background-color:
skyblue;'>Welcome user</div>");
} else {
out.println("<div style='color: skyblue; background-color:
black;'>You have visited this website " + j + " times</div>");
}
i++;

}
}
}
Output:

Result:
Thus the above program is executed successfully.
Ex.no: 6 Servlet for demo of KBC game
Date:

Aim:
To create a Servlet for demo of KBC game.

Algorithm:
Step1: start the program.
Step2: HTML Display:
The HTML page displays a message "Welcome user" within a
<div> element.
Step3: Servlet Setup:
The servlet named "KBCServlet" is set up to handle requests at the
URL pattern "/KBCServlet".
Step4: Question Presentation:
When a user accesses the servlet, it presents a question along with
multiple-choice options related to the TV show "Kaun Banega
Crorepati" (KBC).
Step5: Form Submission:
The user submits their answer by filling in a text input field and
clicking the "Submit" button.
Step6: POST Request Handling:
The servlet receives the submitted form data via a POST request.
It retrieves the user's answer from the request parameter named
"userAnswer".
Step7: Answer Evaluation:
The servlet compares the user's answer to the correct answer ("C")
using a case-insensitive comparison.
Step8: Response Generation:
Based on the correctness of the user's answer, the servlet generates
an HTML response.
If the answer is correct, it displays a congratulatory message in
green text.
If the answer is incorrect, it displays a message indicating the
correct answer in red text.
Step9: Thank You Message:
Regardless of the correctness of the answer, the servlet displays a
message thanking the user for playing KBC.
Step10: Response Sent:
The servlet sends the HTML response back to the user's browser.
Step11: Rendering:
The browser receives and renders the HTML content.
Depending on the correctness of the answer, the browser displays
the appropriate message in the specified text color.
Step12: finally run and execute the program.
Program:

KBCServlet:

package mypack;

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

@WebServlet(name = "KBCServlet", urlPatterns = {"/KBCServlet"})


public class KBCServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

private static final String QUESTION = "What is the capital of


France?";
private static final String[] OPTIONS = {"A. Berlin", "B. London",
"C. Paris", "D. Rome"};
private static final String CORRECT_ANSWER = "C";

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>KBC Game</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Welcome to Kaun Banega Crorepati!</h1>");
out.println("<p>" + QUESTION + "</p>");

for (String option : OPTIONS) {


out.println("<p>" + option + "</p>");
}
out.println("<form method=\"post\">");
out.println("Your Answer: <input type=\"text\"
name=\"userAnswer\"><br>");
out.println("<input type=\"submit\" value=\"Submit\">");
out.println("</form>");

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

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String userAnswer = request.getParameter("userAnswer");
response.setContentType("text/html;charset=UTF-8");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>KBC Game Result</title>");
out.println("</head>");
out.println("<body style=\"color: white; background-color:
black;\">"); // Set font color to dark gray

if (userAnswer != null &&


userAnswer.toUpperCase().equals(CORRECT_ANSWER)) {
out.println("<p style=\"color: green;\">Congratulations! Your
answer is correct.</p>");
} else {
out.println("<p style=\"color: red;\">Sorry, that's incorrect. The
correct answer is " + CORRECT_ANSWER + "</p>");
}
out.println("<p style=\"font-style: italic;\">Thanks for playing Kaun
Banega Crorepati!</p>");
out.println("</body>");
out.println("</html>");
}

if (userAnswer != null &&


userAnswer.toUpperCase().equals(CORRECT_ANSWER)) {
out.println("<p>Congratulations! Your answer is
correct.</p>");
} else {
out.println("<p>Sorry, that's incorrect. The correct answer is "
+ CORRECT_ANSWER + "</p>");
}

out.println("<p>Thanks for playing Kaun Banega


Crorepati!</p>");
out.println("</body>");
out.println("</html>");
}
}
Output:

Result:
Thus the above program is executed successfully.
Ex.no: 7 MCQs
Date:

Aim:
To create MCQs there should be continuous two or three pages with
different MCQs. Each correct answer.

Algorithm:
Step1: start the program.
Step2: Java MCQProgram Class:
The MCQProgram class in Java handles multiple-choice questions
(MCQs) and user input.
It imports the Scanner class to read user input from the console.
Step3: Main Method:
The main method creates an instance of Scanner to read user input.
It iterates through multiple pages of questions using a loop.
Step4: Question Display:
The displayQuestions method displays questions based on the page
number passed as an argument.
Each question presents multiple options (A, B, C, D) for the user to
choose from.
Step5: User Input:
After displaying each page of questions, the program prompts the
user to enter their answer.
The user can input their answer as A, B, C, D, or "quit" to exit the
program.
Step6: Answer Checking:
The checkAnswer method checks if the user's answer matches the
correct answer for the corresponding question.
It returns true if the answer is correct and false otherwise.
Step7: Feedback:
After the user submits their answer, the program provides feedback
indicating whether the answer is correct or incorrect.
Step8: Loop Continuation:
The loop continues until the user decides to quit by entering "quit"
as their answer.
Step9: Resource Closure:
Finally, the Scanner resource is closed to release system resources.
Step10: finally run and execue the program.
Program:

import java.util.Scanner;

public class MCQProgram {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Display questions on multiple pages


for (int page = 1; page <= 3; page++) {
System.out.println("Page " + page);
displayQuestions(page);
System.out.print("Enter your answer (A, B, C, or D) or 'quit' to
exit: ");
String userAnswer = scanner.nextLine().toUpperCase();

// Check if the user wants to quit


if (userAnswer.equals("QUIT")) {
System.out.println("Exiting program.");
break;
}

// Check the user's answer


boolean isCorrect = checkAnswer(page, userAnswer);
if (isCorrect) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
}
scanner.close();
}

// Display questions based on the page number


public static void displayQuestions(int page) {
switch (page) {
case 1:
System.out.println("1. What is the capital of France?");
System.out.println(" A. London");
System.out.println(" B. Paris");
System.out.println(" C. Berlin");
System.out.println(" D. Rome");
break;
case 2:
System.out.println("2. What is the largest planet in our solar
system?");
System.out.println(" A. Earth");
System.out.println(" B. Jupiter");
System.out.println(" C. Saturn");
System.out.println(" D. Mars");
break;
case 3:
System.out.println("3. Who wrote 'Romeo and Juliet'?");
System.out.println(" A. William Shakespeare");
System.out.println(" B. Charles Dickens");
System.out.println(" C. Jane Austen");
System.out.println(" D. Mark Twain");
break;
default:
System.out.println("No questions available for page " + page);
}
}

// Check if the user's answer is correct


public static boolean checkAnswer(int page, String answer) {
switch (page) {
case 1:
return answer.equals("B");
case 2:
return answer.equals("B");
case 3:
return answer.equals("A");
default:
return false;
}
}
}
Output:

Page 1
1. What is the capital of France?
A. London
B. Paris
C. Berlin
D. Rome
Enter your answer (A, B, C, or D) or 'quit' to exit: b
Correct!
Page 2
2. What is the largest planet in our solar system?
A. Earth
B. Jupiter
C. Saturn
D. Mars
Enter your answer (A, B, C, or D) or 'quit' to exit: b
Correct!
Page 3
3. Who wrote 'Romeo and Juliet'?
A. William Shakespeare
B. Charles Dickens
C. Jane Austen
D. Mark Twain
Enter your answer (A, B, C, or D) or 'quit' to exit: a
Correct!

Result:
Thus the above program is executed successfully.
Ex.no:8 Prize
Date:

Aim:
To 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.

Algorithm:
Step1: Start the program.
Step2: Display a welcome message and inform the player that they start
with Rs. 10,000.
Step3: Initialize the variable prize to 10,000.
Step4: Ask the player the first question: "What is the capital of France?
(a) Paris (b) Rome (c) Madrid".
Step5: Accept the player's input using the Scanner class and convert it
to lowercase.
Step6: If the answer is "a":
Display "Correct! You win Rs. 2,000."
Add 2,000 to the prize.
Step7: If the answer is not "a":
Display "Incorrect! You lose Rs. 1,000."
Subtract 1,000 from the prize.
Step8: Ask the player the second question: "What is the largest
mammal? (a) Elephant (b) Blue Whale (c) Giraffe".
Step9: Repeat steps 5-7 for the second question, with Rs. 3,000 for the
correct answer and Rs. 1,500 deducted for a wrong answer.
Step10: Ask the player the third question: "Who wrote 'To Kill a
Mockingbird'? (a) Harper Lee (b) J.K. Rowling (c) Stephen King".
Step11: Repeat steps 5-7 for the third question, with Rs. 4,000 for the
correct answer and Rs. 2,000 deducted for a wrong answer.
Step12: Display the total prize amount.
Step13: Close the Scanner.
Step14: End the program.
Program:

import java.util.Scanner;

public class PrizeGame {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to the Prize Game!");


System.out.println("You start with Rs. 10,000.");

int prize = 10000;

System.out.print("Question 1: What is the capital of France? (a)


Paris (b) Rome (c) Madrid\nYour answer: ");
String answer1 = scanner.nextLine().toLowerCase();
if (answer1.equals("a")) {
System.out.println("Correct! You win Rs. 2,000.");
prize += 2000;
} else {
System.out.println("Incorrect! You lose Rs. 1,000.");
prize -= 1000;
}

System.out.print("Question 2: What is the largest mammal? (a)


Elephant (b) Blue Whale (c) Giraffe\nYour answer: ");
String answer2 = scanner.nextLine().toLowerCase();
if (answer2.equals("b")) {
System.out.println("Correct! You win Rs. 3,000.");
prize += 3000;
} else {
System.out.println("Incorrect! You lose Rs. 1,500.");
prize -= 1500;
}

System.out.print("Question 3: Who wrote 'To Kill a Mockingbird'?


(a) Harper Lee (b) J.K. Rowling (c) Stephen King\nYour answer: ");
String answer3 = scanner.nextLine().toLowerCase();
if (answer3.equals("a")) {
System.out.println("Correct! You win Rs. 4,000.");
prize += 4000;
} else {
System.out.println("Incorrect! You lose Rs. 2,000.");
prize -= 2000;
}

System.out.println("\nTotal prize: Rs. " + prize);

scanner.close();
}
}
Output:

Welcome to the Prize Game!


You start with Rs. 10,000.
Question 1: What is the capital of France? (a) Paris (b) Rome (c) Madrid
Your answer: a
Correct! You win Rs. 2,000.
Question 2: What is the largest mammal? (a) Elephant (b) Blue Whale
(c) Giraffe
Your answer: b
Correct! You win Rs. 3,000.
Question 3: Who wrote 'To Kill a Mockingbird'? (a) Harper Lee (b) J.K.
Rowling (c) Stephen King
Your answer: a
Correct! You win Rs. 4,000.

Total prize: Rs. 19000

Result:
Thus the above program is executed successfully.
Ex.no:9 Calculates server's response time
Date:

Aim:
To create a Servlet filter that calculates server's response time and add it
to response when giving it back to client.

Algorithm:
Step 1: Import Statements:
Import necessary classes from the javax.servlet package for handling
servlet-related functionality.

Step 2: Annotation:
Annotate the class with @WebFilter to indicate that it's a filter and
specify its name and the URL patterns it will intercept.

Step 3: Class Declaration:


Declare the class ResponseTimeFilter implementing the Filter
interface.

Step 4: doFilter Method:


Implement the doFilter method, which is invoked for each request
passing through the filter.

Step 5: Inside doFilter, record the start time of the request processing
using System.currentTimeMillis().
Step 6: Call chain.doFilter(request, response) to pass the request and
response objects to the next filter in the chain or the servlet if no more
filters are present.
Step 7: Calculate the response time by subtracting the start time from
the current time.
Step 8: Cast the ServletResponse to HttpServletResponse to add a
custom header containing the response time.
Step 9: Initialization Method:
Implement the init method to perform any initialization tasks when the
filter is first created. This method may be used to read configuration
parameters from the FilterConfig object if needed.

Step 10: Destruction Method:


Implement the destroy method to perform any clean-up tasks before the
filter is destroyed. This method is called by the servlet container when
the filter is being removed from service.
Program:

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

@WebFilter(filterName = "ResponseTimeFilter", urlPatterns = {"/*"})


public class ResponseTimeFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain)
throws IOException, ServletException {

long startTime = System.currentTimeMillis();

chain.doFilter(request, response);

long responseTime = System.currentTimeMillis() - startTime;

HttpServletResponse httpResponse = (HttpServletResponse)


response;
httpResponse.addHeader("X-Response-Time",
Long.toString(responseTime) + "ms");
}

// Other methods of Filter interface


@Override
public void init(FilterConfig filterConfig) throws ServletException {
// Initialization code here if needed
}

@Override
public void destroy() {
// Clean-up code here if needed
}
}
Output:

A request is processed by the web application, this filter calculates


the response time and adds it to the response headers before
sending the response back to the client.

Result:
Thus the above program is executed successfully.
Ex.no:10 Jsp for hello world
Date:

Aim:
To create a jsp that prints hello world.

Algorithm:
Step1: start the program.
Step2: Open the index.jsp file.
Step3: Set the content type to HTML and the page encoding to UTF-8.
Step4: Start the HTML document with <!DOCTYPE html>.
Step5: Open the <html> tag.
Step6: Inside the <head> section:
Step7: Set the content type meta tag to UTF-8.
Step8: Set the title of the page to "JSP Page".
Step9: Define inline CSS styles:
Step10: Set the background color of the body to black.
Step11: Set the font family to Arial or sans-serif.
Step12: Center align text.
Step13: Adjust padding to vertically center content.
Step14: Set the color of <h1> elements to white.
Step15: Close the <head> tag.
Step16: Inside the <body> section:
Step17: Display a <h1> element with the text "Hello World!".
Step18: Close the <body> and <html> tags.
Step19: End of the document.
Program:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-
8">
<title>JSP Page</title>
<style>
body {
background-color: black; /* Set background color */
font-family: Arial, sans-serif; /* Set font family */
text-align: center; /* Center align text */
padding-top: 20%; /* Adjust padding to vertically center content
*/
}
h1 {
color: white; /* Set font color */
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Output:

Result:
Thus the above program is executed successfully.
Ex.no:11 Jsp for current date and time
Date:

Aim:
To create jsp that prints current date and time.

Algorithm:

Step1: start the program:


Step2: JSP Directives
Import the java.util.Date class to use in the JSP file.
Set the content type to HTML.
Set the page encoding to UTF-8.
Step3: HTML Structure:
Start the HTML document with <!DOCTYPE html>.
Open the <html> tag.
Step4: Head Section:
Set the character encoding to UTF-8.
Set the title of the page to "Current Date and Time".
Step5: Define inline CSS styles for the body:
Set the background color to black.
Set the font family to Arial or sans-serif.
Center align text.
Adjust padding to vertically center content.
Step6: Define CSS styles for <h2> elements:
Set the font color to white.
Step7: Define CSS styles for <p> elements:
Set the font size to 18px.
Step8: Body Section:
Display a <h2> heading with the text "Current Date and Time".
Display a <p> paragraph with the text "The current date and
time is:".
Use scriptlet <%= %> to embed Java code within the HTML to
print the current date and time using the new Date() constructor.
Step9: End HTML Document:
Close the <body> and <html> tags.
Program:

<%@page import="java.util.Date"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Current Date and Time</title>
<style>
body {
background-color: black; /* Set background color */
font-family: Arial, sans-serif; /* Set font family */
text-align: center; /* Center align text */
padding-top: 20%; /* Adjust padding to vertically center content
*/
}
h2 {
color: white; /* Set font color */
}
p{
font-size: 18px; /* Set font size */
}
</style>
</head>
<body>
<h2>Current Date and Time</h2>
<p style="color: skyblue;">The current date and time is: <%= new
Date() %></p>
</body>
</html>
Output:

Result:
Thus the above program is executed successfully.
Ex.no:12 Jsp for add and subtract two numbers.
Date:

Aim:
To create a jsp that add and subtract two numbers.

Algorithm:

Step 1: Define CSS Styles:


Inside the <style> tag, specify the CSS styles for various elements such
as body background color, font styles, input fields, and buttons.

Step 2: Display Calculator Heading:


Use the <h2> tag to display the heading "Calculator".

Step 3: Create Form:


Create a <form> element with the action attribute pointing to the JSP
file itself (calculator.jsp) and the method attribute set to "post".

Step 4: Input Fields:


Within the form, create input fields for the first and second numbers
using <input> tags with type set to "text" and name attributes set to
"num1" and "num2" respectively.

Step 5: Submit Buttons:


Add two submit buttons to the form, one for addition and one for
subtraction. Use the <button> tag with the type attribute set to "submit"
and name attribute set to "add" and "subtract" respectively.

Step 6: JSP Scriptlet for Calculation:


Use JSP scriptlets (<% %> tags) to embed Java code within the
HTML. Check which button was clicked using
request.getParameter("parameterName").

Step 7: Perform Addition:


If the "add" button was clicked, retrieve the values of num1 and num2
from the request parameters, convert them to integers, calculate their
sum, and output the result using out.println().
Step 8: Perform Subtraction:
If the "subtract" button was clicked, retrieve the values of num1 and
num2 from the request parameters, convert them to integers, calculate
their difference, and output the result using out.println().

Step 9: End of JSP Scriptlet:


Close the JSP scriptlet using %>.

Step 10: End of HTML:


Close the <form> tag and the <body> and <html> tags to complete the
HTML document.
Program:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculator</title>
<style>
body {
background-color: lightslategrey; /* Set background color */
font-family: Arial, sans-serif; /* Set font family */
text-align: center; /* Center align text */
padding-top: 20%; /* Adjust padding to vertically center content
*/
}
h2 {
color: lightcyan; /* Set font color */
}
input[type="text"] {
width: 100px; /* Set width of input fields */
}
button {
padding: 8px 20px; /* Set padding for buttons */
background-color: black; /* Set background color for buttons */
color: white; /* Set font color for buttons */
border: none; /* Remove border */
cursor: pointer; /* Change cursor on hover */
margin: 10px; /* Add margin to buttons */
}
button:hover {
background-color: lightskyblue; /* Darken background color on
hover */
}
</style>
</head>
<body>
<h2>Calculator</h2>
<form action="calculator.jsp" method="post">
Enter first number: <input type="text" name="num1"><br>
Enter second number: <input type="text" name="num2"><br><br>
<button type="submit" name="add">Add</button>
<button type="submit" name="subtract">Subtract</button>
</form>

<%-- JSP scriptlet to process form data and perform


addition/subtraction --%>
<%
if (request.getParameter("add") != null) {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
out.println("<p style='color: skyblue;'>Sum: " + sum + "</p>");
} else if (request.getParameter("subtract") != null) {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int difference = num1 - num2;
out.println("<p style='color: red;'>Difference: " + difference +
"</p>");
}
%>
</body>
</html>
Output:

Result:
Thus the above program is executed successfully.
Ex.no:13 Jsp for login module.
Date:

Aim:
To create a jsp for login module.

Algorithm:
Step 1: Set Up HTML Structure:
Define the basic structure of an HTML document including the
<!DOCTYPE html>, <html>, <head>, and <body> tags.

Step 2: Define CSS Styles:


Inside the <style> tag, specify the CSS styles for various elements such
as body background color, font styles, input fields, buttons, and
error/success messages.

Step 3:Display Login Form:


Use the <h2> tag to display the heading "Login". Then, create a <form>
element with the action attribute pointing to the login processing page
(login.jsp) and the method attribute set to "post".

Step 4: Input Fields:


Within the form, create input fields for the username and password
using <input> tags with type set to "text" and "password" respectively.
Also, include the name attribute for each input field to identify them in
the form submission.

Step 5: Submit Button:


Add a submit button to the form using the <button> tag with the type
attribute set to "submit". This button triggers the form submission when
clicked.

Step 6: Define JSP Scriptlet:


Use JSP scriptlets (<% %> tags) to embed Java code within the
HTML. In this case, retrieve the username and password entered by the
user from the request parameters using
request.getParameter("parameterName").

Step 7: Validation:
Perform dummy validation of the username and password. Check if
both fields are not null and if they match predefined values (e.g., "jei"
for the username and "24" for the password).

Step 8: Display Messages:


Depending on the validation result, display either a success message
("Login successful!") or an error message ("Invalid username or
password!") using <p> tags with appropriate classes (success-message
or error-message) for styling.

Step 9: End of JSP Scriptlet:


Close the JSP scriptlet using %>.

Step 10:End of HTML: Close the <form> tag and the <body> and
<html> tags to complete the HTML document.
Program:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<style>
body {
background-color: lightpink; /* Set background color */
font-family: Arial, sans-serif; /* Set font family */
text-align: center; /* Center align text */
padding-top: 20%; /* Adjust padding to vertically center content
*/
}
h2 {
color: black; /* Set font color */
}
input[type="text"],
input[type="password"] {
width: 200px; /* Set width of input fields */
padding: 8px; /* Set padding for input fields */
margin: 5px; /* Add margin to input fields */
}
button {
padding: 8px 20px; /* Set padding for button */
background-color: yellow; /* Set background color for button */
color: black; /* Set font color for button */
border: none; /* Remove border */
cursor: pointer; /* Change cursor on hover */
}
button:hover {
background-color: black; /* Darken background color on hover
*/
color: white; /* Set font color for button on hover */
}
.error-message {
color: red; /* Set color for error message */
margin-top: 10px; /* Add margin to the top of error message */
}
.success-message {
color: green; /* Set color for success message */
margin-top: 10px; /* Add margin to the top of success message
*/
}
</style>
</head>
<body>
<h2>Login</h2>
<form action="${pageContext.request.contextPath}/login.jsp"
method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password"
required><br><br>
<button type="submit">Login</button>
</form>

<%-- JSP scriptlet to validate login credentials --%>


<%
String username = request.getParameter("username");
String password = request.getParameter("password");

// Dummy validation (replace with actual validation logic)


if (username != null && password != null && username.equals("jei")
&& password.equals("24")) {
%>
<p class="success-message">Login successful!</p>
<%
} else if (username != null && password != null) {
%>
<p class="error-message">Invalid username or password!</p>
<%
}
%>
Output:

Result:
Thus the above program is executed successfully.
Ex.no:14 Web page that prints 1 to 10 using JSTL
Date:

Aim:
To create a web page that prints 1 to 10 using JSTL.

Algorithm:
step1: start the program.
step2: Set up page directives:
Set the character encoding and content type for the JSP page.
step3: Declare taglib directive:
Import the JSTL core library for using custom tags in the JSP
page.
step4: Define HTML structure:
Begin the HTML document structure with <html>, <head>,
and <body> tags.
step5: Set character encoding:
Use the <meta charset="UTF-8"> tag to ensure the correct
character encoding for the HTML document.
step6: Set title:
Use the <title> tag to set the title of the HTML document.
step7: Define CSS styling:
Use the <style> tag to define CSS rules for styling various
HTML elements on the page.
step8: Create body content:
Add a heading (<h2>) indicating the purpose of the page
("Numbers from 1 to 10").
Create an unordered list (<ul>) to display the numbers.
step9: Iterate over numbers using JSTL forEach loop:
Use the <c:forEach> tag to loop through numbers from 1 to 10.
Within each iteration, create a list item (<li>) to display the
current number.
The value of the "number" variable is dynamically inserted
into each list item using Expression Language (${number}).
Step10: End HTML structure:
Close the <ul>, <body>, and <html> tags to complete the
HTML document.
Step11: Render the page:
The completed HTML document is rendered in the browser,
displaying the numbers from 1 to 10 in a list format.
Step12: End the program.
Program:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Print Numbers</title>
<style>
body {
background-color: lightblue; /* Set background color */
font-family: Arial, sans-serif; /* Set font family */
text-align: center; /* Center align text */
}
h2 {
color: navy; /* Set font color */
}
ul {
list-style-type: none; /* Remove bullet points */
padding: 0; /* Remove default padding */
}
li {
margin-bottom: 10px; /* Add margin between list items */
}
</style>
</head>
<body>
<h2>Numbers from 1 to 10</h2>
<ul>
<c:forEach var="number" begin="1" end="10">
<li>${number}</li>
</c:forEach>
</ul>
</body>
</html>
Output:

Result:
Thus the above program is executed successfully.
Ex.no:15 Custom JSP tag prints current date&time
Date:

Aim:
To create a custom JSP tag that prints current date and time. Use this tag
into JSP page.

Algorithm:

DateTimeTag.java:

Step1:This Java class (DateTimeTag) is a custom JSP tag handler.


Step 2:It's placed in the mypack package.
Step 3:It extends SimpleTagSupport, which is a class provided by the
Step 4:Java Servlet API for implementing simple tag handlers.
Step 5:It overrides the doTag() method, which is called when the JSP
tag is encountered during the JSP page processing.
Step 6:Inside the doTag() method:
Step 7:It creates a SimpleDateFormat object to format the date and
time.
Step 8:It formats the current date and time (new Date()) into a string in
the format specified ("yyyy-MM-dd HH:mm:ss").
Step 9:It writes the formatted date and time to the JSP output.

datetime.tld:

Step1:This is the Tag Library Descriptor (TLD) file for the custom tag.
Step 2:It defines metadata about the custom tag for the JSP container to
understand how to process it.
Step 3:It specifies the tag name (datetime), the class implementing the
tag (mypack.DateTimeTag), and the body content of the tag (empty in
this case).

Time.jsp:

Step1:This is a JSP page that uses the custom tag defined in


datetime.tld.
Step 2:It declares the taglib directive to import the custom tag library
using the URI specified in the TLD file.
Step 3:It's a simple HTML page.
Step 4:nside the body, it includes the custom tag <dt:datetime />, which
will invoke the functionality defined in the DateTimeTag class when the
JSP page is rendered.

1. When the JSP page Time.jsp is accessed by a client:


2. The JSP container processes the page.
3. It encounters the <dt:datetime /> tag.
4. It looks up the corresponding tag handler for this tag using the
information provided in the TLD file (datetime.tld).
5. It finds the class mypack.DateTimeTag specified in the TLD file as the
handler for this tag.
6. It creates an instance of DateTimeTag and calls its doTag() method.
7. Inside doTag(), the current date and time are formatted.
8. The formatted date and time are written to the output of the JSP page.
9. The resulting HTML page sent back to the client includes the
formatted date and time at the location of the <dt:datetime /> tag.
Program:

1). sourse package-> mypack-> new-> java class

package mypack;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class DateTimeTag extends SimpleTagSupport{

@Override
public void doTag() throws JspException, IOException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-
MM-dd HH:mm:ss");
String dateTime = dateFormat.format(new Date());
getJspContext().getOut().write(dateTime);
}
}

(2). web-inf-> new-> tlds

[this tld file format]


<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
<tlib-version>1.0</tlib-version>
<short-name>datetime</short-name>
<uri>/WEB-INF/tlds/datetime</uri>
<tag>
<name>datetime</name>
<tag-class>mypack.DateTimeTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
(3). webpage-> new->jsp page

<%@ taglib prefix="dt" uri="/WEB-INF/tlds/datetime.tld" %>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<dt:datetime />
</body>
</html>
Output:

Result:
Thus the above program is executed successfully.

You might also like