0% found this document useful (0 votes)
10 views52 pages

Advanced Java Lab Manual for CSE Students

The document is a lab manual for the Advanced Java Lab course at the Global Institute of Technology, detailing various experiments and programming tasks related to Java Swing, JDBC, and Spring Boot. It includes a list of experiments, sample code for GUI applications, and viva questions covering Java concepts. The manual is intended for third-year Computer Science and Engineering students during the 2025-2026 academic session.

Uploaded by

23egjcs115
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)
10 views52 pages

Advanced Java Lab Manual for CSE Students

The document is a lab manual for the Advanced Java Lab course at the Global Institute of Technology, detailing various experiments and programming tasks related to Java Swing, JDBC, and Spring Boot. It includes a list of experiments, sample code for GUI applications, and viva questions covering Java concepts. The manual is intended for third-year Computer Science and Engineering students during the 2025-2026 academic session.

Uploaded by

23egjcs115
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

GLOBAL INSTITUTE OF TECHNOLOGY

​ Department of CSE\IT\AI&DS
Advance Java Lab
Student Name=Chirag jain
Roll no =23EGJCS059
LAB MANUAL

Lab Name : Advance Java Lab


Lab Code​ : 5CS4-24
Branch : Computer Science & Engineering

Year ([Link].) :III Year/ VSem

Global Institute of Technology, Jaipur


​ Department of CSE\IT\AI&DS


GLOBAL INSTITUTE OF TECHNOLOGY

ADVANCED JAVA
PARTICLE RECORD

Submitted to: Submitted by:


Vikram Tailor Chirag Jain
Assist Professor, Dept. CSE 23EGJCS059

Department Of Computer Science & IT

Global Institute Of Technology

​ Jaipur (Rajasthan)-302020

Session: 2025-2026
INDEX

[Link] EXPERIMENTS DATE SIGNATURE

1 18-08-25
Write a Java program to demonstrate various Swing
components.

.2
Write a Java program to implement event handling on
Swing components. 18-08-25

3. 12-09-25
Develop a Swing-based Calculator application using
buttons, text fields, and event handling.

4 12-09-25
Write a Java program that establishes a connection
with a database using JDBC and displays all the
records from a specified table.

5
19-09-25
Write a Java program to insert a new record into a
table using a static SQL query (Statement).

6
19-09-25
Write a Java program to update an existing record in a
table using a dynamic query (PreparedStatement).

7
31-10-25
Write a Java program to demonstrate a Distributed
Application

8
04-11-25
Implementation of CRUD Operations using JPA with
Hibernate

9
05-11-25
Write a simple Spring Boot application that returns
“Hello World” as a web response.

10
07-11-25
Write a RESTful web service that performs
CRUD(Create, Read, Update, Delete) operations on
Employee data.
Experiment – 1
Title: Write a Java program to demonstrate various Swing components.

