0% found this document useful (0 votes)
7 views39 pages

CS1312 - Advanced Java Programming - Lab Manual 1 To 10

The document outlines a series of experiments for an Advanced Java Programming Lab, covering topics such as creating Swing applications, implementing event handling, setting up a Java EE development environment, automating Java EE projects with Ant, and using Remote Method Invocation (RMI) for remote communication. Each experiment includes aims, algorithms, and sample code demonstrating the concepts. The document concludes with results affirming the successful completion of each experiment.

Uploaded by

sanjayrjegadesan
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)
7 views39 pages

CS1312 - Advanced Java Programming - Lab Manual 1 To 10

The document outlines a series of experiments for an Advanced Java Programming Lab, covering topics such as creating Swing applications, implementing event handling, setting up a Java EE development environment, automating Java EE projects with Ant, and using Remote Method Invocation (RMI) for remote communication. Each experiment includes aims, algorithms, and sample code demonstrating the concepts. The document concludes with results affirming the successful completion of each experiment.

Uploaded by

sanjayrjegadesan
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/ 39

CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 1:

Creating a simple Swing application with JFrame and JLabel and Work with different Swing
components, Swing containers and frames to design a GUI layout.

Aim:

To create a simple Java Swing GUI application using JFrame, JLabel, and other Swing
components such as JButton, JTextField, and layout managers to demonstrate basic GUI layout
design.

Algorithm:

1.​ Import Required Packages: Import javax.swing.* and java.awt.* for GUI components
and layout management.
2.​ Create a Class: Create a public class that extends JFrame.
3.​ Set Frame Properties: Set the title, size, layout, default close operation, and visibility of
the frame.
4.​ Create Components: Initialize Swing components like JLabel, JTextField, JButton.
5.​ Add Components to Container: Add the components to the content pane using a layout
manager.
6.​ Add Event Handling (optional): Add ActionListener to handle button clicks (if needed).
7.​ Run the GUI: Use the main() method to create an object of the class and display the
GUI.

Program:
import javax.swing.*; // Swing components
import java.awt.*; // Layouts and container

public class SimpleSwingApp extends JFrame {

// Constructor
public SimpleSwingApp() {
// Set frame title
setTitle("Simple Swing GUI");

// Set frame size


setSize(400, 200);
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

// Set layout manager


setLayout(new FlowLayout());

// Set default close operation


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create Swing components


JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Submit");

// Add components to frame


add(label);
add(textField);
add(button);

// Optional: Action listener for button


button.addActionListener(e -> {
String name = textField.getText();
JOptionPane.showMessageDialog(this, "Hello, " + name + "!");
});

// Make frame visible


setVisible(true);
}

// Main method to run the GUI


public static void main(String[] args) {
new SimpleSwingApp();
}
}
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Output:

Result:

Thus the above program successfully created a simple Java Swing GUI application using
JFrame, JLabel, and other Swing components such as JButton, JTextField, and layout managers
to demonstrate basic GUI layout design.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 2:

Implementing Event Handling for user interactions in a Swing application.

Aim:

To implement event handling in a Java Swing application to respond to user actions (like button
clicks or text input).

Algorithm:

1.​ Import necessary Swing and AWT packages.


2.​ Create a class extending JFrame and implement ActionListener.
3.​ Create GUI components like JLabel, JTextField, and JButton.
4.​ Add components to the frame using a layout manager.
5.​ Register event listeners for the interactive components (e.g.,
button.addActionListener(this);).
6.​ Override the actionPerformed() method to define what should happen on the event.
7.​ Display the frame using setVisible(true).

Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class EventHandlingExample extends JFrame implements ActionListener {

// Declare components
private JTextField nameField;
private JButton greetButton;
private JLabel resultLabel;

// Constructor
public EventHandlingExample() {
// Frame title and layout
setTitle("Event Handling Example");
setLayout(new FlowLayout());
setSize(350, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

// Create components
JLabel promptLabel = new JLabel("Enter your name:");
nameField = new JTextField(15);
greetButton = new JButton("Greet");
resultLabel = new JLabel("");

// Add components to frame


add(promptLabel);
add(nameField);
add(greetButton);
add(resultLabel);

// Register button click event


greetButton.addActionListener(this);

// Make frame visible


setVisible(true);
}

// Event handler
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
if (!name.isEmpty()) {
resultLabel.setText("Hello, " + name + "!");
} else {
resultLabel.setText("Please enter your name.");
}
}

// Main method
public static void main(String[] args) {
new EventHandlingExample();
}
}
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Output:

