0% found this document useful (0 votes)
8 views9 pages

Ajt PRS

The document outlines practical exercises for Advanced Java, focusing on database management, chat application implementation, and Hibernate framework usage. It includes detailed steps for creating a student database, implementing a chat application using TCP, and building a simple Hibernate framework for CRUD operations. Additionally, it covers RMI applications for remote method invocation and the use of Hibernate Query Language for database interactions.

Uploaded by

Piyush Patil
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)
8 views9 pages

Ajt PRS

The document outlines practical exercises for Advanced Java, focusing on database management, chat application implementation, and Hibernate framework usage. It includes detailed steps for creating a student database, implementing a chat application using TCP, and building a simple Hibernate framework for CRUD operations. Additionally, it covers RMI applications for remote method invocation and the use of Hibernate Query Language for database interactions.

Uploaded by

Piyush Patil
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/ 9

IU2241230188 ADVANCED JAVA(AJT) 6CSE-E

Practical-9

Aim: Create database of student subject-wise data and retrieve all data using JSP and generate xml
structure along with DTD and XML Schema definition Write down a program which demonstrates the
core tag of JSTL

Basic Steps to perform aim : -


1. Create Table (Apache Derby):
CREATE TABLE STUDENT_SUBJECT (ID INT PRIMARY KEY, NAME VARCHAR(255), SUBJECT VARCHAR(255), MARKS INT);

2. Add Required JARs:


derbyclient.jar, jstl-1.2.jar, standard.jar

3. DBConnection.java (Utility for DB Connection)


package com.util; public class DBConnection { public static Connection getConnection() throws Exception {
Class.forName("org.apache.derby.jdbc.ClientDriver"); return
DriverManager.getConnection("jdbc:derby://localhost:1527/StudentDB;create=true", "root", "root"); } }

4. FetchStudentServlet.java (Fetch all student data and forward to JSP)


package com.servlet; import com.util.DBConnection; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*;
import java.util.*; public class FetchStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException { try { Connection con = DBConnection.getConnection(); Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM STUDENT_SUBJECT"); List<Map<String, String>> list = new ArrayList<>(); while (rs.next()) {
Map<String, String> m = new HashMap<>(); m.put("id", rs.getString(1)); m.put("name", rs.getString(2)); m.put("subject", rs.getString(3));
m.put("marks", rs.getString(4)); list.add(m); } req.setAttribute("students", list); req.getRequestDispatcher("students.jsp").forward(req, res); }
catch (Exception e) { e.printStackTrace(); } } }

5. students.jsp (JSP to generate XML structure using JSTL)


<%@ page contentType="text/xml" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <students> <c:forEach var="s"
items="${students}"> <student> <id><c:out value="${s.id}" /></id> <name><c:out value="${s.name}" /></name> <subject><c:out
value="${s.subject}" /></subject> <marks><c:out value="${s.marks}" /></marks> </student> </c:forEach> </students>

6. student.dtd (DTD file for XML validation)


