Web Technology & Advanced Java
Web Technology & Advanced Java
STUDENTNAME :
CLASS :
REGISTER NUMBER :
SEMESTER :
DHANALAKSHMI SRINIVASAN ARTS AND SCIENCE (Co-Education) COLLEGE
(Affiliated to University of Madras)
REGISTERNUMBER :
SUBJECT CODES :
Aim:
To create a simple calculator application that demonstrates the use of
RMI. You are not required to create GUI.
Algorithm:
Step 3:CalciClient:
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;
CalciClient:
package CalculatorRmi;
import java.rmi.Naming;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Scanner;
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;
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;
}
}
}
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 {
}
}
}
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 {
}
}
}
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;
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;
out.println("</body>");
out.println("</html>");
}
}
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;
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;
scanner.close();
}
}
Output:
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 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.
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
@Override
public void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(request, response);
@Override
public void destroy() {
// Clean-up code here if needed
}
}
Output:
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:
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:
<%@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:
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 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 10:End of HTML: Close the <form> tag and the <body> and
<html> tags to complete the HTML document.
Program:
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:
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:
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:
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;
@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);
}
}
Result:
Thus the above program is executed successfully.