Result:

Thus the above program successfully implemented event handling in a Java Swing
application to respond to user actions (like button clicks or text input).
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 3:

Setting up a Java EE development environment and Configuring web.xml file.

Aim:

To set up a Java EE web development environment and configure the web.xml file to define a
servlet, servlet mapping, and welcome file.

Algorithm:

Part 1: Setting up Java EE Development Environment

1.​ Install Java Development Kit (JDK) (preferably JDK 8 or 11).


2.​ Install Apache Tomcat Server (or any Java EE-compatible server like GlassFish).
3.​ Install an IDE: Eclipse IDE for Enterprise Java Developers is commonly used.
4.​ Create a Dynamic Web Project:
○​ In Eclipse: File → New → Dynamic Web Project.
○​ Enter project name, target runtime (e.g., Tomcat), and dynamic web module
version (usually 3.1).
5.​ Create index.jsp and servlet classes as needed.

Part 2: Configuring web.xml

The web.xml file is the deployment descriptor for Java EE web applications. It resides in:

WebContent/WEB-INF/web.xml

Sample web.xml Configuration:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">

<!-- Welcome File -->


<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

<!-- Servlet Declaration -->


<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class>
</servlet>

<!-- Servlet Mapping -->


<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

Example Java Servlet Code (HelloServlet.java):


package com.example;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<html><body>");
out.println("<h1>Hello from Java Servlet!</h1>");
out.println("</body></html>");
}
}
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Output:

Result:
​ Thus the above setting up a Java EE development environment and Configuring web.xml
file has successfully completed.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 4:

Automating Java EE Project using Ant build tool & Packaging Java EE applications and
modules for deployment.

Aim:

To use Apache Ant in IntelliJ IDEA to automate building a Java EE project and package
it into a WAR file for deployment.

Algorithm:

1.​ Create a Java EE Web Project in IntelliJ.


2.​ Write Java Servlet code and configure web.xml.
3.​ Create an Ant build script (build.xml).
4.​ Add the Ant build file to IntelliJ.
5.​ Run the Ant target from within IntelliJ.
6.​ Verify the generated WAR file.

Step-by-Step:

1. Create the Project

●​ Open IntelliJ IDEA → New Project.


●​ Select Java Enterprise > Choose SDK > Enable Web Application.
●​ Project Name: MyJavaEEProject
●​ Click Finish.

2. Project Structure

Create this structure:

MyJavaEEProject/
├── src/
│ └── com/example/HelloServlet.java
├── Web/
│ ├── index.html
│ └── WEB-INF/
│ └── web.xml
├── lib/ (for external JARs if needed)
├── build/ (generated by Ant)
├── dist/ (generated WAR will be placed here)
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

├── build.xml

3. Sample Servlet (src/com/example/HelloServlet.java)


package com.example;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello from Servlet in IntelliJ!</h1>");
}
}

4. web.xml (Web/WEB-INF/web.xml)
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

Ant Script (build.xml)

Place this at the root of the project.

<project name="MyJavaEEProject" default="build" basedir=".">

<!-- Define directory properties -->


<property name="src.dir" location="src"/>
<property name="web.dir" location="Web"/>
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

<property name="build.dir" location="build"/>


