[go: up one dir, main page]

0% found this document useful (0 votes)
35 views30 pages

COMJAVA

The document outlines multiple Java servlet and JSP programs aimed at user interaction and database operations. Key functionalities include recognizing first-time visitors with cookies, setting user preferences via cookies, user validation through login forms, and data insertion into MySQL databases. Each program highlights issues and improvements, emphasizing security, session management, and best practices in web application development.

Uploaded by

Akshat Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views30 pages

COMJAVA

The document outlines multiple Java servlet and JSP programs aimed at user interaction and database operations. Key functionalities include recognizing first-time visitors with cookies, setting user preferences via cookies, user validation through login forms, and data insertion into MySQL databases. Each program highlights issues and improvements, emphasizing security, session management, and best practices in web application development.

Uploaded by

Akshat Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

PROGRAM-15

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

 The first time a user visits /setCookie, the cookie is set.


 On subsequent visits, the browser sends the cookie back with each request (until it
expires or is deleted).
 This cookie can later be read by other servlets to personalize the user experience.

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.

2. LoginServlet.java (Authentication Servlet)

 Retrieves user credentials (emailId and password) from the form


submission.
 Prints credentials to the console (for debugging purposes).
 Validates login details:
o If email = "Rohan@gmail.com" and password = "Kxx6969",
authentication succeeds.
o A new session is created, storing the emailId.
o Redirects the user to welcome.jsp.
 If credentials don’t match, it simply does nothing (no error handling
implemented).

3. welcome.jsp (Welcome Page)

 Displays a welcome message, fetching the email from the session.


 If the user is authenticated, it will show:
"Welcome Rohan@gmail.com".

Issues and Improvements

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:

Client-side validation output:


PROGRAM-18
AIM: Write a Java program to insert data into a table using JSP.
THEORY:
1. Database Connection
o The JSP page loads the Oracle JDBC driver.
o Establishes a connection using:
 Username: "xyz"
 Password: "123"
 URL: "jdbc:oracle:thin:@localhost:1521:XE" (Oracle XE instance)
2. Retrieving Form Data
o Extracts name, roll number, section, and contact number from the
request parameters.
3. Executing the Insert Query
o Uses a prepared statement to prevent SQL injection.
o Inserts the values into the student table.
4. Form for User Input
o Provides an HTML form where users can enter student details.
o On submission, the page reloads and executes the insertion.

Issues & Improvements

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.

2. SQL Injection Risk

 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

 Users don’t get feedback if insertion is successful or failed.


 Fix: Display a success/failure message after inserting data.

4. Mixing Java & HTML in JSP

 Problem: Embedding Java code in JSP is not a good practice.


 Fix: Use MVC architecture by moving database operations to a Servlet.
SOURCE CODE:
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%
Connection con;
PreparedStatement pst;
String url,userName,password,driver;

userName = "Nadeem"; password


= "123";
url = "jdbc:oracle:thin:@localhost:1521:XE"; driver =
"oracle.jdbc.driver.OracleDriver";

Class.forName(driver);
con = DriverManager.getConnection(url, userName, password);

System.out.println(con);

String Name = request.getParameter("name"); String


rollNo = request.getParameter("rollNo"); String
section = request.getParameter("section");
String contactNo = request.getParameter("number");

String insertQuery = "insert into student values(?,?,?,?)";


pst = con.prepareStatement(insertQuery);
pst.setString(1, Name);
pst.setString(2, rollNo);
pst.setString(3, section);
pst.setString(4,contactNo);

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).

Issues & Improvements

1. Security Issues

 User credentials are hardcoded (easily hackable).


 ◆ Fix: Store credentials securely in a database.

2. Passwords are Exposed in URL

 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

 Once authenticated, the user is not tracked.


 ◆ Fix: Use HttpSession to maintain login state.

4. Mixing Java with JSP (Bad Practice)

 Business logic should be in a Servlet, not JSP.


 ◆ Fix: Move authentication logic to a Servlet.

SOURCE CODE:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<%
String userName = request.getParameter("userName");
String userPassword = request.getParameter("password");

if(userName.equals("admin") && userPassword.equals("1234"))


{
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.forward(request,response);

}
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

Before working with JSP and MySQL, we must set up a database.

SQL Commands to Create a Database and Table

sql
CopyEdit
CREATE DATABASE IF NOT EXISTS mydatabase;
USE mydatabase;

CREATE TABLE IF NOT EXISTS users (


id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
);

 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.

2. JSP Pages for User Operations

A. index.jsp (Form for User Input)

This page contains an HTML form to collect user details (username, email) and send them to
the insert.jsp page.

Key Points:

 Uses <form> to capture user input.


 The action="insert.jsp" directs the form submission to insert.jsp.
 method="post" ensures data is sent securely.

B. insert.jsp (Insert Data into MySQL)


This JSP file:

1. Retrieves user input using request.getParameter().


2. Establishes a database connection using JDBC (Java Database Connectivity).
3. Executes an SQL INSERT query to store user data.

Key Concepts:

 JDBC Driver Loading:

java
CopyEdit
Class.forName("com.mysql.cj.jdbc.Driver");

 Database Connection:

java
CopyEdit
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root",
"");

 SQL Execution Using PreparedStatement:

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();

C. retrieve.jsp (Retrieve Data from MySQL)

This JSP file:

1. Connects to the MySQL database.


2. Executes an SQL SELECT query to retrieve all users.
3. Displays user data in an HTML table.

Key Concepts:

 Fetching Data Using ResultSet:

