0% found this document useful (0 votes)
12 views24 pages

Practical 3 AJAVA

Uploaded by

ay9219532407
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)
12 views24 pages

Practical 3 AJAVA

Uploaded by

ay9219532407
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/ 24

Name: Satyajit Gorad

Roll No:5287
Class:SYCS-A

Practical 3

1] Create a servlet for a login page. If the username and password are correct then it
says message “Hello with username” else a message “login failed”.
Pseudo Code
1. Create a Java Web project named "5287gsatya".
2. In Index.html:
o Create a form with action="LoginServlet" and method="POST".
o Add input fields for Username and Password, and a submit button labeled "Login".
3. Create a servlet named LoginServlet.
4. In the servlet:
o Use request.getParameter("username") and request.getParameter("password") to get
user inputs.
o Compare inputs with predefined credentials (e.g., "Satyajit" and "satyajit123").
o If credentials match, display "Hello with username".
o Otherwise, display "Login failed".
5. Run Index.html in a browser and test the login functionality.

Source Code:
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Page</h2>
<form action="LoginServlet" method="POST">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br><br>

<label for="password">Password:</label><br>
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

<input type="password" id="password" name="password" required><br><br>

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


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

LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get the username and password from the form
String username = request.getParameter("username");
String password = request.getParameter("password");

// Hardcoded valid username and password for demonstration purposes


String validUsername = "satyajit";
String validPassword = "satyajit123";

// Set the response content type


response.setContentType("text/html");

// Get the PrintWriter object to send output


PrintWriter out = response.getWriter();

// Check if the username and password are correct


if (username.equals(validUsername) && password.equals(validPassword)) {
out.println("<h2>Hello, " + username + "!</h2>");
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

} else {
out.println("<h2>Login failed</h2>");
}
}
}

Output:
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

2] Create a servlet application that demonstrates the use of ServletContext for sharing
data between two servlets.

Pseudo Code
1. Create a Java Web project named "5287gsatya ".
2. In Index.html:
o Create a form with action="FirstServlet1" and method="post".
o Add an input field for data and a submit button labeled "Submit".
3. Create a servlet named FirstServlet:
o Use request.getParameter("data") to get the input.
o Store the input in the ServletContext using
getServletContext().setAttribute("sharedData", inputData).
o Display a link to SecondServlet.
4. Create a servlet named SecondServlet2:
o Retrieve data using getServletContext().getAttribute("sharedData").
o Display the retrieved data or show a message if no data is found.
5. Map the servlets (/FirstServlet1 and /SecondServlet2) using annotations or web.xml.
6. Test by submitting data in Index.html and viewing it in SecondServlet2.

Source Code:
Index.html
<!DOCTYPE html>
<html>
<head>
<title>ServletContext Example</title>
</head>
<body>
<h3>Name: Satyajit Gorad, Roll No: 5287</h3>

<h1>Enter Data to Share Between Servlets</h1>


Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

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


<label for="data">Enter Data:</label>
<input type="text" id="data" name="data" required>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

FirstServlet1.java
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("/FirstServlet")
public class FirstServlet1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String inputData = request.getParameter("data");
getServletContext().setAttribute("sharedData", inputData); response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h3>Name: Satyajit Gorad, Roll No: 5287</H3>");
out.println("<h1>Data has been stored in ServletContext.</h1>");
out.println("<a href='SecondServlet2'>View Stored Data</a>");
out.println("</body></html>");
}
}
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

SecondServlet2.java
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("/SecondServlet")
public class SecondServlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


String sharedData = (String) getServletContext().getAttribute("sharedData");
response.setContentType("text/html");
PrintWriter out = response.getWriter(); out.println("<html><body>");
if (sharedData != null) {
out.println("<h3>Name: Satyajit Gorad, Roll No: 5287</H3>");
out.println("<h1>Data retrieved from ServletContext:</h1>");
out.println("<p>" + sharedData + "</p>");
} else {
out.println("<h3>Name: Satyajit Gorad, Roll No: 5287</H3>");
out.println("<h1>No data found in ServletContext.</h1>");
}
out.println("</body></html>");
}
}
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

Output:
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

3] Using Requestdispatcher Interface create a Servlet which will validate the

password entered by the user, if the user has entered "Servlet" as password, then he
will be forwarded to Welcome Servlet else the user will stay on the index.html page
andan error message will be displayed.

