0% found this document useful (0 votes)
4 views19 pages

Java Servlet Session and Cookie Examples

It's all I have
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)
4 views19 pages

Java Servlet Session and Cookie Examples

It's all I have
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

I23040 Advanced Java Vikas Pal

Create a servlet demostrating the use of session creation and destruction also check
whether the user has visited this page first time or has visited earlier also using session.
Code:
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Hello Form</title>
</head>
<body>
<form action="sessiont" method="get">
<input type="submit" value="Submit">
</form>
</body>
</html>

[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

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

protected void doGet(HttpServletRequest request, HttpServletResponse response)


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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
I23040 Advanced Java Vikas Pal

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

[Link]("text/html;charset=UTF-8");

try (PrintWriter out = [Link]()) {

// Create or retrieve session


HttpSession session = [Link](true);

// Session creation and last access time


Date createTime = new Date([Link]());
Date lastAccessTime = new Date([Link]());

// Define session attribute keys and defaults


String title = "Welcome Back to my website";
String visitCountKey = "visitCount";
String userIDKey = "userID";
String userID = "ABCD";
Integer visitCount;

// Check if session is new


if ([Link]()) {
title = "Welcome to my website";
visitCount = 1;
[Link](userIDKey, userID);
} else {
visitCount = (Integer) [Link](visitCountKey);
if (visitCount == null) {
visitCount = 1;
} else {
visitCount = visitCount + 1;
}
userID = (String) [Link](userIDKey);
}

// Store updated visit count


[Link](visitCountKey, visitCount);

// Start HTML output


[Link]("<!DOCTYPE html>");
[Link]("<html>");
I23040 Advanced Java Vikas Pal

[Link]("<head><title>" + title + "</title></head>");


[Link]("<body bgcolor=\"#f0f0f0\">");

[Link]("<h1 align=\"center\">" + title + "</h1>");


[Link]("<h2 align=\"center\">Session Information</h2>");

[Link]("<table border=\"1\" align=\"center\">");


[Link]("<tr bgcolor=\"#949494\">");
[Link]("<th>Session Info</th><th>Value</th></tr>");

[Link]("<tr><td>Session ID</td><td>" + [Link]() + "</td></tr>");


[Link]("<tr><td>Creation Time</td><td>" + createTime + "</td></tr>");
[Link]("<tr><td>Last Access Time</td><td>" + lastAccessTime + "</td></tr>");
[Link]("<tr><td>User ID</td><td>" + userID + "</td></tr>");
[Link]("<tr><td>Number of Visits</td><td>" + visitCount + "</td></tr>");
[Link]("</table>");

[Link]("</body>");
[Link]("</html>");
}
}
}

Output:
I23040 Advanced Java Vikas Pal

Create a servlet that uses cookies to store the number of times a user has visit a servlet.
Code:
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Cookie visit</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Click below to open the visit counter servlet:</h1>
<a href="cookieS">Go to Visit Counter</a>

</body>
</html>

[Link]
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/[Link] to change
this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/[Link] to edit this
template
*/

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

/**
*
* @author Admin
*/
public class cookieS extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

int visitCount = 1;
I23040 Advanced Java Vikas Pal

boolean cookieFound = false;

// Get cookies from request


Cookie[] cookies = [Link]();
if (cookies != null) {
for (Cookie c : cookies) {
if ([Link]().equals("visitCount")) {
visitCount = [Link]([Link]()) + 1;
[Link]([Link](visitCount));
[Link](60 * 60 * 24 * 365); // 1 year
[Link](c);
cookieFound = true;
break;
}
}
}

// If visitCount cookie not found, create one


if (!cookieFound) {
Cookie newCookie = new Cookie("visitCount", "1");
[Link](60 * 60 * 24 * 365);
[Link](newCookie);
}

// Send response to client


[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
[Link]("<!DOCTYPE html>");
[Link]("<html><head><title>Cookie Visit Counter</title></head><body>");
[Link]("<h1>Welcome to the Cookie Visit Counter Page</h1>");
[Link]("<h2>You have visited this page: " + visitCount + " times.</h2>");
[Link]("<a href='cookieS'>Refresh Page</a>");
[Link]("</body></html>");
}
}
}