Program / Code:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class SwingComponents {

public static void main (String args[]) {


​ JFrame f = new JFrame();
​ [Link](null);
​ [Link](300, 250);
​ [Link](500, 300);

​ JLabel l1 = new JLabel("User Name");
​ [Link](30, 30, 100, 30);

​ JTextField t1 = new JTextField();
​ [Link](130, 30, 120, 30);

​ JLabel l2 = new JLabel("Password");
​ [Link](30, 80, 100, 30);

​ JPasswordField t2 = new JPasswordField();


​ [Link](130, 80, 120, 30);

​ JButton b =new JButton("Submit");
​ [Link](90, 120, 80, 30);

​ [Link](l1);
​ [Link](t1);
​ [Link](l2);
​ [Link](t2);
​ [Link](b);
​ [Link](true);
}

Viva Questions

1. What is Java?

Java is the high-level, object-oriented, robust, secure programming language,


platform-independent, high performance, Multithreaded, and portable programming
language. It was developed by James Gosling in June 1991. It can also be known as
the platform as it provides its own JRE and API.

2. List the features of Java Programming language.

There are the following features in Java Programming Language.

Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to
write the program in it.
Object-Oriented: Java follows the object-oriented paradigm which allows us to
maintain our code as the combination of different type of objects that incorporates both
data and behavior.

Portable: Java supports read-once-write-anywhere approach. We can execute the Java


program on every machine. Java program (.java) is converted to byte code (.class)
which can be easily run on every machine.

Platform Independent: Java is a platform independent programming language. It is


different from other programming languages like C and C++ which needs a platform to
be executed. Java comes with its platform on which its code is executed. Java doesn't
depend upon the operating system to be executed.

Secured: Java is secured because it doesn't use explicit pointers. Java also provides the
concept of Byte Code and Exception handling which makes it more secured.

Robust: Java is a strong programming language as it uses strong memory management.


The concepts like Automatic garbage collection, Exception handling, etc. make it more
robust.

Architecture Neutral: Java is architectural neutral as it is not dependent on the


architecture. In C, the size of data types may vary according to the architecture (32 bit
or 64 bit) which doesn't exist in Java.

Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the
program execution.

High Performance: Java is faster than other traditional interpreted programming


languages because Java byte code is "close" to native code. It is still a little bit slower
than a compiled language (e.g., C++).

Multithreaded: We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are
important for multi-media, Web applications, etc.

Distributed: Java is distributed because it facilitates users to create distributed


applications in Java. RMI and EJB are used for creating distributed applications. This
feature of Java makes us able to access files by calling the methods from any machine
on the internet.

Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means


classes are loaded on demand. It also supports functions from its native languages, i.e.,
C and C++.

3. How many types of memory areas are allocated by JVM?


1.​ Class (Method) Area: Class Area stores per-class structures such as the runtime
constant pool, field, method data, and the code for methods.
2.​ Heap: It is the runtime data area in which the memory is allocated to the objects
3.​ Stack: Java Stack stores frames. It holds local variables and partial results, and
plays a part in method invocation and return. Each thread has a private JVM
stack, created at the same time as the thread. A new frame is created each time a
method is invoked. A frame is destroyed when its method invocation completes.
4.​ Program Counter Register: PC (program counter) register contains the address
of the Java virtual machine instruction currently being executed.
5.​ Native Method Stack: It contains all the native methods used in the application.

4. What are the main differences between the Java platform and other
platforms?

There are the following differences between the Java platform and other platforms.

·Java is the software-based platform whereas other platforms may be the hardware
platforms or software-based platforms.

· Java is executed on the top of other hardware platforms whereas other platforms can
only have the hardware components.

5. What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

· Packages avoid the name clashes.

· The Package provides easier access control.

· We can also have the hidden classes that are not visible outside and used by the
package.

· It is easier to locate the related classes


Experiment – 2
Title: Write a Java program to implement event handling on Swing
components.

Program / Code:

import [Link].*;

import [Link].*;

import [Link].*;

public class SwingEventHandling {

public static void main(String[] args) {

// Create frame

JFrame frame = new JFrame("Event Handling Example");

// Create components

JLabel label = new JLabel("Enter your name:");

JTextField textField = new JTextField(15);

JButton button = new JButton("Submit");

// Set layout

[Link](new FlowLayout());

// Add components

[Link](label);

[Link](textField);

[Link](button);

// Add ActionListener using anonymous class

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {


String name = [Link]().trim();

if (![Link]()) {

[Link](frame, "Hello, " + name +


"!");

} else {

[Link](frame, "Please enter your


name first.");

});

// Frame settings

[Link](300, 150);

[Link](JFrame.EXIT_ON_CLOSE);

[Link](true);

Output:
Viva Question

1. Explain JDK, JRE and JVM?

JDK vs. JRE vs. JVM

JDK JRE JVM

It stands for It stands for Java It stands for Java Virtual Machine.
Java Runtime
Development Environment.
Kit.

It is the tool JRE refers to a It is an abstract machine. It is a


necessary to runtime environment specification that provides a
compile,document in which Java byte run-time environment in which Java
and package Java code can be executed. byte code can be executed.
programs.

It contains JRE It’s an JVM follows three notations:


+ development implementation of Specification, Implementation, and
tools. the JVM which Runtime Instance.
physically exists.

2. What Are The Different Types Of Controls In Awt?


The AWT supports the following types of controls:
Labels, Pushbuttons, Checkboxes, Choice lists, Lists, Scroll bars, Text components
These controls are subclasses of components.

3. What Is The Difference Between A Swing And Awt Components?


AWT components are heavy weight, whereas Swing components are lightweight. Heavy
weight components depend on the local windowing toolkit.

For example, [Link] is a heavy weight component, when it is running on the


Java platform for UNIX platform, it maps to a real Motif button.

4. What is AWT used for in Java?


Abstract Window Toolkit (AWT) is a set of application program interfaces (API s)
used by Java programmers to create graphical user interface (GUI) objects, such as
buttons, scroll bars, and windows.

5. What is an important AWT event?

Set. Event. Provides interfaces and classes for dealing with different types of events
fired by AWT components. This package defines events and event listeners, as well as
event listener adapters, which are convenience classes to make easier the process of
writing event listeners easier.
Experiment – 3
Title: Develop a Swing-based Calculator application using buttons, text
fields, and event handling.

Program / Code:
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

class Calculator{

public static void main (String args[]){

JFrame frame = new JFrame();

​ [Link]("Calculator");

​ [Link](400,100);

​ [Link](400,350);

​ [Link](null);

​ JLabel label = new JLabel("Calculator");

​ [Link](150,50,100,20);

​ [Link](label);

JLabel label1 = new JLabel("Enter First Number");

​ [Link](50,100,150,20);

​ [Link](label1);

​ JTextField textField1 = new JTextField();

​ [Link](200,100,120,20);
​ [Link](textField1);

​ JLabel label2 = new JLabel("Enter Second Number");

​ [Link](50,150,150,20);

​ [Link](label2);

​ JTextField textField2 = new JTextField();

​ [Link](200,150,120,20);

​ [Link](textField2);

​ JLabel label3 = new JLabel("Result");

​ [Link](50,200,150,20);

​ [Link](label3);

​ JTextField textField3 = new JTextField();

​ [Link](200,200,120,20);

​ [Link](textField3);

​ JButton button1 = new JButton("+");

​ JButton button2 = new JButton("-");

JButton button3 = new JButton("*");

​ JButton button4 = new JButton("/");

​ [Link](70,250,50,30);

​ [Link](new ActionListener(){

​ ​ public void actionPerformed(ActionEvent e){

​ ​ ​ Integer num1 = [Link]([Link]());

​ ​ ​ Integer num2 = [Link]([Link]());

​ ​ ​ Integer ans = num1 + num2;

​ ​ ​ [Link]([Link]());

​ ​ ​ }
​ ​ });

​ [Link](140,250,50,30);

​ [Link](new ActionListener(){

​ ​ public void actionPerformed(ActionEvent e){

​ ​ ​ Integer num1 = [Link]([Link]());

​ ​ ​ Integer num2 = [Link]([Link]());

​ ​ ​ Integer ans = num1 - num2;

​ ​ ​ [Link]([Link]());

​ ​ ​ }

​ ​ });

​ [Link](210,250,50,30);

​ [Link](new ActionListener(){

​ ​ public void actionPerformed(ActionEvent e){

​ ​ ​ Integer num1 = [Link]([Link]());

​ ​ ​ Integer num2 = [Link]([Link]());

​ ​ ​ Integer ans = num1 * num2;

​ ​ ​ [Link]([Link]());

​ ​ ​ }

​ ​ });

​ [Link](280,250,50,30);

​ [Link](new ActionListener(){

​ ​ public void actionPerformed(ActionEvent e){

​ ​ ​ Integer num1 = [Link]([Link]());

​ ​ ​ Float num2 = [Link]([Link]());

​ ​ ​ Float ans = num1 / num2;


​ ​ ​ [Link]([Link]());

​ ​ ​ }

​ ​ });

​ [Link](button1);

​ [Link](button2);

​ [Link](button3);

​ [Link](button4);

​ [Link](true);

Output:
Viva Questions

1. What's Java Swing?


Swing is a GUI toolkit for Java. It is one part of the Java Foundation
Classes (JFC). Swing includes graphical user interface (GUI) widgets
such as text boxes, buttons, split-panes, and [Link] widgets
provide more sophisticated GUI components than the earlier Abstract
Window Toolkit. Since they are written in pure Java, they run the same
on all platforms, unlike the AWT which is tied to the underlying
platform's windowing system. Swing supports pluggable look and feel –
not by using the native platform's facilities, but by roughly emulating
them. This means you can get any supported look and feel on any
platform. The disadvantage of lightweight components is slower
execution. The advantage is uniform behavior on all platforms.

2. What are the main features of Java Swing?

Swing offers two key features:

Ø Swing components are lightweight and don't rely on peers.

Ø Swing supports a pluggable look and feel. The three PLAFs available to all users
are Metal (default), Windows, and Motif.

3. What is Java Swing technology?

Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation
Classes (JFC) – an API for providing a graphical user interface (GUI) for Java
programs. Swing was developed to provide a more sophisticated set of GUI
components than the earlier Abstract Window Toolkit (AWT).

4. What are the five Java Swing components?

Below are the different components of swing in java:

· Image Icon. The Image Icon component creates an icon sized-image from an
image residing at the source URL. ...
·J Button. J Button class is used to create a push-button on the UI. ...
·J Label. ...
· J Text Field. ...
· J Text Area. ...
· J Password Field. ...
· J Check Box.
· J Radio Button

5. Are Swing components lightweight?

A Swing component is said to be a lightweight component because it is


written entirely in Java and does the high-level display work itself, rather
than relying on code provided by your computer's operating system.
Experiment no 4
Title: Write a Java program that establishes a connection with a
database using JDBC and displays all the records from a specified table.

Program / Code:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class jdbc1 {

​ public static void main(String[] args) {

​ String driverName ="[Link]";

​ String url ="jdbc:mysql://localhost:3306/db_name";

​ String userName ="user_name";

​ String userPass ="password";

​ String sql ="select * from emp";

​ try {

​ [Link](driverName);

​ Connection connection =
[Link](url,userName,userPass);

​ Statement statement =
[Link]();
​ ResultSet resultSet =
[Link](sql);

​ while([Link]()) {

​ [Link]("EmpNo is:
"+[Link](1));

​ [Link]("EmpName is:
"+[Link](2));

​ [Link]("EmpSal is:
"+[Link](3));

​ [Link]("---------------------------");

​ }

​ [Link]();

​ }catch(ClassNotFoundException e) {

​ [Link]("driver not found");

​ }catch(SQLException e) {

​ [Link](e);

​ }

​}

Output:

EmpNo is: 101

EmpName is: Amit

EmpSal is: 1212.0

---------------------------

EmpNo is: 102

EmpName is: Deep


EmpSal is: 545459.0

---------------------------

EmpNo is: 103

EmpName is: Rohit

EmpSal is: 78451.0

---------------------------

EmpNo is: 104

EmpName is: Suman

EmpSal is: 98745.0

---------------------------

EmpNo is: 105

EmpName is: Neha

EmpSal is: 45000.0

---------------------------

Viva Questions
1. What are JDBC and ODBC?

ODBC is an SQL-based Application Programming Interface (API) created by


Microsoft that is used by Windows software applications to access databases via
SQL. JDBC is an SQL-based API created by Sun Microsystems to enable Java
applications to use SQL for database access.

2. Which class is responsible for creating JDBC?

JDBC Driver Manager: It is the class in JDBC API. It loads the JDBC driver in a
Java application for establishing a connection with the database.

3. What is a JDBC Driver?

JDBC Driver is a software component that enables Java application to interact with the
database.
There are 4 types of JDBC drivers:

· JDBC-ODBC bridge driver: The JDBC-ODBC bridge driver uses the ODBC driver to
connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls
into the ODBC function calls. This is now discouraged because of the thin driver. It is
easy to use and can be easily connected to any database.

· Native-API driver (partially java driver): The Native API driver uses the client-side
libraries of the database. The driver converts JDBC method calls into native calls of the
database API. It is not written entirely in Java. Its performance is better than
JDBC-ODBC bridge driver. However, the native driver must be installed on each client
machine.

·Network Protocol driver (fully java driver): The Network Protocol driver uses
middleware (application server) that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. It is entirely written in Java. There is no requirement
of the client-side library because of the application server that can perform many tasks
like auditing, load balancing, logging, etc.

·Thin driver (fully java driver): The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is known as the thin driver. It is
entirely written in Java language. Its performance is better than all other drivers
however these drivers depend upon the database.

4. What are the JDBC API components?

The [Link] package contains the following interfaces and classes for JDBC API.

Interfaces:Connection: The Connection object is created by using the get Connection ()


method of the Driver Manager class. Driver Manager is the factory for connection
Statement: The Statement object is created by using create Statement () method of
Connection class. The Connection interface is the factory for Statement.

Prepared Statement: The Prepare Statement object is created by using the prepare
Statement () method of Connection class. It is used to execute the parameterized query.
Result Set: The object of Result Set maintains a cursor pointing to a row of a table.
Initially, cursor points before the first row. The execute Query () method of Statement
interface returns the Result Set object.

Result Set Meta Data: The object of Result Set Meta Data interface contains the
information about the data (table) such as number of columns, column name, column
type, etc. The get Meta Data () method of Result Set returns the object of Result Set
Meta Data.

5. What are the JDBC statements?

In JDBC, Statements are used to send SQL commands to the database and receive data
from the database. There are various methods provided by JDBC statements such as
execute (), execute Update (), execute Query, etc. which helps you to interact with the
database.

There are three types of JDBC statements given in the following table.
Experiment – 5
Title: Write a Java program to insert a new record into a table using a
static SQL query (Statement).

Program / Code:

import [Link];

import [Link];

import [Link];

import [Link];

public class jdbc2 {

​ public static void main(String[] args) { ​

​ String sql ="insert into emp


values(106,'Mohan',67543)";

​ String url ="jdbc:mysql://localhost:3306/db_name";

​ String userName ="user_name";

​ String userPass ="password";

​ try {

​ [Link]("[Link]");

​ Connection connection =
[Link](url,uname,upass);

​ Statement statement =
[Link]();

​ int x = [Link](sql);

​ [Link](x+" Record Added.");​

​ [Link]();
​ }catch(ClassNotFoundException e)

​ {

​ [Link]("Driver Not Found");

​ }

​ catch(SQLException e)

​ {

​ [Link](e);

​ }

​ }

Output:

1 Record Added.

Viva Questions

1. What is DNS?

DNS is an acronym that stands for Domain Name System.

●​ DNS was introduced by Paul Mock aperies and Jon Postal in 1983.
●​ It is a naming system for all the resources over the internet which includes
physical nodes and applications. It is used to locate to resource easily over
a network.
●​ DNS is an internet which maps the domain names to their associated IP
addresses.
●​ Without DNS, users must know the IP address of the web page that you
wanted to access.
2. What is NIC?
NIC stands for Network Interface Card. It is a peripheral card attached to the
PC to connect to a network. Every NIC has its own MAC address that
identifies the PC on the network. It provides a wireless connection to a local
area network. NICs were mainly used in desktop computers.

3. ​ What is the full form of ADS?


ADS stands for Active Directory [Link] are a Microsoft technology
used to manage the computers and other [Link] allow the network
administrators to manage the domains, users and objects within the network.

ADS consist of three main tiers:

· Domain: Users that use the same database will be grouped into a single
domain.

· Tree: Multiple domains can be grouped into a single tree.

· Forest: Multiple trees can be grouped into a single forest.

4. How many layers are in the OSI reference model?

OSI reference model: OSI reference model is an ISO standard which defines a
networking framework for implementing the protocols in seven layers. These
seven layers can be grouped into three categories:

· Network layer: Layer 1, Layer 2 and layer 3 are the network layers.

· Transport layer: Layer 4 is a transport layer.

· Application layer. Layer 5, Layer 6 and Layer 7 are the application layers.

· There are 7 layers in the OSI reference model.


5. What is Java Socket Programming ? Explain with examples.

Java Socket programming is used for communication between the


applications running on different [Link] Socket programming can be
connection-oriented or connection-less. Socket and Server Socket
classes are used for connection-oriented socket programming and
Datagram Socket and Datagram Packet classes are used for
connection-less socket programming.
Experiment – 6
Title: Write a Java program to update an existing record in a table using a
dynamic query (PreparedStatement).

Program / Code:
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class jdbc1 {

​ public static void main(String[] args) {

​ Scanner scanner = new Scanner([Link]);

​ String sql = "update emp set empName = ?,empSal = ?


where empNo= ?";

​ String url ="jdbc:mysql://localhost:3306/db_name";

​ String userName ="user_name";

​ String userPass ="password";

​ String driverName ="[Link]";

​ try {

​ [Link](driverName);

​ Connection connection =
[Link](url,uName,uPass);

​ PreparedStatement preparedStatement =
[Link](sql);

​ while(true) {
​ [Link]("Enter EmpNo.: ");

​ Integer empNo = [Link]();

​ [Link]("Enter new
EmpName.: ");

​ String empName = [Link]();

​ [Link]("Enter new EmpSal.:


");

​ Double empSal =
[Link]();

​ [Link](3,empNo);


[Link](1,empName);


[Link](2,empSal);

​ int x =
[Link]();

​ [Link](x+" Entry
updated.");

​ [Link]("Do you want to


update more.(y/n): ");

​ Character ch =
[Link]().charAt(0);

​ if (ch=='n') {

​ break;

​ }

​ }

​ [Link]();

​ [Link]();
​ }catch(ClassNotFoundException e) {

​ [Link]("driver not found");

​ }catch(SQLException e) {

​ [Link](e);

​ }

​ }

Output:

Enter EmpNo.: 101

Enter new EmpName.: Romit

Enter new EmpSal.: 80000

1 Entry updated.

Do you want to update more.(y/n):

1. What is the difference between a web server web container and application server?

The main difference between the web containers and application server is that most web
containers such as Apache Tomcat implements only basic JSR like Servlet, JSP, JSTL
where Application servers implement the entire Java EE Specification. Every
application server contains a web container.

2. What is the use of an application server in Java?

An application server enables a server to generate a dynamic, customized response to a


client request. An application server is a Java™ Virtual Machine (JVM) that runs user
applications. The application server collaborates with the web server to return a
dynamic, customized response to a client request.

3. Which server is best for Java?

Web vs. Application Server.


Apache Tomcat. One of the more popular web servers in the Java ecosystem is Apache
Tomcat.
Jetty.
Apache Tome.
Oracle Web Logic.
Web Sphere. Wild Fly.

4. What are the 4 types of containers in Java?

Container Types

· Java EE server: The runtime portion of a Java EE product. ...


· Enterprise JavaBeans (EJB) container: Manages the execution of enterprise beans for
Java EE applications. ...
·Web container: Manages the execution of JSP page and servlet components for Java
EE applications.

5. What are the two main types of servlet?

There are two main servlet types, generic and HTTP

· Generic servlets. Extending Java. Servlet. Generic Servlet. Is protocol independent

·HTTP servlets. Extending Java. Servlet. Http Servlet. Have built-in HTTP protocol
support and are more useful in a Sun Java System Web Server environment.
Experiment – 7
Title: Write a Java program to demonstrate a Distributed Application.

Program / Code:

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class ChatClient {

​ public static void main(String[] args) throws IOException ,


UnknownHostException {

​ Socket s = new Socket("localhost",2427);

​ [Link]("Sent text..");

​ Scanner sc = new Scanner([Link]);

​ PrintWriter pw = new
PrintWriter([Link](),true);

​ BufferedReader br = new BufferedReader(new


InputStreamReader([Link]()));


​ while(true) {

​ [Link](" ​ ");

​ [Link](sc.

String msg = [Link]();

​ [Link](msg); ​

​ }

​ }

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class ChatServer {

​ public static void main(String[] args) throws IOException {

​ [Link]("Server Ready for Accepting the


Request");

​ ServerSocket ss = new ServerSocket(2427);

​ Socket s = [Link]();

​ [Link]("Connected");
​ Scanner sc = new Scanner([Link]);

​ BufferedReader br = new BufferedReader(new


InputStreamReader([Link]()));

​ PrintWriter pw = new
PrintWriter([Link](),true);

​ while(true) { ​

​ String msg = [Link]();

​ [Link](msg);

​ [Link](" ​ ");

​ [Link]([Link]());

Viva Questions
1. What is the use of JSP in Java?

Java Server Pages (JSP) is a programming tool on the application server side that
supports platform-independent and dynamic methods to construct Web-based
applications. Much as Servlet technology does, the JSP method provides a web
application.

1. What is the JSP life cycle?

A JSP life cycle is defined as the process from its creation till the destruction. This is
similar to a servlet life cycle with an additional step which is required to compile a JSP
into servlet.

2. What is servlet and JSP?

Servlets are Java-based codes. JSP are HTML-based codes. Servlets are harder to code,
as here, the HTML codes are written in Java. JSPs are easier to code, as here Java is
coded in HTML. In an MVC architecture, Servlets act as the controllers.

3. What is a JSP file?

A JSP file extension is given to a server-generated web page containing Java code. The
code is parsed by the web server, which generates HTML. Since the Java code is parsed
on the server, the end user never sees the JSP code, but only the HTML generated by
the Java code in the page.

4. What are JSP and its advantages?

The advantages of JSP are twofold. First, the dynamic part is written in Java, not
Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.


Experiment – 8
Title: Implementation of CRUD Operations using JPA with Hibernate

Program / Code:

[Link]

<?xml version="1.0" encoding="UTF-8"?>​


<project xmlns="[Link]
​ xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>​

<groupId>[Link]</groupId>​
​ <artifactId>h2</artifactId>​
<version>1.0-SNAPSHOT</version>​

​ <properties>​
<[Link]>20</[Link]>​
<[Link]>20</[Link]>​
<[Link]>UTF-8</[Link]>​
​ </properties>​

​ <dependencies>​
​ <!-- Hibernate Core -->​
​ <dependency>​
<groupId>[Link]</groupId>​
<artifactId>hibernate-core</artifactId>​
<version>[Link]</version>​
​ </dependency>​

​ <!-- JPA API -->​
​ <dependency>​
<groupId>[Link]</groupId>​
<artifactId>[Link]-api</artifactId>​
<version>3.1.0</version>​
​ </dependency>​

​ <!-- MySQL Connector -->​
​ <dependency>​
<groupId>[Link]</groupId>​
<artifactId>mysql-connector-j</artifactId>​
<version>8.3.0</version>​
​ </dependency>​
​ </dependencies>


</project>

src/main/resources/META-INF/[Link]

<?xml version="1.0" encoding="UTF-8"?>​


<persistence xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
​[Link]
​version="3.0">​

​ <persistence-unit name="student_unit">​
<class>[Link]</class>​

​ <properties>​
​ <!-- MySQL Connection -->​
​ <property name="[Link]"
value="[Link]"/>​
​ <property name="[Link]"
value="jdbc:mysql://localhost:3306/jpa_demo"/>​
​ <property name="[Link]" value="root"/>​
​ <property name="[Link]"
value="password"/>​

​ <!-- Hibernate Configuration -->​
​ <property name="[Link]"
value="[Link]"/>​
​ <property name="[Link]" value="update"/>​
​ <property name="hibernate.show_sql" value="true"/>​
​ <property name="hibernate.format_sql" value="true"/>​
​ </properties>​
​ </persistence-unit>​

</persistence>

[Link]

package [Link];

import [Link].*;
@Entity

@Table(name = "students")

public class Student {

​ @Id

@GeneratedValue(strategy = [Link])

​ private int id;

​ private String name;

​ private String city;

​ private double marks;

​ public Student() {}

​ public Student(String name, String city, double marks) {

[Link] = name;

[Link] = city;

[Link] = marks;

​ }

​ // Getters & Setters

​ public int getId() { return id; }

​ public String getName() { return name; }

​ public String getCity() { return city; }

​ public double getMarks() { return marks; }

​ public void setName(String name) { [Link] = name; }

​ public void setCity(String city) { [Link] = city; }

​ public void setMarks(double marks) { [Link] = marks; }

​ @Override

​ public String toString() {


​ return id + " | " + name + " | " + city + " | " + marks;

​ }

[Link]

package [Link];

import [Link].*;

public class Main {

​ public static void main(String[] args) {

EntityManagerFactory emf =
[Link]("student_unit");

EntityManager em = [Link]();

​ // CREATE

[Link]().begin();

​ Student s1 = new Student("Rohit", "Delhi", 85.5);

[Link](s1);

[Link]().commit();

[Link]("Record inserted: " + s1);

​ // READ

​ Student found = [Link]([Link], [Link]());

​ [Link]("Fetched Record: " + found);

​ // UPDATE

[Link]().begin();

[Link](90.0);

[Link](found);

[Link]().commit();
[Link]("Updated Record: " + found);

​ // DELETE

[Link]().begin();

[Link](found);

[Link]().commit();

[Link]("Deleted Record");

[Link]();

[Link]();

​ }

OUTPUT :

Hibernate:

​ insert

​ into

​ students

​ (city, marks, name)

​ values

​ (?, ?, ?)

Record inserted: 2 | Rohit | Delhi | 85.5

Fetched Record: 2 | Rohit | Delhi | 85.5

Hibernate:

​ update

​ students

​ set

​ city=?,
​ marks=?,

​ name=?

​ where

​ id=?

Updated Record: 2 | Rohit | Delhi | 90.0

Hibernate:

​ delete

​ from

​ students

​ where

​ id=?

Deleted Record

VIVA QUESTION

1. What is JPA and how does Hibernate relate to it?

●​ JPA (Java Persistence API) is a specification that defines how to


manage relational data in Java applications using object-relational
mapping (ORM).​

●​ Hibernate is one of the most popular implementations of JPA. It


provides the actual engine and tools to perform database
operations such as Create, Read, Update, and Delete (CRUD)
based on JPA annotations and interfaces.​

●​ In short, JPA defines what to do, while Hibernate defines how to do


it.

2. How do you perform the Create (Insert) operation in JPA using Hibernate?
To insert a new record, you use the persist() method of
EntityManager.​
Example:

EntityManagerFactory emf =
[Link]("my-pu");

EntityManager em = [Link]();

[Link]().begin();

Student student = new Student();

[Link]("John");

[Link](22);

[Link](student); // Adds record to database

[Link]().commit();

[Link]();

[Link]();

●​ persist() marks the entity for insertion.​

●​ When commit() is called, Hibernate generates an INSERT SQL


statement.​

3. How do you retrieve (Read) data using JPA and Hibernate?

Answer:​
There are two common ways:

1.​ Find by ID:Student student = [Link]([Link], 1);


2.​ Using JPQL (Java Persistence Query Language):​
List<Student> students = [Link]("SELECT s
FROM Student s", [Link] .getResultList()
●​ find() fetches a record by primary key.
●​ JPQL allows fetching multiple records using object-oriented
queries.

4. How do you perform an Update operation in JPA with Hibernate?​


You can update an entity using the merge() method.​
Example:[Link]().begin();

Student student = [Link]([Link], 1);

[Link](25); // Update the field

[Link](student); // Optional if entity is managed

[Link]().commit();

●​ If the entity is managed, changes are automatically synchronized


with the database when committing the transaction.​

●​ If it’s detached, merge() brings it back into the persistence


context and updates the database.

5. How do you perform a Delete operation using JPA and Hibernate?​


Use the remove() method to delete an entity.​
Example:[Link]().begin();

Student student = [Link]([Link], 1);

[Link](student); // Deletes the record

[Link]().commit();

●​ You must first ensure the entity is managed (attached to the


persistence context).​
●​ If the entity is detached, you must reattach it using merge()
or fetch it again using find() before removal.​
Experiment – 9
Title: Write a simple Spring Boot application that returns “Hello World” as a
web response.

Program / Code:

[Link]

package [Link];

import [Link];

import [Link];

@SpringBootApplication

public class SpringbootHelloApplication {

​ public static void main(String[] args) {

[Link]([Link], args);

[Link]("Hello World Spring Boot Application Started!");

​ }

[Link]

package [Link];

import [Link];

import [Link];

@RestController

public class HelloController {

​ @GetMapping("/")

​ public String hello() {

​ return "Hello, Spring Boot!";

​ }

OUTPUT :-Hello, Spring Boot


Viva Questions
1. Mention some important JSP Action Tags.

2. Mention the scope values for <[Link]> tag.

Ans: There are mainly four scope values available for <[Link]> tag.

●​ page
●​ request
●​ application
●​ session

3. What are the Literals used in JSP?

Ans: The Literals used in JSP are as follows:

●​ Null
●​ Boolean
●​ String
●​ Integer Float

4. List down the major differences between the JSP Custom Tags and Java Beans.

Ans: The Major Differences between JSP Custom Tags and Java Beans are as follows:
5. Mention the Implicit Objects in a JSP.

Ans: JSP implicit objects are created during the translation phase of JSP to the servlet.
These objects can be directly used in scriptlets that go in the service method. They are
created by the container automatically, and they can be accessed using objects.

There are 9 types of implicit objects available in the container:

1.​ Out
2.​ Request
3.​ Response
4.​ Config
5.​ Application
6.​ Session
7.​ PageContext
8.​ Page
9.​ Exception

6. What are the different Life-Cycle methods?

Ans: The different Life-Cycle Methods are as follows:

●​ jsp Init()
●​ disservice()
●​ Jsp Destroy

Jsp Init (): Container calls jsp Init () method to initialize servlet instance. It is called
once for the servlet instance and preceded every other method.

Jsp Service (): Container calls _jsp Service () method for each request and passes it on
to the objects.

Jsp Destroy (): Container calls the jsp Destroy () just before destruction of the instance.
Experiment – 10
Title: Write a RESTful web service that performs CRUD (Create, Read, Update,
Delete) operations on Employee data.

Program / Code:

[Link]

package [Link];

import [Link];

import [Link];

@SpringBootApplication

public class CrudDemoApplication {

​ public static void main(String[] args) {

[Link]([Link], args);

​ [Link]("CRUD REST API Application Started!");

​ }

[Link]

package [Link];

public class Employee {

​ private int id;

​ private String name;

​ private double salary;

​ public Employee() {}

​ public Employee(int id, String name, double salary) {

​ [Link] = id;

​ [Link] = name;
​ [Link] = salary;

​ }

​ public int getId() { return id; }

​ public void setId(int id) { [Link] = id; }

​ public String getName() { return name; }

​ public void setName(String name) { [Link] = name; }

​ public double getSalary() { return salary; }

​ public void setSalary(double salary) { [Link] = salary; }

[Link]

package [Link];

import [Link];

import [Link].*;

import [Link].*;

@RestController

@RequestMapping("/employees")

public class EmployeeController {

​ private Map<Integer, Employee> employees = new HashMap<>();

​ @PostMapping

​ public String addEmployee(@RequestBody Employee emp) {

​ [Link]([Link](), emp);

​ return "Employee added successfully!";

​ }
​ @GetMapping

​ public Collection<Employee> getAllEmployees() {

​ return [Link]();

​ }

​ @GetMapping("/{id}")

​ public Employee getEmployee(@PathVariable int id) {

​ return [Link](id);

​ }

​ @PutMapping("/{id}")

​ public String updateEmployee(@PathVariable int id, @RequestBody


Employee emp) {

​ [Link](id, emp);

​ return "Employee updated successfully!";

​ }

​ @DeleteMapping("/{id}")

​ public String deleteEmployee(@PathVariable int id) {

​ [Link](id);

​ return "Employee deleted successfully!";

​ }

Viva Questions

Define JSP Declaration.


Ans: The JSP declaration tag is used to declare fields and methods. The code written
inside the JSP declaration is enclosed in < %!%> Tag. It is placed outside the service ()
method of the auto-generated set. Syntax:

1 <%! field or method declaration %>

Example:

1 <html>

2 <body>

3 <%! int data=50; %>

4 <%= "Value of the variable is:"+data %>

5 </body>

6 </html>

2. Differentiate between JSP Script let tag and Declaration tag.

Ans: The difference in both is discussed as follows:

JSP Script let Tag Declaration Tag

JSP Script let Tag can only declare Declaration Tag declares Methods and
Variables Variables

Script let Tag is placed within _jsp Declaration Tag is placed outside _jsp
Service() Service()

3. How are JSP (Java Server Pages) better than ASP (Active Server Pages)?

Ans: The advantages of JSP over ASP are as follows:

●​ The dynamic part of the code is written in Java, not in Visual Basic or the
Microsoft-specific language. Hence, it is powerful and easier to use.
●​ It is portable to other operating systems and Non-Microsoft Web servers.
4. Mention the advantages of JSP over Pure Servlets?

Ans: Some of the Major Advantages of JSP over Pure Servlets are as discussed below:

· It is more convenient to write and modify normal HTML than to have plenty of print
ln statements that generate the HTML.

· Embedding of Java code in HTML pages.

· Platform independence.

· Creation of database-driven Web applications.

· Server-side programming capabilities.

5. What are the steps involved in reading data from a form using JSP?

Ans: The data parsing is a JSP is Automatic. It is done through the following steps
depending on the situation.

1.​ Get Parameter (): request. Get Parameter () method is called to get the value of
the form parameter.
2.​ Get Parameter Values (): This method is called if the parameter appears more
than once and returns multiple values.
3.​ Get Parameter Names (): This method is called if the user wants a complete list
of all parameters in the current request.

Get Input Stream (): This method is used to read binary data stream coming from the
client.

You might also like