<!ELEMENT students (student*)> <!ELEMENT student (id, name, subject, marks)> <!ELEMENT id (#PCDATA)> <!ELEMENT name (#PCDATA)>
<!ELEMENT subject (#PCDATA)> <!ELEMENT marks (#PCDATA)>

7. student.xsd (XML Schema Definition)


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="students"> <xs:complexType> <xs:sequence>
<xs:element name="student" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="id" type="xs:int"/>
<xs:element name="name" type="xs:string"/> <xs:element name="subject" type="xs:string"/> <xs:element name="marks" type="xs:int"/>
</xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

8. JSTL Core Tag Demo (demo.jsp)


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:set var="name" value="Jigar Sindhi" /> <p>Welcome, <c:out
value="${name}" /></p> <c:if test="${10 > 5}"><p>Condition is True</p></c:if> <c:forEach var="i" begin="1" end="3"><p>Count:
${i}</p></c:forEach> <c:choose> <c:when test="${name eq 'Jigar Sindhi'}"><p>Hello Jigar!</p></c:when> <c:otherwise><p>Guest
User</p></c:otherwise> </c:choose>

OUTPUT : -

FORM FOR INSERTING DATA : - BASIC OUTPUT ON THE WEB : - XML – STYLED O/P : -

1
IU2241230188 ADVANCED JAVA(AJT) 6CSE-E

Practical-10

Aim: Implement a chat application using TCP. Write an RMI application where client supplies two numbers &
server response by addition. Provide your custom security policy for this application.

Basic Steps to implement a chat application using TCP

Chat Application: Server Code (ChatServer.java)

import java.io.*; import java.net.*; public class ChatServer { public static void main(String[] args) { try { ServerSocket server = new
ServerSocket(1234); System.out.println("Server started..."); while(true) { Socket clientSocket = server.accept(); new
ClientHandler(clientSocket).start(); } } catch(Exception e) { System.out.println(e); } } static class ClientHandler extends Thread { Socket
clientSocket; ClientHandler(Socket socket) { this.clientSocket = socket; } public void run() { try { BufferedReader in = new
BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new
PrintWriter(clientSocket.getOutputStream(), true); String message; while((message = in.readLine()) != null) { System.out.println("Client: " +
message); out.println("Server: " + message); } } catch(Exception e) { System.out.println(e); } finally { try { clientSocket.close(); }
catch(IOException e) { System.out.println(e); } } } } }

Chat Application: Client Code (ChatClient.java)

import java.io.*;import java.net.*;public class ChatClient {public static void main(String[] args) {try { Socket socket=new Socket("localhost",
1234); BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new
PrintWriter(socket.getOutputStream(), true); BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));String
message; while(true) {System.out.print("Enter message: "); message =
userInput.readLine();out.println(message);System.out.println(in.readLine()); }} catch(Exception e){System.out.println(e);}}}}

Instructions for Running the Chat Application:

1. Compile the Code: Save the server code in a file named ChatServer.java. Save the client code in a file named ChatClient.java.
Compile both the server and client code using the following commands:

javac ChatServer.java

javac ChatClient.java

2. Run the Server: Run the server in one terminal:

java ChatServer - This will start the server on port 1234.

3. Run the Client: Run the client in another terminal:

java ChatClient - You can run multiple clients as needed to simulate chat communication.

4. Chat Communication: The client can send messages, and the server will echo the same message back.

OUTPUT : -

Basic Steps to implement RMI application where client supplies two numbers & server responds by addition.
Provide the custom security policy for this application.

1. AddNumbers.java (RMI Interface):

import java.rmi.*; public interface AddNumbers extends Remote { public int add(int num1, int num2) throws RemoteException; }

2. AddNumbersImpl.java (RMI Server Implementation):

import java.rmi.*; import java.rmi.server.*; public class AddNumbersImpl extends UnicastRemoteObject implements AddNumbers { public
AddNumbersImpl() throws RemoteException { super(); } public int add(int num1, int num2) throws RemoteException { return num1 +
num2; } public static void main(String[] args) { try { AddNumbersImpl obj = new AddNumbersImpl();

1
IU2241230188 ADVANCED JAVA(AJT) 6CSE-E

Naming.rebind("rmi://localhost:1099/AddNumbers", obj); System.out.println("Server ready..."); } catch(Exception e) {


System.out.println("Server Error: " + e); } } }

3. AddNumbersClient.java (RMI Client):

import java.rmi.*; public class AddNumbersClient { public static void main(String[] args) { try { AddNumbers obj = (AddNumbers)
Naming.lookup("rmi://localhost:1099/AddNumbers"); int result = obj.add(10, 20); System.out.println("Result: " + result); } catch(Exception
e) { System.out.println("Client Error: " + e); } } }

4. security.policy (Custom Security Policy): grant { permission java.security.AllPermission; };

5. Steps to Run:
1. Open CMD
2. Make the path to the relevant folder where all files are located

3. Compile Java Files:

javac *.java

4. Start RMI Registry:

start rmiregistry

5. Run Server:

java AddNumbersImpl

6. Freeing port’s from its existing user files

7. Run Client:

java AddNumbersClient

8. (Optional) Security Policy file: Make sure the security.policy file is used when running with a policy:

java -Djava.security.manager -Djava.security.policy=security.policy AddNumbersImpl

2
IU2241230188 ADVANCED JAVA(AJT) 6CSE-E

Practical-11
Aim: Implement simple framework using hibernates and studies its architecture
Basic Steps to Implement a Simple Hibernate Framework and Study Its Architecture

Step 1: Create the Entity Class

• Create a POJO class (e.g., Student.java)


• Use @Entity to map the class to a DB table.
• Use @Id to define the primary key field.

Step 2: Configure hibernate.cfg.xml

• Define database connection properties (URL, username, password).


• Specify dialect (e.g., DerbyDialect for Apache Derby).
• Add mapping for entity class using <mapping class="com.Student"/>.

Step 3: Create HibernateUtil.java

• Build and provide a single SessionFactory object.


• Use Configuration().configure().buildSessionFactory() to read the config file and build the
session factory.

Step 4: Write Main Logic in MainApp.java

• Get Session from HibernateUtil.


• Begin a transaction.
• Create an object of Student.
• Save the object using session.save().
• Commit the transaction and close the session.

Step 5: Understand Hibernate Architecture

1. Configuration Layer – Loads hibernate.cfg.xml


2. SessionFactory – Heavyweight, created once, gives sessions.
3. Session – Opens connection to DB for performing operations.
4. Transaction – Controls commit/rollback.

1. Entity Class - Student.java

package com; import jakarta.persistence.Entity; import jakarta.persistence.Id; @Entity public class Student { @Id
private int id; private String name; private String course; // Constructors public Student() {} public Student(int id, String
name, String course) { this.id = id; this.name = name; this.course = course; } // Getters and Setters
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public String getCourse() { return course; }
public void setCourse(String course) { this.course = course; } }

2. Hibernate Configuration - hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration


DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-
factory> <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property> <property
name="hibernate.connection.url">jdbc:derby://localhost:1527/StudentDB</property> <property
name="hibernate.connection.username">root</property> <property
name="hibernate.connection.password">root</property> <property
name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property> <property

1
IU2241230188 ADVANCED JAVA(AJT) 6CSE-E

name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> <mapping


class="com.Student"/></session-factory></hibernate-configuration>

3. Hibernate Utility - HibernateUtil.java

package com; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil {


private static final SessionFactory sessionFactory; static { try { sessionFactory = new
Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } }
public static SessionFactory getSessionFactory() { return sessionFactory; }}

4. Main Application - MainApp.java