<property name="dist.dir" location="dist"/>
<property name="lib.dir" location="lib"/>

<!-- Clean build and dist directories -->


<target name="clean">
<delete dir="${build.dir}"/>
<delete dir="${dist.dir}"/>
</target>

<!-- Compile the Java source files -->


<target name="compile">
<mkdir dir="${build.dir}"/>
<javac srcdir="${src.dir}" destdir="${build.dir}" includeantruntime="false"/>
</target>

<!-- Package the WAR file -->


<target name="build" depends="clean, compile">
<mkdir dir="${dist.dir}"/>
<war destfile="${dist.dir}/MyJavaEEApp.war"
webxml="${web.dir}/WEB-INF/web.xml">
<fileset dir="${web.dir}" excludes="WEB-INF/web.xml"/>
<lib dir="${lib.dir}"/>
<classes dir="${build.dir}"/>
</war>
</target>
</project>

How to Run Ant in IntelliJ IDEA

Add Ant to IntelliJ:

1.​ Open IntelliJ.


2.​ Go to View > Tool Windows > Ant Build.
3.​ Click and select build.xml from your project.
4.​ You’ll see the build targets (clean, compile, build).
5.​ Right-click on build → Run.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Output:

clean:
[delete] Deleting directory /build
[delete] Deleting directory /dist

compile:
[mkdir] Created dir: /build
[javac] Compiling 1 source file to /build

build:
[mkdir] Created dir: /dist
[war] Building war: /dist/MyJavaEEApp.war

BUILD SUCCESSFUL

●​ Check the dist/ folder — you’ll see MyJavaEEApp.war.

Deploy WAR in Tomcat (Optional)

1.​ Copy MyJavaEEApp.war to tomcat/webapps/.


2.​ Start Tomcat.
3.​ Access: http://localhost:8080/MyJavaEEApp/hello

Result:

​ Thus the above automating Java EE Project using Ant build tool & Packaging Java EE
applications and modules for deployment has successfully completed.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 5:

Implementing Remote Method Invocation (RMI) for remote communication between


Java objects & exploring different activation models in RMI.

Aim:

To implement Java Remote Method Invocation (RMI) for enabling communication


between distributed Java objects running on different JVMs and to explore different activation
models: eager (default) and lazy (on-demand) activation.

Algorithm:

For Eager Activation (Default Model)

1.​ Define a remote interface extending java.rmi.Remote.


2.​ Implement the remote interface and extend UnicastRemoteObject.
3.​ Create and start the RMI server.
4.​ Register the remote object in the RMI registry.
5.​ Create a client to lookup and call the remote method.
6.​ Compile and run:​
a. Compile classes​
b. Run the RMI registry​
c. Start the server​
d. Run the client

File 1: Hello.java (Remote Interface)


import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Hello extends Remote {


String sayHello() throws RemoteException;
}

File 2: HelloImpl.java (Remote Object Implementation)


import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

public class HelloImpl extends UnicastRemoteObject implements Hello {


CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

public HelloImpl() throws RemoteException {


super();
}

@Override
public String sayHello() throws RemoteException {
return "Hello from the RMI server!";
}
}

File 3: Server.java (RMI Server)


import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class Server {


public static void main(String[] args) {
try {
HelloImpl obj = new HelloImpl();
LocateRegistry.createRegistry(1099); // Start RMI Registry
Naming.rebind("HelloService", obj);
System.out.println("Server is ready.");
} catch (Exception e) {
System.err.println("Server Exception: " + e.getMessage());
e.printStackTrace();
}
}
}

File 4: Client.java (RMI Client)


import java.rmi.Naming;

public class Client {


public static void main(String[] args) {
try {
Hello stub = (Hello) Naming.lookup("rmi://localhost/HelloService");
String response = stub.sayHello();
System.out.println("Response from server: " + response);
} catch (Exception e) {
System.err.println("Client Exception: " + e.getMessage());
e.printStackTrace();
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

}
}
}

