COMJAVA
COMJAVA
AIM: Create a servlet that recognizes a visitor for the first time to a web
application and responds by saying “Welcome, you are visiting for the first
time”. When the page is visited for the second time, it should say “Welcome
Back”.
THEORY:
This servlet is designed to track whether a user is visiting a website for the first time using
cookies. When a user accesses the WelcomeServlet, it checks for a cookie named "visitedBefore".
If the cookie is not found, it assumes the user is visiting for the first time, displays a
"Welcome, you are visiting for the first time" message, and sets a cookie to mark
the visit.
If the cookie is found, it recognizes the user as a returning visitor and displays
"Welcome Back".
The servlet works by setting the response content type to HTML and using PrintWriter to
generate an appropriate response. Cookies are retrieved from the request and checked for
the "visitedBefore" flag. If absent, a new cookie is created and sent back with the response to
ensure the user is recognized on future visits.
This method helps track user visits without requiring a login or database storage.
SOURCE CODE:
import java.io.IOException;
import java.io.PrintWriter;
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;
@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
boolean isFirstTimeVisitor = true;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("visitedBefore".equals(cookie.getName()))
{ isFirstTimeVisitor = false;
break;
}
}
}
Cookie visitedCookie = new Cookie("visitedBefore", "true");
response.addCookie(visitedCookie);
out.println("<html><head><title>Welcome</title></head><bo
dy>"); if (isFirstTimeVisitor) {
out.println("<h2>Welcome, you are visiting for the first
time</h2>"); } else {
out.println("<h2>Welcome Back</h2>");
}
out.println("</body></html>");
}
}
OUTPUT:
PROGRAM-16
AIM: Write a program to set cookie information using Servlet.
THEORY:
This servlet, SetCookieServlet, is responsible for setting a cookie in the user's browser.
When a user accesses the /setCookie URL, the servlet does the following:
1. Creates a Cookie
o The cookie is named "userPref", with a value of "darkMode".
o This could be used for storing user preferences like theme settings.
2. Sets the Cookie Expiry
o The cookie is configured to last for 24 hours (60 * 60 * 24 seconds).
3. Sends the Cookie in the Response
o The cookie is added to the HTTP response using response.addCookie(cookie),
which instructs the browser to store it.
4. Responds to the User
o The response type is set to plain text (text/plain).
o A simple message, "Cookie set successfully!", is sent to inform the user.
How It Works
OUTPUT:
PROGRAM-17
AIM: Write a Java program to show user validation using Servlet.
THEORY:
1. login.jsp (Login Page)
Displays a login form that collects the user's email and password.
Includes JavaScript validation to check if the entered email is in a proper
format.
Submits the form to LoginServlet using a POST request.
1. Hardcoded Credentials
o User authentication is hardcoded (Rohan@gmail.com / Kxx6969).
o ◆ Fix: Use a database or a HashMap for user verification.
2. Lack of Error Handling
o No message is displayed if login fails.
o ◆ Fix: Redirect users back to login.jsp with an error message.
3. Session Management
o No session timeout or logout mechanism.
o ◆ Fix: Add a logout button and session invalidation
(session.invalidate()).
OUTPUT:
Login view:
1. Connection Issues
The database connection is opened but never closed, which can lead to resource leaks.
Fix: Close the Connection and PreparedStatement after execution.
The form submits data via GET, exposing parameters in the URL.
Fix: Change <form action=""> to <form action="" method="POST"> to secure
the data.
3. No Confirmation Message
<%
Connection con;
PreparedStatement pst;
String url,userName,password,driver;
Class.forName(driver);
con = DriverManager.getConnection(url, userName, password);
System.out.println(con);
pst.executeUpdate();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Inserting Data into Table</title>
</head>
<body>
<form action="">
<input type="text" name="name" placeholder="Name"><br>
<input type="text" name="rollNo" placeholder="RollNO"><br>
<input type="text" name="section" placeholder="Section"><br>
<input type="text" name="number" placeholder="Contact Number"><br>
<input type="submit" value="Insert">
</form>
</body>
</html>
OUTPUT:
PROGRAM-19
AIM: Write JSP program to implement form data validation.
THEORY:
1. Retrieves User Input
o Gets userName and password from the form submission.
2. Validates Credentials
o If userName is "admin" and password is "1234", the user is forwarded to
login.jsp.
o Otherwise, they are redirected to error.jsp.
3. Displays a Simple Login Form
o Users can enter their credentials.
o The form submits data via GET (but should use POST for security).
1. Security Issues
The form does not specify method="POST", so data is sent in the URL.
◆ Fix: Change <form action=""> to <form action="" method="POST">.
3. No Session Management
SOURCE CODE:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userName = request.getParameter("userName");
String userPassword = request.getParameter("password");
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
rd.forward(request,response);
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form Data Validation</title>
</head>
<body>
<form action="">
<input type="text" name="userName" placeholder="User Name">
<input type="text" name="password" placeholder="Password">
<input type="submit" value="login">
</form>
</body>
</html>
OUTPUT:
PROGRAM-20
AIM: Create a database in MySQL using JSP and perform insertion and
retrieval operations.
THEORY:
JSP (JavaServer Pages) is used to create dynamic web applications by embedding Java code
within HTML. When integrating JSP with MySQL, we can perform CRUD (Create, Read,
Update, Delete) operations on a database.
1. Database Setup
sql
CopyEdit
CREATE DATABASE IF NOT EXISTS mydatabase;
USE mydatabase;
CREATE DATABASE creates a database named mydatabase if it does not already exist.
CREATE TABLE creates a users table with three columns: id, username, and email.
This page contains an HTML form to collect user details (username, email) and send them to
the insert.jsp page.
Key Points:
Key Concepts:
java
CopyEdit
Class.forName("com.mysql.cj.jdbc.Driver");
Database Connection:
java
CopyEdit
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root",
"");
java
CopyEdit
String sql = "INSERT INTO users (username, email) VALUES (?, ?)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, email);
pstmt.executeUpdate();
Key Concepts:
java
CopyEdit
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
out.println(rs.getString("username") + " - " + rs.getString("email"));
}
JDBC is a Java API used to connect Java applications with a database. The main steps
include:
OUTPUT:
PROGRAM-21
AIM: Create a Java JSP login and Sign Up form with Session using MySQL.
THEORY:
This program demonstrates the development of a web application using JavaServer Pages
(JSP) to implement login and sign up functionality with session management, backed by a
MySQL database.
Login Functionality:
● Users can enter their credentials (username and password) into the login form.
● Upon submission, the program verifies the entered credentials against the data stored in
the MySQL database.
● If the credentials match, a session is created to maintain the user's login state. Sign Up
Functionality:
● Users can register by providing required information (username, password, email, etc.) in
the sign-up form.
● Upon submission, the program stores the user's information in the MySQL database for
future login.
Session Management:
● A session is created upon successful login, allowing users to access restricted areas of the
application without reauthentication.
● Sessions are managed to ensure security and prevent unauthorized access. MySQL
Database
Integration:
● The program connects to a MySQL database to store user credentials and registration
details securely.
SOURCE CODE:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login</title>
</head>
<body>
<form action="login.jsp" method="post">
User name :<input type="text" name="usr" /><br>
password :<input type="password" name="password" /><br>
<input type="submit" />
</form>
<p>New user. <a href="register.html">Login Here</a>.
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String userid=request.getParameter("userid");
session.putValue("userid",userid);
String password=request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection
con
DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","");
Statement st= con.createStatement();
=
ResultSet rs=st.executeQuery("select * from users where userid='"+userid+"' and
password='"+password+"'");
try{ rs.next
();
if(rs.getString("password").equals(password)&&rs.getString("userid").equals(userid))
{
out.println("Welcome " +userid);
}
else{
out.println("Invalid password or username.");
}
}
catch (Exception e) {
e.printStackTrace();
}
%>
register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>new registration</title>
</head>
<body>
<form action="reg-process.jsp" method="post">
First name :<input type="text" name="fname" />
Last name :<input type="text" name="lname" />
Email ID :<input type="text" name="email" />
User name :<input type="text" name="userid" />
password :<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>
reg-process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
String userid=request.getParameter("userid");
String password=request.getParameter("password");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
conn
DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
Statement st=conn.createStatement();
=
int
i=st.executeUpdate("insert
into
users(fname,lname,email,userid,password)values('"+fname+"','"+lname+"','"+email+"'
,'"+userid+"','"+password+"')");
out.println("Thank you for register ! Please <a href='index.html'>Login</a> to
continue.");
}
catch(Exception e){
System.out.print(e);
e.printStackTrace();
}
%>
OUTPUT:
PROGRAM-22
AIM: Create Employee Registration Form using a combination of JSP, Servlet,
JDBC and MySQL database.
THEORY:
This program demonstrates a simple Employee Registration System using Java
Servlets, JSP, and MySQL database connectivity.
Workflow:
SOURCE CODE:
registrationForm.jsp
<!DOCTYPE html>
<html>
<head>
<title>Employee Registration Form</title>
</head>
<body>
<h2>Employee Registration Form</h2>
<form action="RegistrationServlet" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
Department: <input type="text" name="department"><br>
<input type="submit" value="Register">
</form>
</body>
</html>
RegistrationServlet.java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse res
ponse)
throws
ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String department = request.getParameter("department");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase",
"username",
"password");
PreparedStatement ps = con.prepareStatement("INSERT INTO employee (n
ame,
email,
department) VALUES (?, ?, ?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, department);
int rowsAffected = ps.executeUpdate();
if (rowsAffected > 0) {
response.sendRedirect("registrationSuccess.jsp");
} else {
response.sendRedirect("registrationError.jsp");
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
registrationSuccess.jsp
<!DOCTYPE html>
<html>
<head>
<title>Registration Success</title>
</head>
<body>
<h2>Registration Successful!</h2>
<a href="registrationForm.jsp">Go back to Registration Form</a>
</body>
</html>
OUTPUT:
PROGRAM-23
AIM: Develop a small web program using Servlets, JSPs with Database
connectivity.
THEORY:
The program aims to showcase the integration of Java Servlets, JavaServer Pages (JSP), and
database connectivity to develop a dynamic web application.
● Servlets handle HTTP requests and responses, serving as the backbone for server-side
logic and processing.
● They interact with the database to fetch or manipulate data based on client requests.
● JSPs are used to create dynamic web pages by embedding Java code within HTML markup.
● They provide a user-friendly interface, presenting data fetched from the database via
servlets.
Database Connectivity:
● Servlets utilize JDBC to execute SQL queries, retrieve data, and update database records as
required.
Workflow:
1. Client Request Handling: Servlets receive HTTP requests from clients and perform
necessary processing.
2. Data Presentation: Servlets pass data to JSPs, which dynamically generate HTML content
for presentation.
3. Database Interaction: Servlets interact with the database using JDBC to retrieve or
manipulate data.
4. Response Generation: Servlets send the processed data to clients as HTTP responses.
SOURCE CODE:
UserServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class UserServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if ("register".equals(action)) {
register(request, response);
} else if ("login".equals(action))
{ login(request, response);
}
}
private void register(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection
DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb",
"password");
con
=
"username",
PreparedStatement pst = con.prepareStatement("INSERT INTO users
(username, password) VALUES (?, ?)");
pst.setString(1, username);
pst.setString(2, password);
pst.executeUpdate();
con.close();
response.sendRedirect("registration_success.jsp");
} catch (Exception e) {
e.printStackTrace();
}
}
private void login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb", "username",
"password");
PreparedStatement pst = con.prepareStatement("SELECT * FROM users
WHERE username=? AND password=?");
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
// Successful login
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
} else {
// Invalid credentials
response.sendRedirect("login.jsp?error=true");
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
registration.jsp
<html>
<head><title>User Registration</title></head>
<body>
<h2>User Registration</h2>
<form action="UserServlet" method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="hidden" name="action" value="register">
<input type="submit" value="Register">
</form>
</body>
</html>
login.jsp
<html>
<head><title>User Login</title></head>
<body>
<h2>User Login</h2>
<form action="UserServlet" method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="hidden" name="action" value="login">
<input type="submit" value="Login">
<% if ("true".equals(request.getParameter("error"))) { %>
<p style="color:red;">Invalid username or password</p>
<% } %>
</form>
</body>
</html>
registration_success.jsp
<html>
<head><title>Registration Success</title></head>
<body>
<h2>Registration Successful</h2>
<p>You have successfully registered.</p>
<a href="login.jsp">Login</a>
</body>
</html>
welcome.jsp
<html>
<head><title>Welcome</title></head>
<body>
<h2>Welcome, <%= session.getAttribute("username") %>!</h2>
<p>You are now logged in.</p>
</body>
</html>
OUTPUT:
PROGRAM-24
AIM: Create an RMI application where the server hosts a calculator service,
and the client can perform basic arithmetic operations remotely.
THEORY:
Remote Method Invocation (RMI) - Calculator Application
Introduction
Remote Method Invocation (RMI) is a Java API that allows an object residing
in one Java Virtual Machine (JVM) to invoke methods on an object located in
another JVM, possibly on a different machine. This enables distributed
computing, where clients can access services provided by remote servers.
Objective
A server hosts a remote calculator object that performs basic arithmetic operations
(addition, subtraction, multiplication, division).
A client accesses the calculator service remotely and invokes these operations.
1. Define the Remote Interface: The interface specifies the methods that clients can
call remotely.
2. Implement the Remote Object: The implementation class provides the logic for
arithmetic operations.
3. Start the RMI Server: The server registers the remote object with the RMI registry,
making it available for clients.
4. Client Invokes Remote Methods: The client looks up the calculator service and calls
its methods over the network.
Advantages of RMI
Potential Enhancements
THEORY:
Hibernate-Based CRUD Application for Student Management - Theory
1. Hibernate Configuration
3. Hibernate Utility
Reduces Boilerplate Code: Eliminates the need for writing raw SQL
queries.
Database Independence: Supports multiple databases without changing
code.
Automatic Schema Management: Handles table creation and updates.
Improved Performance: Uses caching mechanisms to enhance query
execution.
Simplifies Relationships: Easily manages complex relationships (one-to-
many, many-to-many).