package com; import org.hibernate.Session; import org.hibernate.Transaction; public class MainApp { public static void
main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction =
session.beginTransaction(); Student student = new Student(6, "HibernateUser", "ORM with Hibernate");
session.save(student); transaction.commit(); session.close(); System.out.println("Student record inserted successfully using
Hibernate framework."); }}

OUTPUT : -

Architecture Summary:

1. Configuration Layer: Reads hibernate.cfg.xml to setup DB properties.

2. SessionFactory: Thread-safe object that provides session instances.

3. Session: Represents a unit of work with DB.

4. Transaction: Manages commit and rollback.

5. Entity Class: POJO mapped to DB table using annotations.

2
IU2241230188 ADVANCED JAVA(AJT) 6CSE-E

Practical-12
Aim: Use Hibernate Query Language to insert, update and delete records in the database.
Steps for HQL-based CRUD Operations in Hibernate:

1. Configure Hibernate: Create a configuration file (hibernate.cfg.xml) to set up database connection and
mapping.

2. Create Entity Class: Use Java classes with annotations like @Entity, @Id, @Column to represent database
tables.

3. Build SessionFactory: Use Configuration().configure().buildSessionFactory() to get a SessionFactory.

4. Open Session: Use sessionFactory.openSession() to obtain a session.

5. Begin Transaction: session.beginTransaction() starts a new transaction.

6. Insert Record: Use HQL "INSERT INTO" query or session.save() to insert a new record.

7. Update Record: Use HQL "UPDATE" query with session.createQuery() and executeUpdate().

8. Delete Record: Use HQL "DELETE" query with conditions to remove records.

9. Commit Transaction: Use transaction.commit() to save changes.

10. Close Session: Always close session and SessionFactory.CREATE DATABASE STUDENTDB

To Run Steps for CRUD Operations in Java using Hibernate (Apache Derby)

1. Add Required JARs: hibernate-core, hibernate-commons-annotations, hibernate-jpa, antlr, javax.persistence,


dom4j, jboss-logging, derbyclient, derby.

2. Create Apache Derby DB: No explicit DB creation in Derby client mode, it’s auto-created on connect (StudentDB).

3. Create Table: Table is auto-created by Hibernate using hbm2ddl.auto=update.

Configure Hibernate : hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration


DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-
factory><property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property><property
name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property><property
name="hibernate.connection.url">jdbc:derby://localhost:1527/StudentDB;create=true</property><property
name="hibernate.connection.username">root</property><property
name="hibernate.connection.password">root</property><property
name="hibernate.hbm2ddl.auto">update</property><property name="hibernate.show_sql">true</property><mapping
class="com.Student"/></session-factory></hibernate-configuration>

Create Student Entity Class : Student.java

package com; import javax.persistence.*; @Entity @Table(name="STUDENT") public class Student { @Id private int id; private
String name; private int age; private String course; public Student() {} public Student(int id, String name, int age, String course)
{ this.id = id; this.name = name; this.age = age; this.course = course; } public int getId() { return id; } public void setId(int id) {
this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int
getAge() { return age; } public void setAge(int age) { this.age = age; } public String getCourse() { return course; } public void
setCourse(String course) { this.course = course; } }

HibernateUtil.java

package com; import org.hibernate.*; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final
SessionFactory factory; static { try { factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) {
throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return factory; } }

1
IU2241230188 ADVANCED JAVA(AJT) 6CSE-E

InsertStudent.java (Using HQL)

package com; import org.hibernate.*; import java.util.Scanner; public class InsertStudent { public static void main(String[]
args) { Scanner sc = new Scanner(System.in); System.out.print("Enter ID: "); int id = sc.nextInt(); sc.nextLine();
System.out.print("Enter Name: "); String name = sc.nextLine(); System.out.print("Enter Age: "); int age = sc.nextInt();
sc.nextLine(); System.out.print("Enter Course: "); String course = sc.nextLine(); Session session =
HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); Student s = new Student(id,
name, age, course); session.save(s); tx.commit(); session.close(); System.out.println("✔ Student Inserted!"); } }

UpdateStudent.java (Using HQL)

package com; import org.hibernate.*; import java.util.Scanner; public class UpdateStudent { public static void main(String[]
args) { Scanner sc = new Scanner(System.in); System.out.print("Enter ID to Update: "); int id = sc.nextInt(); sc.nextLine();
System.out.print("New Name: "); String name = sc.nextLine(); System.out.print("New Age: "); int age = sc.nextInt();
sc.nextLine(); System.out.print("New Course: "); String course = sc.nextLine(); Session session =
HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); String hql = "UPDATE Student
SET name = :name, age = :age, course = :course WHERE id = :id"; Query query = session.createQuery(hql);
query.setParameter("name", name); query.setParameter("age", age); query.setParameter("course", course);
query.setParameter("id", id); int result = query.executeUpdate(); tx.commit(); session.close(); System.out.println(result > 0 ?
"✔ Updated Successfully!" : "+ Record not found!"); } }

DeleteStudent.java (Using HQL)

package com; import org.hibernate.*; import java.util.Scanner; public class DeleteStudent { public static void main(String[]
args) { Scanner sc = new Scanner(System.in); System.out.print("Enter ID to Delete: "); int id = sc.nextInt(); Session session =
HibernateUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); String hql = "DELETE FROM
Student WHERE id = :id"; Query query = session.createQuery(hql); query.setParameter("id", id); int result =
query.executeUpdate(); tx.commit(); session.close(); System.out.println(result > 0 ? "✔ Deleted Successfully!" : "+ Record
not found!"); } }

OUTPUT SCREENSHOTS : -

Insert data

Update data

Delete data

2
IU2241230188 ADVANCED JAVA(AJT) 6CSE-E

Practical-13
Aim: Demonstrate CRUD operation using DAO and Spring Framework API.
Basic Steps to Spring-based Java application which performs CRUD operations on a STUDENT table
using DAO pattern and Apache Derby database.
Table Structure (Apache Derby):

CREATE TABLE STUDENT (ID INT PRIMARY KEY, NAME VARCHAR(255), AGE INT, COURSE VARCHAR(255));

Steps for CRUD Operations using Spring Framework & DAO:

1. Add Required JARs:

• spring-core.jar, spring-beans.jar, spring-context.jar, spring-jdbc.jar

• derbyclient.jar (Apache Derby JDBC)

2. Student.java (Model Class)

package com.model; public class Student { private int id; private String name; private int age; private String course; public
Student() {} public Student(int id, String name, int age, String course) { this.id = id; this.name = name; this.age = age;
this.course = course; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return
name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int
age) { this.age = age; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course;
}}

3. StudentDAO.java (DAO Interface)

package com.dao; import com.model.Student; import java.util.*; public interface StudentDAO { public int insert(Student s);
public int update(Student s); public int delete(int id); public List<Student> getAll(); }

4. StudentDAOImpl.java (DAO Implementation)

package com.dao; import com.model.Student; import java.util.*; import org.springframework.jdbc.core.*; import


javax.sql.DataSource; public class StudentDAOImpl implements StudentDAO { private JdbcTemplate jdbcTemplate; public
void setDataSource(DataSource ds) { this.jdbcTemplate = new JdbcTemplate(ds); } public int insert(Student s) { return
jdbcTemplate.update("INSERT INTO STUDENT VALUES (?, ?, ?, ?)", s.getId(), s.getName(), s.getAge(), s.getCourse()); } public
int update(Student s) { return jdbcTemplate.update("UPDATE STUDENT SET NAME=?, AGE=?, COURSE=? WHERE ID=?",
s.getName(), s.getAge(), s.getCourse(), s.getId()); } public int delete(int id) { return jdbcTemplate.update("DELETE FROM
STUDENT WHERE ID=?", id); } public List<Student> getAll() { return jdbcTemplate.query("SELECT * FROM STUDENT", (rs,
rowNum) -> new Student(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4))); } }

5. applicationContext.xml (Spring Config File)

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-


instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName"
value="org.apache.derby.jdbc.ClientDriver"/> <property name="url"
value="jdbc:derby://localhost:1527/StudentDB;create=true"/> <property name="username" value="root"/> <property
name="password" value="root"/> </bean> <bean id="studentDAO" class="com.dao.StudentDAOImpl"> <property
name="dataSource" ref="dataSource"/> </bean> </beans>

6. TestStudent.java (Main App)

package com.main; import com.model.Student; import com.dao.StudentDAO; import


org.springframework.context.ApplicationContext; import
org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.*; public class TestStudent { public
static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDAO dao = (StudentDAO) ctx.getBean("studentDAO"); dao.insert(new Student(1, "Jigar", 20, "CSE"));

1
IU2241230188 ADVANCED JAVA(AJT) 6CSE-E

dao.update(new Student(1, "Jigar Sindhi", 21, "AI/ML")); dao.delete(1); List<Student> list = dao.getAll(); for (Student s : list)
System.out.println(s.getId() + " " + s.getName() + " " + s.getAge() + " " + s.getCourse()); } }

OUTPUT : -

INSERT DATA

UPDATE DATA

DELETE DATA

You might also like