java
CopyEdit
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
out.println(rs.getString("username") + " - " + rs.getString("email"));
}

 Looping Through Results:


o The while (rs.next()) loop fetches all rows from the database.

3. JDBC (Java Database Connectivity)

JDBC is a Java API used to connect Java applications with a database. The main steps
include:

1. Load the JDBC Driver


o Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish a Database Connection
o DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"root", "");
3. Execute SQL Queries
o Using PreparedStatement to insert or fetch data.
4. Close the Connection
o con.close(); prevents memory leaks.

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.

Key Features of the Program:

1. Employee Registration Form (registrationForm.jsp):


o A form where users input their name, email, and department.
o Sends data to RegistrationServlet using the POST method.
2. Servlet for Backend Processing (RegistrationServlet.java):
o Handles form submission and inserts data into the MySQL
database.
o Uses JDBC for database connectivity.
o Redirects users to registrationSuccess.jsp if registration is successful,
else to registrationError.jsp.
3. Database Connectivity:
o Establishes a connection with MySQL using DriverManager.
o Executes an INSERT query to store employee details.
4. Success Page (registrationSuccess.jsp):
o Confirms successful registration.

Workflow:

1. User fills out the registration form and submits it.


2. The servlet processes the request and inserts data into the database.
3. If successful, the user is redirected to the success page; otherwise, an
error page is shown.

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 for Backend Processing:

● 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.

JavaServer Pages (JSP) for Presentation:

● 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:

● Database connectivity is established using JDBC (Java Database Connectivity) to interact


with the backend database.

● 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

This RMI application demonstrates a Calculator Service, where:

 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.

Key Components of the RMI Application

1. Remote Interface (Calculator.java)


o Defines the methods that can be invoked remotely.
o Extends java.rmi.Remote and declares methods that throw RemoteException.
2. Remote Implementation (CalculatorImpl.java)
o Implements the methods defined in the remote interface.
o Extends UnicastRemoteObject to make the object available for remote access.
3. Server (CalculatorServer.java)
o Registers the remote object using RMI Registry so that clients can look it up.
o Uses LocateRegistry.createRegistry(port) to create an RMI registry.
4. Client (CalculatorClient.java)
o Looks up the remote object from the RMI Registry and invokes methods on it.

Workflow of the RMI Application

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.

Steps to Run the RMI Application

1. Compile all Java files (javac *.java).


2. Start the RMI Registry (rmiregistry).
3. Run the Server (java CalculatorServer) to bind the remote object.
4. Run the Client (java CalculatorClient) to perform remote calculations.

Advantages of RMI

✔ Platform Independence: Works across different operating systems.


✔ Encapsulation of Network Communication: RMI handles communication
between objects transparently.
✔ Object-Oriented Approach: Unlike traditional client-server models, RMI allows
remote method invocation on Java objects.

Potential Enhancements

 Security Enhancements: Implement security policies to restrict unauthorized access.


 Graphical User Interface (GUI): Provide a GUI-based calculator client.
 Logging & Error Handling: Improve robustness by handling network failures and
exceptions.
PROGRAM-25
AIM: Create a Hibernate application to perform CRUD (Create, Read, Update,
Delete) operations on a Student entity.

THEORY:
Hibernate-Based CRUD Application for Student Management - Theory

This application demonstrates the Hibernate framework for performing CRUD


(Create, Read, Update, Delete) operations on a Student entity using a
relational database. Hibernate is an ORM (Object-Relational Mapping)
framework that simplifies database interaction in Java applications.

Key Components of the Application

1. Hibernate Configuration

 Hibernate requires a configuration file (hibernate.cfg.xml) to set up


database connection properties.
 This file includes details such as:
o Database URL, username, and password.
o Hibernate dialect (SQL language support for different databases).
o JDBC driver class for database connectivity.
o hbm2ddl.auto property to define how Hibernate updates or
creates tables.

2. Student Entity (Model)

 The Student class is mapped to a database table using JPA annotations


such as:
o @Entity → Declares the class as an entity.
o @Table(name="students") → Specifies the database table name.
o @Id and @GeneratedValue → Define the primary key with auto-
increment.
 This class contains fields (name, email, age) and corresponding
getters/setters.

3. Hibernate Utility

 A SessionFactory object is required to manage database sessions.


 The HibernateUtil class initializes and provides the SessionFactory object,
which is essential for creating, retrieving, updating, and deleting data.

4. DAO (Data Access Object) Layer

 This layer is responsible for performing database operations using


Hibernate.
 The StudentDAO class contains methods for:
1. Create (Insert): Adds a new student to the database.
2. Read (Retrieve): Fetches a student by ID or retrieves all students.
3. Update: Modifies an existing student’s details.
4. Delete: Removes a student record from the database.
 These methods use Hibernate’s Session API to interact with the
database.

5. Main Application (Business Logic)

 The MainApp class acts as the entry point of the program.


 It creates an instance of StudentDAO and calls its methods to perform:
o Inserting a new student.
o Fetching student details.
o Updating student information.
o Deleting a student record.
 The operations are executed using Hibernate’s session and transaction
management.

Workflow of the Application

1. Database Connection: Hibernate establishes a connection with MySQL


(or another relational database).
2. Student Registration (Create): A student is added using Hibernate’s
session.save().
3. Fetching Student Data (Read): The application retrieves student details
using session.get().
4. Updating Student Information (Update): Hibernate updates an existing
record with session.update().
5. Removing a Student (Delete): The record is deleted using
session.delete().
6. Session and Transaction Management: Hibernate ensures data
consistency by managing transactions.
Advantages of Using Hibernate

 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).

You might also like