Output:
I23040 Advanced Java Vikas Pal

Create a simple calculator application using servlet.


Code:
[Link]
<!DOCTYPE html>
<html>
<head>
<title>calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style=" height:100vh; width:100vw; background-repeat: no-repeat;
background-image:
url('[Link]
d7VA1OFqEvx9UzVBES0YfExexj72FFrJ9ZWzXNsk0yzw8YBnc0L5_pQokvgpG6hE-
asdyUO8IA')">
<div>
<form action="Calculator" method="post">
Enter the first number:
<input style="margin-bottom: 2px;" type="number" name="num1" step="any">
<br>
Enter the second number:
<input type="number" name="num2" step="any">
<select name="Operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<br>
<input style="background-color: purple;color:white;" type="submit"
value="calculate">
</form>
</div>
</body>
</html>

[Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
I23040 Advanced Java Vikas Pal

import [Link];

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


public class Calculator extends HttpServlet {

// Handles both GET and POST


protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {

try {
float fnum = [Link]([Link]("num1"));
float snum = [Link]([Link]("num2"));
String operator = [Link]("Operator");
float total = 0;

switch (operator) {
case "+":
total = fnum + snum;
break;
case "-":
total = fnum - snum;
break;
case "*":
total = fnum * snum;
break;
case "/":
if (snum != 0) {
total = fnum / snum;
} else {
[Link]("<h2 style='color:red;'>Error: Cannot divide by zero.</h2>");
return;
}
break;
default:
[Link]("<h2 style='color:red;'>Invalid operator!</h2>");
return;
}

[Link]("<!DOCTYPE html>");
[Link]("<html>");
I23040 Advanced Java Vikas Pal

[Link]("<head><title>Calculator Result</title></head>");
[Link]("<body style='background-color:#f2f2f2;'>");
[Link]("<h1>Result: " + fnum + " " + operator + " " + snum + " = " + total +
"</h1>");
[Link]("<br><a href='[Link]'>Back to Calculator</a>");
[Link]("</body></html>");

} catch (NumberFormatException e) {
[Link]("<h2 style='color:red;'>Invalid number input!</h2>");
[Link]("<a href='[Link]'>Try Again</a>");
}
}
}

// Important: Add doPost to handle POST request from form


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

// (Optional) If someone tries GET, show message


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("[Link]");
}
}

Output:
I23040 Advanced Java Vikas Pal

Create a servlet page for login page if the username and password are correct then it says
a message “Hello ” else a message login failed.
Code:
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div style="height:50vh; width:50vh; background-color: window; display:flex;
border-radius: 10px; flex-direction: column; justify-content: start;">
<h1 style="padding-left: 10px">Login Form</h1>
<form action="CollegeForm" method="post">
<div>
<div style="margin-top: 10px">
<label style="padding-left: 10px; font-size: 20px" for="username" >Enter your
Username:</label>
<input style=" border: 1px solid black; border-radius: 5px; padding:10px"
type="text" id="username" name="username">
</div>
<div style="margin-top: 10px">
<label style="padding-left: 10px; font-size: 20px" for="pass" >Enter your
Password:</label>
<input style=" border: 1px solid black; border-radius: 5px; padding:10px "
type="password" id="pass" name="pass">
</div>
<input style=" background-color:purple; color:white; margin: 10px; padding:
10px; border: 1px solid black; border-radius: 5px; cursor:pointer" type="submit"
value="submit">
</div>
</form>
</div>
</div>
</body>
</html>

[Link]

import [Link];
import [Link];
import [Link];
I23040 Advanced Java Vikas Pal

import [Link];
import [Link];
import [Link];
import [Link];

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

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {

String username = [Link]("username");


String password = [Link]("pass");

[Link]("<!DOCTYPE html>");
[Link]("<html><head><title>Login Result</title></head><body>");

if ("PW".equals(username) && "Arise".equals(password)) {


[Link]("<h1 style='color:green;'>Hello " + username + " </h1>");
} else {
[Link]("<h1 style='color:red;'>Login failed </h1>");
}

[Link]("<br><a href='[Link]'>Back to Login</a>");


[Link]("</body></html>");
}
}