Pseudo Code
1. Create a Java Web project named "5287gsatya ".
2. In Index.html:
o Create a form with action="Login2" and method="post".
o Add an input field for Password and a submit button labeled "Submit".
3. Create a servlet named Login2:
o Use request.getParameter("password") to get user input.
o If the password is "Satyajit", forward to Welcome servlet using RequestDispatcher.
o Otherwise, display an error message.
4. Create a servlet named Welcome2:
o Display a welcome message when accessed.
5. Map the servlets (/Login and /Welcome) using annotations or web.xml.
6. Test by submitting valid and invalid passwords.

Source Code:
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>Password Validation</title>
</head>
<body>
<h3>Name: Satyajit Gorad, Roll No: 5287</h3>
<h1>Login</h1>
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

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


<label for="password">Enter Password:</label>
<input type="password" id="password" name="password" required>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

Login2.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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("/Login")
public class Login2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String password = request.getParameter("password");
if ("Satyajit".equals(password)) {
RequestDispatcher dispatcher = request.getRequestDispatcher("Welcome2");
dispatcher.forward(request, response);
} else {
response.setContentType("text/html");
response.getWriter().println("<html><body><h3>Name: Satyajit Gorad, Roll
no:5287</h3><br><br><h1>Invalid Password!</h1></body></html>");
}
}
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

Welcome2.java
import java.io.IOException;
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("/Welcome")

public class Welcome2 extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<html><body><h3><h1>Welcome to the Servlet
Application!</h1><br><br><h3>Name: Satyajit GOrad, Roll No: 5287</h3></body></html>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doPost(request, response); // Redirect GET to POST handling

}
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

Output:
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

4] Create a servlet that uses Cookies to store the number of times a user has visited
servlet.
Pseudo Code
1. Create a Java Web project named "5287gsatya ".
2. In VisitCount servlet:
o Use request.getCookies() to check for a cookie named visitCount.
o If found, increment its value and update the cookie.
o If not found, create a new cookie with value 1.
o Use response.addCookie(cookie) to save the cookie.
o Display the visit count to the user.
3. Map the servlet to /VisitCount using annotations or web.xml.
4. Test by accessing the servlet multiple times to track visits.

Source Code:
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>Visit Count</title>
</head>
<body>
<h3>Name: Satyajit Gorad, Roll No: 5287</h3>
<h1>Welcome to the Visit Count Servlet!</h1>
<p><a href="VisitCount">Click here to check your visit count.</a></p>
</body>
</html>
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

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

@WebServlet("/VisitCount")
public class VisitCount extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");

Cookie[] cookies = request.getCookies();


boolean visitCookieFound = false;
int visitCount = 0;

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

cookie.setValue(String.valueOf(visitCount));
cookie.setMaxAge(60 * 60 * 24);
response.addCookie(cookie);
visitCookieFound = true;
break;
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

}
}
}
if (!visitCookieFound) { visitCount = 1;
Cookie newCookie = new Cookie("visitCount", String.valueOf(visitCount));
newCookie.setMaxAge(60 * 60 * 24);
response.addCookie(newCookie);
}
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>You have visited this servlet " + visitCount + "times.</h1>");
response.getWriter().println("<h3>Name: Satyajit Gorad, Roll No: 5287</h3> ");
response.getWriter().println("</body></html>");
}
}

Output:
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

5] Create a servlet demonstrating the use of session creation and destruction. Also
check whether the user has visited this page first time or has visited earlier also using
sessions.

Pseudo Code
1. Create a Java Web project named "5287gsatya".

2. In SessionExampleServlet:

o Use request.getSession(true) to get or create a session.


o Check if visitCount exists in the session attributes.
o If not, initialize it to 1 and display a first-visit message.
o If it exists, increment the value and display the updated count.
o Provide a logout link that invalidates the session using session.invalidate().
3. Map the servlet to /SessionExampleServlet using annotations or web.xml.

4. Test by tracking visits and logging out.

SessionExampleServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SessionExampleServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
Integer visitCount = (Integer) session.getAttribute("visitCount");
if (visitCount == null) {
visitCount = 1;
session.setAttribute("visitCount", visitCount);
out.println("<h3>Name: Satyajit Gorad, Roll No:5287 </h3>");
out.println("<h3>Welcome, first-time visitor!</h3>");
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

} else {
visitCount++; session.setAttribute("visitCount", visitCount);
out.println("<h3>Name: Satyajit Gorad, Roll No:5287 </h3>");
out.println("<h3>Welcome back! You have visited this page " + visitCount + " times.</h3>");
}
out.println("<br><a href='" + request.getRequestURI() + "?action=logout'>Click here to logout and
destroy session</a>");

String action = request.getParameter("action");


if (action != null && action.equals("logout")) { session.invalidate(); // Destroy the session

out.println("<h3>Your session has been destroyed.</h3>");


}
out.close();
}
}
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

Output:
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

6]Create a new servlet which will handle searches on the search engine. This servlet
should accept search queries from users and redirect them to the search results page by
using sendRedirect() method.
Pseudo Code
1. In Index.html:

o Create a form with action="SearchServlet" and method="GET".


o Add an input field for query and a submit button labeled "Search".
2. Create a servlet named SearchServlet:

o Use request.getParameter("query") to get the search query.


o Construct a search URL (e.g., https://www.google.com/search?q=<query>).
o Redirect to the URL using response.sendRedirect().
3. Map the servlet to /SearchServlet.

4. Test by submitting search queries and verifying redirection.

Source Code:
Index.html:

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<!-- Form to submit username and password-->
<h3>Name: Satyajit Gorad, Roll No: 5287</h3>
<form method="GET" action="SearchServlet">
<input type="text" name="query" placeholder="Enter search query">
<BR><BR>
<input type="submit" value="Search">
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

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

SearchServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SearchServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String query = request.getParameter("query");
if (query == null || query.trim().isEmpty()) {
out.println("<h3>Please enter a search query.</h3>");
out.println("<form method='GET' action='search'>");
out.println("<input type='text' name='query' placeholder='Enter search query'>");
out.println("<input type='submit' value='Search'>");
out.println("</form>");
} else {
String encodedQuery = java.net.URLEncoder.encode(query, "UTF-8"); // Encode query for URL
safety
String searchUrl = "https://www.google.com/search?q=" + encodedQuery;
response.sendRedirect(searchUrl);
}
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

Output:
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

7] Create a Java web application that demonstrates the usage of ServletContext to set
and retrieve attributes.
Pseudo Code
1. Create a Java Web project named "5287gsatya".

2. In SetAttributeServlet:

o Use getServletContext() to retrieve the context.


o Set an attribute using setAttribute("key", "value").
o Display a confirmation message with a link to GetAttributeServlet.
3. In GetAttributeServlet:

o Retrieve the context using getServletContext().


o Use getAttribute("key") to get the stored value.
o Display the value or a message if no value is found.
4. Map the servlets (/SetAttributeServlet and /GetAttributeServlet).

5. Test by setting and retrieving attributes via the mapped URLs.

Source Code:
Index.html:
\<!DOCTYPE html>
<html>
<head>
<title>ServletContext Example</title>
</head>
<body>
<h3>Name: Satyajit Gorad, Roll No: 5287</h3>
<h1>Welcome to the ServletContext Example</h1>
<p><a href="SetAttributeServlet">Click here to set the attribute in ServletContext</a></p>
</body>
</html>

SetAttributeServlet.java
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @WebServlet("/SetAttributeServlet")
public class SetAttributeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
ServletContext context = getServletContext();
context.setAttribute("message", "5287 Satyajit Welcomes You!!!!!");
response.getWriter().println("<html><body>");
response.getWriter().println("<h3>Name: Satyajit Gorad, Roll No:5287</h3><br><br><h1>Attribute
set in ServletContext!</h1>");
response.getWriter().println("<p><a href='GetAttributeServlet'>Click here to retrieve the
attribute</a></p>");

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

GetAttributeServlet.java
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

@WebServlet("/GetAttributeServlet")
public class GetAttributeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
ServletContext context = getServletContext();
String message = (String) context.getAttribute("message");
response.getWriter().println("<html><body>");
if (message != null) {
response.getWriter().println("<h1>Retrieved Attribute: " + message + "</h1>");
} else {
response.getWriter().println("<h1>No attribute found in ServletContext!</h1>");
}
response.getWriter().println("<p><a href='attribute.html'>Back to Home</a></p>");
response.getWriter().println("</body></html>");
}
}

Output:
Name: Satyajit Gorad
Roll No:5287
Class:SYCS-A

You might also like