How to Compile and Run (Eager Model)

1.​ Compile all Java files:

javac *.java

2.​ Start the RMI Registry (in a separate terminal):

rmiregistry

(Make sure it runs from the folder where your classes are located)

3.​ Run the Server:

java Server

4.​ Run the Client:

java Client

Output:

Server Terminal:
Server is ready.

Client Terminal:
Response from server: Hello from the RMI server!

Exploring Activation Models

1. Eager Activation (Used Above)

●​ Object created and registered at server startup.


CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

●​ Always available in memory.

2. Lazy Activation (Activatable Objects) — Java 8 only

●​ Object loaded when client calls a method.


●​ Requires: rmid, activation descriptor, Activatable.

⚠️ Lazy activation using Activatable is deprecated in Java 9+ and removed in Java


15+.​
If you want a legacy lazy activation example, I can give a separate version using
rmid.

Result:

​ Thus the above implements Java Remote Method Invocation (RMI) for enabling
communication between distributed Java objects running on different JVMs and to explore
different activation models: eager (default) and lazy (on-demand) activation has successfully
completed.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 6:

Serializing Java objects for network transmission using Object Serialization.

Aim:

To implement object serialization and deserialization for transmitting Java objects over a
network using sockets in IntelliJ IDEA.

Algorithm:

1.​ Create a Java class that implements Serializable (e.g., Student).


2.​ Create a Server that:
○​ Opens a ServerSocket.
○​ Accepts a connection.
○​ Reads an object using ObjectInputStream.
3.​ Create a Client that:
○​ Connects to the server.
○​ Sends an object using ObjectOutputStream.
4.​ Run both in IntelliJ IDEA in separate Run/Debug windows.

Steps in IntelliJ IDEA:

1. Open IntelliJ IDEA → File > New > Project

●​ Choose Java > Next


●​ Project name: ObjectSerializationExample
●​ Click Finish

2. Create Package & Java Classes

●​ Right-click src > New > Package → name it: com.example


●​ Inside this package, create these three classes:
○​ Student.java
○​ Server.java
○​ Client.java
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Program:

Student.java
package com.example;

import java.io.Serializable;

public class Student implements Serializable {


private String name;
private int age;

public Student(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
}

Server.java
package com.example;

import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(5000)) {
System.out.println("Server is waiting for connection...");

Socket socket = serverSocket.accept();


System.out.println("Client connected!");

ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());


Student student = (Student) ois.readObject();
System.out.println("Received: " + student);
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

ois.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Client.java
package com.example;