// Add this to support POST from the HTML form


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

// (Optional) GET request handler


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("[Link]");
I23040 Advanced Java Vikas Pal

}
}

Output:
I23040 Advanced Java Vikas Pal

Create a servlet application to download a file.


Code:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<form action="Download" method="get">
<h2>Welcome to GeeksforGeeks.</h2>
<h3>Download the updated Data structures course structure here.</h3>
<input type="submit" value="Download" />
</form>
</body>
</html>

[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/Download")
public class Download extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String fileName = "[Link]";


String filePath = "C:\\Users\\User\\Documents\\TYIT Storage\\AWP\\" +
fileName;
File file = new File(filePath);
if (![Link]()) {
[Link]("text/html");
[Link]().println("<h3>File not found at: " + filePath + "</h3>");
I23040 Advanced Java Vikas Pal

return;
}

[Link]("application/[Link]
[Link]");
[Link]("Content-Disposition", "attachment; filename=\"" +
fileName + "\"");
try (FileInputStream inStream = new FileInputStream(file);
ServletOutputStream outStream = [Link]()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = [Link](buffer)) != -1) {
[Link](buffer, 0, bytesRead);
}
}
}
}

Output:
I23040 Advanced Java Vikas Pal

Create a servlet application to upload a file.


Code:
[Link]
<!DOCTYPE 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>
<form action="uploadservlet" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>
</form>
</body>
</html>

[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet(urlPatterns = {"/uploadservlet"})
public class uploadservlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("File uploaded successfully");
}
}

Output:
I23040 Advanced Java Vikas Pal

Create a Registration servlet in java uisng jdbc. Accept the detail such as username,
password, email and country from the user using html form and store the registration
detail in the database.
Code:
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<h2>User Registration</h2>
<form action="RegisterServlet" method="post">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>
<label for="country">Country:</label><br>
<input type="text" id="country" name="country" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>

RegisterServlet:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet(urlPatterns = {"/RegisterServlet"})
public class RegisterServlet extends HttpServlet {
@Override
I23040 Advanced Java Vikas Pal

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
String username = [Link]("username");
String password = [Link]("password");
String email = [Link]("email");
String country = [Link]("country");
Connection con = null;
PreparedStatement pst = null;
try {
[Link]("[Link]");
con = (Connection) [Link]("jdbc:mysql://localhost:3307/tyit",
"root", "root");
pst = [Link]("INSERT INTO users (username, password, email, country)
VALUES (?, ?, ?, ?)");
[Link](1, username);
[Link](2, password);
[Link](3, email);
[Link](4, country);
int row = [Link]();
if (row > 0) {
[Link]("<h1>Registration Successful!</h1>");
} else {
[Link]("<h1>Registration Failed!</h1>");
}
} catch (SQLException e) {
[Link]("<h1>Error: " + [Link]() + "</h1>");
} catch (ClassNotFoundException e) {
[Link]("<h1>Database Driver not found: " + [Link]() +
"</h1>");
} finally {
// Close resources
try {
if (pst != null) [Link]();
if (con != null) [Link]();
} catch (SQLException e) {
[Link]("<h1>Error closing resources: " + [Link]() +
"</h1>");
}
}
}
@Override
I23040 Advanced Java Vikas Pal

public String getServletInfo() {


return "Registration Servlet";
}
}

Output:
I23040 Advanced Java Vikas Pal

Using Request Dispatcher interface create a servlet which will validate the password
entered by the user if the user has enter “servlet ” as a password then he willl be
forwarded to the welcome servlet else the user will stay on the [Link] page and an
error message will be displayed.
Code:
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Request Dispatcher</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Login1" method="post">
Name:<input type="text" name="userName"/>
<br>
Password: <input type="password" name="userPass"/>
<br>
<input type="submit" value="login"/>
</form>
</body>
</html>

[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

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


public class Login extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

String username = [Link]("userName");


String password = [Link]("userPass");
I23040 Advanced Java Vikas Pal

if ("servlet".equals(password)) {
// Login success → send success message
[Link]("user", username);
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
} else {
// Login failed → send error back to login page
[Link]("errorMsg", " Incorrect username or password");
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
}
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}

Output:

You might also like