WT File Removed
WT File Removed
CODE:
// CartServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CartServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
HttpSession session = request.getSession();
String action = request.getParameter("action");
if (session.getAttribute("cart") == null) {
session.setAttribute("cart", new
java.util.ArrayList<String>());
}
// cart.jsp
<%@ page import="java.util.*" %>
<html>
<head>
<title>Shopping Cart</title>
</head>
<body>
<h2>Shopping Cart</h2>
<form method="POST" action="CartServlet">
<label for="item">Item to add:</label>
<input type="text" id="item" name="item">
<input type="hidden" name="action" value="add">
<input type="submit" value="Add to Cart">
</form>
<h3>Your Cart:</h3>
<ul>
<% List<String> cart = (List<String>)
session.getAttribute("cart");
if (cart != null) {
for (String item : cart) {
%>
<li>
<%= item %>
<form style="display:inline;"
method="POST" action="CartServlet">
<input type="hidden" name="item" value="<%= item %>">
<input type="hidden" name="action" value="remove">
<input type="submit" value="Remove">
</form>
</li>
<% } } %>
</ul>
<a href="checkout.jsp">Proceed to Checkout</a>
</body>
</html>
// checkout.jsp
<%@ page import="java.util.*" %>
<html>
<head><title>Checkout</title></head>
<body>
<h2>Checkout</h2>
<h3>Your Cart:</h3>
<ul>
<%
List<String> cart = (List<String>)
session.getAttribute("cart");
if (cart != null) {
for (String item : cart) {
%>
<li><%= item %></li>
<%
}
}
%>
</ul>
<h4>Total items: <%= cart != null ? cart.size() : 0 %></h4>
<a href="cart.jsp">Back to Cart</a>
</body>
</html>
OUTPUT:
RESULT:
Code for Design and implement a simple shopping cart example
with session tracking API written, executed and the output has been
Verified successfully.
Experiment-10
AIM: Create a table which should contain at least the following fields:
name, password, email-id, phone number Write Servlet/JSP to
connect to that database and extract data from the tables and display
them. Insert the details of the users who register with the web site,
whenever a new user clicks the submit button in the registration
page.
CODE:
//Sql
CREATE DATABASE user_db;
USE user_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
password VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(15)
);
//HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
</head>
<body>
<h3>User Registration Form</h3>
<form action="RegisterServlet" method="POST">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"
required><br><br>
<label for="email">Email ID:</label><br>
<input type="email" id="email" name="email"
required><br><br>
<label for="phone">Phone Number:</label><br>
<input type="text" id="phone" name="phone"
required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
// RegisterServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
String dbURL = "jdbc:mysql://localhost:3306/user_db"; //
Database URL
String dbUsername = "root"; // Database username
String dbPassword = "password"; // Database password
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUsername,
dbPassword);
String sql = "INSERT INTO users (name, password, email,
phone) VALUES (?, ?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
ps.setString(3, email);
ps.setString(4, phone);
int rowsAffected = ps.executeUpdate();
if (rowsAffected > 0) {
// Prepare the query to retrieve user data
String query = "SELECT * FROM users";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h3>Registration Successful! All Users:</h3>");
out.println("<table border='1'>");
out.println("<tr><th>ID</th><th>Name</th><th>Email</th><th>Pho
ne</th></tr>");
while (rs.next()) {
int id = rs.getInt("id");
String dbName = rs.getString("name");
String dbEmail = rs.getString("email");
String dbPhone = rs.getString("phone");
out.println("<tr><td>" + id + "</td><td>" + dbName +
"</td><td>" + dbEmail + "</td><td>" + dbPhone + "</td></tr>");
}
out.println("</table>");
out.println("</body></html>");
rs.close();
stmt.close();
}
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("Error: " + e.getMessage());
} finally {
try {
// Close database resources
if (ps != null) ps.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//web.xml
<web-app 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-
app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
RESULT:
Code for create a table which should contain at least the following
fields: name, password, email-id, phone number Write Servlet/JSP to
connect to that database and extract data from the tables and display
them. Insert the details of the users who register with the web site,
whenever a new user clicks the submit button in the registration
page written, executed and the output has been Verified successfully.
Experiment-11
AIM: Write a JSP which insert the details of the 3 or 4 users who
register with the web site by using registration form. Authenticate
the user when he submits the login form using the user name and
password from the database.
CODE:
//sql
CREATE DATABASE user_db;
USE user_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL
);
// Registration Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
</head>
<body>
<h3>Register</h3>
<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>
<input type="submit" value="Register">
</form>
</body>
</html>
// Login Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Login</title>
</head>
<body>
<h3>Login</h3>
<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>
<input type="password" id="password" name="password"
required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
// RegisterServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
String dbURL = "jdbc:mysql://localhost:3306/user_db";
String dbUsername = "root";
String dbPassword = "password";
try (Connection conn = DriverManager.getConnection(dbURL,
dbUsername, dbPassword)) {
String sql = "INSERT INTO users (username, password) VALUES
(?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, username);
ps.setString(2, password);
ps.executeUpdate();
response.sendRedirect("login.jsp");
}
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("Error: " + e.getMessage());
}
}
}
// LoginServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
String dbURL = "jdbc:mysql://localhost:3306/user_db";
String dbUsername = "root";
String dbPassword = "password";
try (Connection conn = DriverManager.getConnection(dbURL,
dbUsername, dbPassword)) {
String sql = "SELECT * FROM users WHERE username = ? AND
password = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, username);
ps.setString(2, password);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
response.sendRedirect("welcome.jsp");
} else {
response.getWriter().println("Invalid username or
password.");
}
}
}
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("Error: " + e.getMessage());
}
}
}
// Welcome Page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h3>Welcome, you have logged in successfully!</h3>
</body>
</html>
OUTPUT:
RESULT:
Code for Write a JSP which insert the details of the 3 or 4 users who
register with the web site by using registration form. Authenticate
the user when he submits the login form using the user name and
password from the database written, executed and the output has
been Verified successfully.
Experiment-9
AIM: Assume four users user1, user2, user3 and user4 having the
passwords pwd1, pwd2, pwd3 and pwd4 respectively. Write a servlet
for doing the following: 1. Create a Cookie and add these four user
id’s and passwords to this Cookie. 2. Read the user id and passwords
entered in the Login form and authenticate with the values available
in the cookies.
CODE:
//CookieServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CreateCookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// Sample user credentials
String[] users = {"user1", "user2", "user3", "user4"};
String[] passwords = {"pwd1", "pwd2", "pwd3", "pwd4"};
Cookie userCookie = new Cookie("userCredentials", "");
StringBuilder cookieValue = new StringBuilder();
for (int i = 0; i < users.length; i++) {
cookieValue.append(users[i]).append(":").append(passwords[i]);
if (i < users.length - 1) {
cookieValue.append(";");
}
}
// Set the cookie value
userCookie.setValue(cookieValue.toString());
userCookie.setMaxAge(60 * 60 * 24); // Cookie will last for one
day
response.addCookie(userCookie);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h3>Cookies have been created
successfully!</h3>");
out.println("<p><a href='login.html'>Go to Login
Page</a></p>");
out.println("</body></html>");
}
}
//login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Form</title>
</head>
<body>
<h3>Login</h3>
<form action="LoginServlet" method="POST">
<label for="userid">User ID:</label><br>
<input type="text" id="userid" name="userid"><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password"
name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
//LoginServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// Get user input from the login form
String enteredUserId = request.getParameter("userid");
String enteredPassword = request.getParameter("password");
Cookie[] cookies = request.getCookies();
String storedCredentials = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("userCredentials")) {
storedCredentials = cookie.getValue();
break;
}
}
}
if (storedCredentials == null) {
response.getWriter().println("No credentials found in
cookies.");
return;
}
String[] userCredentials = storedCredentials.split(";");
Map<String, String> userMap = new HashMap<>();
for (String userCred : userCredentials) {
String[] credentials = userCred.split(":");
userMap.put(credentials[0], credentials[1]);
}
String storedPassword = userMap.get(enteredUserId);
if (storedPassword != null &&
storedPassword.equals(enteredPassword)) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h3>Login Successful!</h3>");
out.println("<p>Welcome, " + enteredUserId + "!</p>");
out.println("</body></html>");
} else {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h3>Login Failed!</h3>");
out.println("<p>Invalid user ID or password.</p>");
out.println("</body></html>");
}
}
//web.xml
<web-app 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-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>CreateCookieServlet</servlet-name>
<servlet-class>CreateCookieServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class></servlet>
<servlet-mapping>
<servlet-name>CreateCookieServlet</servlet-name>
<url-pattern>/createCookies</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
RESULT:
Code for Assume four users user1, user2, user3 and user4 having the
passwords pwd1, pwd2, pwd3 and pwd4 respectively. Write a servlet
for doing the following: 1. Create a Cookie and add these four user
id’s and passwords to this Cookie. 2. Read the user id and passwords
entered in the Login form and authenticate with the values available
in the cookies written, executed and the output has been Verified
successfully