import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)) {
Student student = new Student("Alice", 21);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(student);
System.out.println("Sent: " + student);

oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

How to Run in IntelliJ IDEA:


Step 1: Run the Server

●​ Right-click on Server.java → Run 'Server.main()'

You should see:​


Server is waiting for a connection...
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Step 2: Run the Client (in another Run tab)

●​ Right-click on Client.java → Run 'Client.main()'

You should see in Client tab:​


Sent: Student{name='Alice', age=21}

●​ In Server tab:​
Client connected!

Received: Student{name='Alice', age=21}

Output:

Result:

To implement object serialization and deserialization for transmitting Java objects over a
network using sockets in IntelliJ IDEA.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 7:

Working with Naming Services and CORBA programming models & Creating JAR files
for packaging and distributing Java applications.

Aim:

1.​ To develop a distributed Java application using CORBA and Naming Service for
locating remote objects.
2.​ To package the application as a JAR file for easy distribution and execution.

Part 1: CORBA with Naming Service

Algorithm:

1.​ Define a CORBA interface using IDL.


2.​ Compile the IDL using idlj to generate Java stubs.
3.​ Implement the server object using generated skeletons.
4.​ Register the object with the ORB Naming Service.
5.​ Write a client to connect to the remote object using the name.
6.​ Compile and run the server, then the client using orbd for the Naming Service.

Steps in IntelliJ IDEA for CORBA (Java 8 Only)

CORBA is removed in Java 11 and later, so use Java 8 SDK in IntelliJ.

1. Define IDL File

Create a file: Hello.idl

module HelloApp {
interface Hello {
string sayHello();
};
};

2. Compile IDL Using idlj


idlj -fall Hello.idl

This creates:
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

●​ Hello.java
●​ HelloHelper.java
●​ HelloOperations.java
●​ HelloPOA.java
●​ HelloHolder.java

Move these files into src/com/example/ in IntelliJ IDEA.

3. Server Implementation

HelloImpl.java

package com.example;

import HelloApp.HelloPOA;

public class HelloImpl extends HelloPOA {


public String sayHello() {
return "Hello from CORBA Server!";
}
}

Server.java
package com.example;

import HelloApp.Hello;
import HelloApp.HelloHelper;

import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import org.omg.PortableServer.*;

public class Server {


public static void main(String[] args) {
try {
ORB orb = ORB.init(args, null);
POA rootPOA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootPOA.the_POAManager().activate();

HelloImpl helloImpl = new HelloImpl();


CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

org.omg.CORBA.Object ref = rootPOA.servant_to_reference(helloImpl);


Hello href = HelloHelper.narrow(ref);

org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");


NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

NameComponent[] path = ncRef.to_name("HelloService");


ncRef.rebind(path, href);

System.out.println("CORBA Server is running...");


orb.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Client.java
package com.example;

import HelloApp.Hello;
import HelloApp.HelloHelper;

import org.omg.CORBA.*;
import org.omg.CosNaming.*;

public class Client {


public static void main(String[] args) {
try {
ORB orb = ORB.init(args, null);

org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");


NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

Hello helloRef = HelloHelper.narrow(ncRef.resolve_str("HelloService"));

String response = helloRef.sayHello();


System.out.println("Response from server: " + response);
} catch (Exception e) {
e.printStackTrace();
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

}
}
}

4. Run CORBA App in IntelliJ IDEA

a. Start Naming Service (in terminal):


orbd -ORBInitialPort 1050

b. Run Server:
VM Options:
-ORBInitialPort 1050 -ORBInitialHost localhost

c. Run Client:
VM Options:
-ORBInitialPort 1050 -ORBInitialHost localhost

Output:

Server Console:
CORBA Server is running...

Client Console:
Response from server: Hello from CORBA Server!

Part 2: Creating JAR File in IntelliJ IDEA

Algorithm for Packaging JAR:

1.​ Open IntelliJ > Project Structure > Artifacts.


2.​ Add JAR > From modules with dependencies.
3.​ Choose the main class (e.g., Client.java).
4.​ Build > Build Artifacts > Build.
5.​ Run the JAR file from the terminal.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Steps in IntelliJ IDEA


1.​ Go to File > Project Structure > Artifacts.
2.​ Click → JAR > From modules with dependencies.
3.​ Choose module and Main class (e.g., com.example.Client).
4.​ Output directory: out/artifacts/.
5.​ Click Apply and OK.
6.​ Build > Build Artifacts > Build.

Run the JAR


java -jar out/artifacts/ObjectSerializationExample.jar

(Make sure orbd and server are running if you call CORBA from the JAR)

Output:

Result:

​ Thus the above working with Naming Services and CORBA programming models &
Creating JAR files for packaging and distributing Java applications has successfully completed.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 8:

Developing server-side programs using Servlets for handling HTTP requests and
responses.

Aim:

To create a server-side Java web application using Servlets to handle HTTP GET and
POST requests and generate dynamic HTML responses.

Algorithm:

1.​ Create a Java Enterprise project in IntelliJ IDEA with support for Web Application
and Servlets.
2.​ Define a Servlet class that extends HttpServlet.
3.​ Override doGet() and/or doPost() methods to handle HTTP requests.
4.​ Configure the servlet mapping using web.xml or @WebServlet.
5.​ Deploy the application using Tomcat or another servlet container.
6.​ Run the servlet and access it via a web browser.

Steps in IntelliJ IDEA:

1. Create a Java EE Web Project:

1.​ File → New → Project


2.​ Choose Java Enterprise
○​ Check: Web Application
○​ Application Server: Apache Tomcat (Install if not configured)
3.​ Project Name: ServletExample
4.​ Click Finish

Project Structure:

ServletExample/

├── src/

│ └── com/example/HelloServlet.java

├── web/

│ └── WEB-INF/
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

│ └── web.xml

├── out/

├── ServletExample.iml

HelloServlet.java

package com.example;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.annotation.WebServlet;

@WebServlet("/hello") // Optional if using web.xml

public class HelloServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");

out.println("<h1>Welcome to Servlets!</h1>");

out.println("<p>This is a response to an HTTP GET request.</p>");

out.println("</body></html>");

}
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

web.xml (if not using @WebServlet)

Path: web/WEB-INF/web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">

<servlet>

<servlet-name>HelloServlet</servlet-name>

<servlet-class>com.example.HelloServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloServlet</servlet-name>

<url-pattern>/hello</url-pattern>

</servlet-mapping>

</web-app>

Note: You can choose either annotation or XML mapping (not both).

How to Run in IntelliJ IDEA:

1.​ Right-click your project → Add Framework Support → Enable Web Application if
not already.


2.​ Go to Run > Edit Configurations...
○​ Click > Tomcat Server > Local
○​ Name: RunServletApp
○​ Select your artifact: ServletExample:war exploded
○​ Set Application context: / (optional)
3.​ Click Run
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Output:

Access this URL:

http://localhost:8080/hello

You will see:

<h1>Welcome to Servlets!</h1>

<p>This is a response to an HTTP GET request.</p>

Result:

Thus the above programming was successfully developed server-side programs using
Servlets for handling HTTP requests and responses.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 9:

Creating dynamic web content using Java Server Pages (JSP).

Aim:

To create a dynamic web page using JSP (Java Server Pages) that generates and displays
content dynamically based on user input or logic.

Algorithm:

1.​ Create a Java EE web project in IntelliJ IDEA with Tomcat server.
2.​ Add a JSP file in the web/ directory.
3.​ Write embedded Java code in the JSP file to generate dynamic HTML.
4.​ Deploy the application on Tomcat.
5.​ Run and test the dynamic response via a web browser.

Project Structure:

JSPExample/

├── src/

├── web/

│ ├── index.jsp

│ └── WEB-INF/

│ └── web.xml (optional)

Steps in IntelliJ IDEA:

1. Create a New Project:

1.​ Open IntelliJ → File > New > Project


2.​ Select Java Enterprise
○​ Check Web Application
○​ Choose SDK (Java 8+)
○​ Add Apache Tomcat
3.​ Project name: JSPExample
4.​ Finish
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

2. Create a JSP File

web/index.jsp

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

<html>

<head>

<title>JSP Dynamic Page</title>

</head>

<body>

<h1>Hello from JSP!</h1>

<p>Current Time: <%= new java.util.Date() %></p>

<form method="get">

Enter your name: <input type="text" name="user">

<input type="submit" value="Greet Me">

</form>

<%

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

if (name != null && !name.isEmpty()) {

%>

<h2>Welcome, <%= name %>!</h2>

<%

}
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

%>

</body>

</html>

Optional web.xml (Not required unless using legacy setup)

web/WEB-INF/web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

Run in IntelliJ IDEA:


1.​ Go to Run > Edit Configurations
2.​ Click > Tomcat Server > Local
3.​ Set:
○​ Name: RunJSP
○​ Deployment: Add JSPExample:war exploded
○​ Application context: /
4.​ Click Apply and Run
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Output:

URL:

http://localhost:8080/index.jsp

Initial:

Hello from JSP!

Current Time: [current date & time]

[Enter your name box]

After submitting name:

Hello from JSP!

Current Time: [current date & time]

Welcome, [YourName]!

Result:
​ Thus the above Creating dynamic web content using Java Server Pages (JSP) has
successfully completed.
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Experiment 10:

Implementing communication between Java applets and Servlets.

Aim:

To implement a system where a Java Applet sends data to a Servlet, and the servlet processes it
and sends a response back, demonstrating communication between client-side applet and
server-side servlet.

Note:

●​ Modern browsers do not support Java Applets anymore. Applets are obsolete since
Java 9 and removed in Java 11.
●​ This experiment can only be run in older Java versions (Java 8 or lower) using
appletviewer or embedded JVM.

Algorithm:

1.​ Create a Java Applet that collects user input and sends it to a Servlet using HTTP
POST.
2.​ Create a Servlet to read the input, process it, and return a response.
3.​ Deploy the servlet on a Java EE server (like Tomcat).
4.​ Load the Applet using appletviewer or in an HTML page.
5.​ Applet sends data to the servlet and receives the response.

Directory Structure:
AppletServletComm/
├── src/
│ ├── com.example/
│ │ ├── MyApplet.java
│ │ └── MyServlet.java
├── web/
│ ├── index.html
│ └── WEB-INF/
│ └── web.xml
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

1. Java Applet: MyApplet.java


package com.example;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class MyApplet extends Applet implements ActionListener {


TextField nameField;
Button sendButton;
Label resultLabel;

public void init() {


nameField = new TextField(20);
sendButton = new Button("Send to Servlet");
resultLabel = new Label("");

add(new Label("Enter your name:"));


add(nameField);
add(sendButton);
add(resultLabel);

sendButton.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


try {
String name = URLEncoder.encode(nameField.getText(), "UTF-8");
URL url = new URL(getCodeBase(), "MyServlet");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());


writer.write("name=" + name);
writer.flush();

BufferedReader reader = new BufferedReader(


new InputStreamReader(conn.getInputStream()));
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

String line = reader.readLine();


resultLabel.setText("Response: " + line);

writer.close();
reader.close();
} catch (Exception ex) {
resultLabel.setText("Error: " + ex.getMessage());
}
}
}

2. Java Servlet: MyServlet.java


package com.example;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

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


PrintWriter out = response.getWriter();
response.setContentType("text/plain");

out.println("Hello, " + name + "! (from Servlet)");


}

// Allow GET also for testing


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

3. HTML to Load Applet: index.html


<html>
<head><title>Applet-Servlet Communication</title></head>
<body>
<h3>Applet communicating with Servlet</h3>
<applet code="com.example.MyApplet.class" width="400" height="150"
archive="AppletServletComm.jar">
</applet>
</body>
</html>

4. web.xml Servlet Mapping


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>

How to Build and Run in IntelliJ IDEA

1.​ Create Java EE Web App → add Tomcat.


2.​ Put applet and servlet in src/com/example/.
3.​ Add index.html under web/.
4.​ Package applet class into AppletServletComm.jar
○​ Build > Build Artifacts > JAR > From modules with dependencies
5.​ Run with Run > Tomcat → Visit http://localhost:8080/index.html
6.​ Use appletviewer if browser doesn’t support applets.

appletviewer index.html
CS1312 - Advanced Java Programming Lab Department of CSE 2025 -2026

Output:

1.​ Applet asks: “Enter your name”


2.​ You enter Alice → click “Send to Servlet”
3.​ Label updates:​
Response: Hello, Alice! (from Servlet)

Result:
Thus the above implements a system where a Java Applet sends data to a Servlet, and
the servlet processes it and sends a response back, demonstrating communication between
client-side applet and server-side servlet has been successfully completed.

You might also like