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

Full Stack Java Lab

Uploaded by

sshaikh76696
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)
6 views52 pages

Full Stack Java Lab

Uploaded by

sshaikh76696
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/ 52

1

DEPARTMENT OF COMPUTER ENGINEERING


ACADEMIC YEAR 2025-2026

Full Stack Java Programming

Class: Second Year Sem: III

INDEX

S. No. Practical Page No.


1 Programs on classes and objects. 2

2 Programs on method and constructor overloading. 5

3 Programs on various types of inheritance and Exception handling 8

4 Program on Implementing Generic and HTTP servlet. 14

5 Program on Implicit and Explicit objects in JSP 18

6 Program to create a website using HTML CSS and JavaScript 22

7 Program based on Document Object Model to change the 25


background color of the web page automatically after every 5
seconds
8 Program to create a Monolithic Application using SpringBoot 28

9 Program for Building RESTful APIs with spring boot 34

10 Creating a Single Page website using the concepts in React like 42


Hooks, Router, Props and States.
2

EXPERIMENT NO:1

TITLE OF EXPERIMENT: Programs on classes and objects.


AIM: To understand the concept of classes and objects in Java by writing a basic program that
demonstrates encapsulation, object instantiation, and method usage.

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


1 System 1
2 JDK -

Theory

🔹 What is a Class?
A class in Java is a blueprint for creating objects. It defines properties (variables) and behaviors
(methods) that the object will have.
🔹 What is an Object?
An object is an instance of a class. It is created using the new keyword and has its own state and
behavior defined by the class.
🔹 Why Use Classes and Objects?
Promotes modularity and code reuse
Follows Object-Oriented Programming (OOP) principles
Allows encapsulation (data hiding), which enhances security and maintainability

Syntax:
// Class Declaration
class ClassName {

// Fields (Variables)

datatype variableName;

// Method

returnType methodName(parameters) {
// method body

}
}
3

// Object Creation

ClassName obj = new ClassName(); // creating object

Procedure:
1. Open your IDE or text editor.
2. Create a new Java file named Student.java.
3. Define a class Student with fields like name, age, and methods like displayDetails().
4. In the main method, create objects of the class and call methods.
5. Compile and run the program.
6. Observe the output and verify the behavior.
4

Example:

class Car {
String model;
int year;

void start() {
System.out.println("Car is starting...");
}
}

Algorithm:
1. Start.
2. Define a class Student with fields: name, rollNumber, and grade.
3. Add a method to input student details.
4. Add a method to display student details.
5. Create a main() method in another class (e.g., StudentDemo).
6. Create an object of Student and call input/display methods.
7. Stop.

Program:

// Student.java
import java.util.Scanner;

class Student {
String name;
int rollNumber;
char grade;

// Method to input student details


void inputDetails() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
name = sc.nextLine();
System.out.print("Enter Roll Number: ");
rollNumber = sc.nextInt();
System.out.print("Enter Grade: ");
grade = sc.next().charAt(0);
}

// Method to display student details


void displayDetails() {
System.out.println("----- Student Details -----");
System.out.println("Name : " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Grade : " + grade);
}
}
5

// StudentDemo.java
public class StudentDemo {
public static void main(String[] args) {
Student s1 = new Student(); // Object creation
s1.inputDetails(); // Method call
s1.displayDetails(); // Method call
}
}

Sample Output:

Enter Name: Alice


Enter Roll Number: 101
Enter Grade: A
----- Student Details -----
Name : Alice
Roll Number: 101
Grade :A

Conclusion:

In this experiment, we successfully implemented a Java program to demonstrate the concept of Classes and
Objects. We learned how to define a class, create objects, and use methods to encapsulate behavior. This forms
the base for object-oriented programming and full stack development using Java.
6

EXPERIMENT NO:2

TITLE OF EXPERIMENT: Method and Constructor Overloading

AIM: To implement and understand Method Overloading and Constructor Overloading in Java.

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


1 System 1
2 Java JDK, Command Prompt -

Theory

1. Method Overloading:

 Definition: Defining multiple methods in the same class with the same name but different
parameter lists.
 Purpose: Increases program readability and reusability.

int add(int a, int b);


double add(double a, double b);

2. Constructor Overloading:

 Definition: A class can have multiple constructors with different parameter lists.
 Purpose: Allows different ways of object creation.

Student() {}

Student(String name) {}

Student(String name, int age) {}

Example:

Create a class Calculator to demonstrate:

 Method Overloading: add() with different parameter types


 Constructor Overloading: Constructors with different numbers of parameters
7

Algorithm:

1. Start.
2. Define a class Calculator.
3. Implement multiple add() methods with different parameters (int, double).
4. Create overloaded constructors.
5. Instantiate objects using different constructors.
6. Call various add() methods to show overloading.
7. Stop.

Program:

// Calculator.java
public class Calculator {
int a, b;

// Constructor Overloading
Calculator() {
System.out.println("Default Constructor");
}

Calculator(int x, int y) {
a = x;
b = y;
System.out.println("Parameterized Constructor: " + a + ", " + b);
}

// Method Overloading
int add(int x, int y) {
return x + y;
}

double add(double x, double y) {


return x + y;
}

int add(int x, int y, int z) {


return x + y + z;
}
}
8

// CalculatorDemo.java
public class CalculatorDemo {
public static void main(String[] args) {
// Constructor overloading
Calculator c1 = new Calculator();
Calculator c2 = new Calculator(10, 20);

// Method overloading
System.out.println("add(int, int): " + c2.add(5, 10));
System.out.println("add(double, double): " + c2.add(3.5, 4.5));
System.out.println("add(int, int, int): " + c2.add(1, 2, 3));
}
}

Sample Output:

Default Constructor
Parameterized Constructor: 10, 20
add(int, int): 15
add(double, double): 8.0
add(int, int, int): 6

Conclusion:

In this experiment, we explored Method and Constructor Overloading in Java. We learned how to define
multiple methods and constructors with the same name but different parameter lists. This supports compile-time
polymorphism, enhances flexibility, and allows multiple ways to initialize and interact with objects.
9

EXPERIMENT NO:3

TITLE OF EXPERIMENT: Programs on Various Types of Inheritance and Exception Handling

AIM: To understand and implement different types of inheritance and apply exception handling mechanisms in
Java.

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


3 System 1
4 Java JDK, Command -

Theory

Inheritance in Java:

Inheritance is a mechanism where one class (child class) inherits the properties and behaviors (fields and
methods) of another class (parent class).

Types of Inheritance:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance (Not directly supported in Java with classes but can be achieved using
interfaces)

➤ Exception Handling:

Exception handling is a powerful mechanism in Java to handle runtime errors to maintain the normal flow of
the application using:

 try
 catch
 finally
 throw
 throws
10

PROCEDURE:

1. Open your IDE or text editor.


2. Create Java classes demonstrating different types of inheritance.
3. Add exception handling in relevant parts.
4. Compile the program using javac.
5. Run the program using java.
6. Observe and analyze the output.

SYNTAX:

Inheritance:
class Parent {
// fields and methods
}

class Child extends Parent {


// additional fields and methods
}

Exception Handling:

try {
// risky code
} catch (ExceptionType name) {
// exception handler
} finally {
// optional, cleanup code
}

ALGORITHM:

1. Define base class (Parent).


2. Define derived class (Child) using extends.
3. Override methods if necessary.
4. Add a block of code that may throw an exception.
5. Use try-catch-finally to handle exceptions.
6. Print output for successful execution and exception.

PROGRAMS:
1. Single Inheritance with Exception Handling

class Animal {

void eat() {

System.out.println("This animal eats food.");

}
11

class Dog extends Animal {

void bark() {

System.out.println("Dog barks.");

void divide(int a, int b) {

try {

int result = a / b;

System.out.println("Division Result: " + result);

} catch (ArithmeticException e) {

System.out.println("Exception caught: " + e);

public class SingleInheritanceDemo {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat();

dog.bark();

dog.divide(10, 0); // Causes ArithmeticException

}
12

2. Multilevel Inheritance

class Grandparent {

void show() {

System.out.println("Grandparent class");

class Parent extends Grandparent {

void display() {

System.out.println("Parent class");

class Child extends Parent {

void print() {

System.out.println("Child class");

public class MultilevelDemo {

public static void main(String[] args) {

Child obj = new Child();

obj.show();

obj.display();

obj.print();

}
13

3. Hierarchical Inheritance

class Vehicle {

void start() {

System.out.println("Vehicle started");

class Car extends Vehicle {

void drive() {

System.out.println("Car is driving");

class Bike extends Vehicle {

void ride() {

System.out.println("Bike is riding");

public class HierarchicalDemo {

public static void main(String[] args) {

Car c = new Car();

c.start();

c.drive();

Bike b = new Bike();


14

b.start();

b.ride();

OUTPUT:
Program 1:

This animal eats food.

Dog barks.

Exception caught: java.lang.ArithmeticException: / by zero

Program 2:

Grandparent class

Parent class

Child class

Program 3:

Vehicle started

Car is driving

Vehicle started

Bike is riding

Program 4:

Exception: Index 5 out of bounds for length 3

Execution finished.

CONCLUSION:

The experiment successfully demonstrated various types of inheritance (single, multilevel, and hierarchical) in
Java. It also showed how exception handling ensures that the program continues execution even in the presence of
runtime errors, thereby making it robust and reliable.
15

EXPERIMENT NO:4

TITLE OF EXPERIMENT: Program on Implementing Generic and HTTP Servlets

AIM: To implement and demonstrate the use of GenericServlet and HttpServlet classes in Java for web-
based request handling using Java Servlet technology.

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


1 System 1
2 Java JDK, Browser (Chrome) -

Theory
1 Servlet:

A Servlet is a Java class that handles HTTP requests and generates responses (typically HTML). It runs
on a servlet container (e.g., Apache Tomcat).

2 GenericServlet:

 An abstract class under javax.servlet.


 Protocol-independent (can be used for any type of request).
 Requires implementation of service() method.

3 HttpServlet:

 Extends GenericServlet.
 Handles HTTP-specific protocols (GET, POST, etc.).
 Developers typically override doGet() or doPost() methods.

PROCEDURE:
1. Set up Apache Tomcat on your system.
2. Create a dynamic web project in your IDE.
3. Implement a GenericServlet.
4. Implement an HttpServlet with doGet() or doPost().
5. Configure web.xml (or use annotations).
6. Deploy the WAR file to Tomcat.
7. Access servlet in browser using http://localhost:8080/YourApp/ServletName.
16

SYNTAX:

GenericServlet:

public abstract class GenericServlet implements Servlet {

public abstract void service(ServletRequest req, ServletResponse res);

HttpServlet:

public class HttpServlet extends GenericServlet {


protected void doGet(HttpServletRequest req, HttpServletResponse res);
protected void doPost(HttpServletRequest req, HttpServletResponse res);
}

ALGORITHM:
1. Create a servlet class.
2. Extend GenericServlet or HttpServlet.
3. Override service() or doGet() method.
4. Set content type and write HTML response.
5. Deploy servlet to Tomcat.
6. Run the servlet in the browser.

PROGRAMS:

1. GenericServlet Example:

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

public class MyGenericServlet extends GenericServlet {


public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h2>This is a GenericServlet Example</h2>");
}
}

web.xml Mapping:

<web-app>
<servlet>
<servlet-name>generic</servlet-name>
17

<servlet-class>MyGenericServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>generic</servlet-name>
<url-pattern>/generic</url-pattern>
</servlet-mapping>
</web-app>

2. HttpServlet Example:

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

public class MyHttpServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h2>This is an HttpServlet GET Example</h2>");
}
}

web.xml Mapping:

<servlet>
<servlet-name>http</servlet-name>
<servlet-class>MyHttpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>http</servlet-name>
<url-pattern>/http</url-pattern>
</servlet-mapping>

OUTPUT:

For /generic:

<h2>This is a GenericServlet Example</h2>

For /http:

<h2>This is an HttpServlet GET Example</h2>


18

CONCLUSION:

The experiment successfully demonstrated the implementation of GenericServlet and HttpServlet in Java. It
showed how Servlets are capable of handling client requests and dynamically generating web responses. While
GenericServlet is protocol-independent, HttpServlet is specifically designed for handling HTTP-based
requests.
19

EXPERIMENT NO:5

TITLE OF EXPERIMENT: Program on Implicit and Explicit Objects in JSP

AIM: To demonstrate the use of implicit and explicit objects in JavaServer Pages (JSP) for dynamic web content
generation.

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


5 System 1
6 Java JDK, Browser (Chrome) -

Theory

JSP (JavaServer Pages):

JSP is a server-side technology used to create dynamic, platform-independent web content. It allows
embedding Java code into HTML using special JSP tags.

Implicit Objects in JSP:

Implicit objects are predefined by the JSP container and available to all JSP pages without explicit
declaration. This Include

Object Type Purpose

request HttpServletRequest For accessing request information

response HttpServletResponse For modifying response

out JspWriter For sending content to client

session HttpSession For managing session data

application ServletContext For accessing application-wide data

config ServletConfig For accessing servlet config info

pageContext PageContext For accessing all JSP scopes

page Object Reference to the current page object

exception Throwable Used in error pages


20

Explicit Objects in JSP:

These are manually declared Java objects (variables or classes) by the developer inside a JSP page.

<%! int count = 0; %> <%-- Declaration block --%>

<% count++; %> <%-- Scriptlet block --%>

<%= count %> <%-- Expression block --%>

PROCEDURE:

1. Create a Dynamic Web Project in your IDE.


2. Create JSP pages using implicit and explicit objects.
3. Deploy the project on Apache Tomcat.
4. Access the JSP pages in the browser and observe output.
5. Analyze how implicit and explicit objects behave.

SYNTAX:

Implicit Object Usage:

<%= request.getParameter("username") %>


<%= session.getId() %>
<%= application.getInitParameter("param") %>

Explicit Object Declaration:

<%! int counter = 0; %> <%-- declaration --%>


<% counter++; %> <%-- scriptlet --%>
<%= counter %> <%-- expression --%>

ALGORITHM:

1. Create a JSP page.


2. Use request, session, and other implicit objects.
3. Declare variables explicitly using <%! %> block.
4. Use expressions <%= %> to print results.
5. Run the JSP page and verify the behavior.
21

PROGRAM:
File: implicitExplicit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="java.util.*" %>

<%!
int counter = 0; // Explicit declaration
%>

<html>
<head><title>Implicit & Explicit Object Demo</title></head>
<body>
<h2>Demonstration of JSP Implicit and Explicit Objects</h2>

<%
counter++; // Explicit usage
String name = request.getParameter("name"); // Implicit object
if(name == null) name = "Guest";
%>

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


<p>This page has been refreshed <%= counter %> times since last deployment.</p>

<p>Session ID: <%= session.getId() %></p>


<p>Server Time: <%= new Date() %></p>
</body>
</html>
Optional: web.xml (if no annotation is used)
<web-app>
<welcome-file-list>
<welcome-file>implicitExplicit.jsp</welcome-file>
</welcome-file-list>
</web-app>
22

OUTPUT:
When accessed via URL like:
http://localhost:8080/JSPDemo/implicitExplicit.jsp?name=John

Output:
Demonstration of JSP Implicit and Explicit Objects
Welcome, John!
This page has been refreshed 1 times since last deployment.
Session ID: 1A23B456CDE78F9G123H456IJKL
Server Time: Sun Aug 04 14:50:22 IST 2025

CONCLUSION:

This experiment demonstrates how implicit objects such as request, session, and application provide
essential server-side functionality in JSP without needing to declare them. It also highlights how explicit objects
allow developers to manage custom logic and variables within JSP pages.
23

EXPERIMENT NO:6

TITLE OF EXPERIMENT: Create a Website Using HTML, CSS, and JavaScript

AIM: To design and develop a basic website using HTML for structure, CSS for styling, and JavaScript for
interactivity, as part of full stack Java programming.

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


2 System 1
2 Java JDK, Code editor (VS Code, -

Theory
In full-stack development, the frontend (client-side) is the part users interact with. It is built using:

 HTML (HyperText Markup Language): Provides the structure of web pages.


 CSS (Cascading Style Sheets): Adds styling to HTML elements.
 JavaScript: Adds dynamic behavior to the website, such as event handling and DOM
manipulation.

In a full stack Java project, the frontend communicates with the backend (Java-based server) using APIs,
but in this experiment, we're focusing only on the frontend development part.

PROCEDURE:

1. Open your code editor.


2. Create a project folder.
3. Inside the folder, create three files:
o index.html (HTML structure)
o style.css (CSS styling)
o script.js (JavaScript behavior)
4. Link the CSS and JS files in the HTML file.
5. Write code for a simple webpage (e.g., a portfolio or landing page).
6. Run index.html in the browser and test the interactivity.
24

Syntax:
HTML:

<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<!-- Content here -->
</body>
</html>

CSS:

selector {
property: value;
}

JavaScript:

document.getElementById("id").addEventListener("click", functionName);

Algorithm:
1. Start.
2. Create HTML elements (heading, paragraph, button).
3. Style the elements using CSS.
4. Add JavaScript event listeners to handle user interaction.
5. Test the output on the browser.
6. Stop.

Program:
🔹 index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Website</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a simple webpage using HTML, CSS, and JavaScript.</p>
<button onclick="showMessage()">Click Me</button>
<p id="message"></p>

<script src="script.js"></script>
</body>
</html>
25

🔹 style.css
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
text-align: center;
padding-top: 50px;
}

h1 {
color: #333;
}

button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}

🔹 script.js
function showMessage() {
document.getElementById("message").textContent = "Hello! You clicked the button.";
}

Output:

When the page loads:

 A heading and a paragraph are displayed.


 A button labeled "Click Me" is shown.

When the user clicks the button:

 The message "Hello! You clicked the button." appears below the button.

Conclusion:

In this experiment, we successfully created a simple and interactive web page using HTML, CSS, and JavaScript.
This forms the frontend of a full-stack Java application, which can later be connected to a backend using Java
(e.g., using Spring Boot).
26

EXPERIMENT NO:7

TITLE OF EXPERIMENT: DOM Manipulation to Change Background Color Automatically

AIM: To create a webpage using HTML, CSS, and JavaScript that utilizes the Document Object Model
(DOM) to change the background color of the page automatically every 5 seconds.

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


3 System 1
2 Java JDK, Code editor (VS Code, -

Theory
In full-stack development, the frontend (client-side) is the part users interact with. It is built using:

 HTML (HyperText Markup Language): Provides the structure of web pages.


 CSS (Cascading Style Sheets): Adds styling to HTML elements.
 JavaScript: Adds dynamic behavior to the website, such as event handling and DOM
manipulation.

In a full stack Java project, the frontend communicates with the backend (Java-based server) using APIs,
but in this experiment, we're focusing only on the frontend development part.

PROCEDURE:

7. Open your code editor.


8. Create a project folder.
9. Inside the folder, create three files:
o index.html (HTML structure)
o style.css (CSS styling)
o script.js (JavaScript behavior)
10. Link the CSS and JS files in the HTML file.
11. Write code for a simple webpage (e.g., a portfolio or landing page).
12. Run index.html in the browser and test the interactivity.

Syntax Used:
setInterval(function, milliseconds)
document.body.style.backgroundColor = "color";
Math.floor(Math.random() * array.length)
27

Algorithm:
1. Define an array of colors.
2. Use setInterval() to call a function every 5 seconds.
3. In the function, randomly select a color from the array.
4. Change the document body’s background color to the selected color using DOM.

Program (HTML + JavaScript):

<!DOCTYPE html>
<html>
<head>
<title>Auto Background Color Change</title>
<style>
body {
transition: background-color 1s;
font-family: Arial, sans-serif;
text-align: center;
margin-top: 20%;
color: white;
font-size: 24px;
}
</style>
</head>
<body>
<p>Background color will change every 5 seconds</p>

<script>
const colors = ["red", "green", "blue", "purple", "orange", "pink", "teal", "brown", "black",
"yellow"];

function changeBackgroundColor() {
const randomIndex = Math.floor(Math.random() * colors.length);
document.body.style.backgroundColor = colors[randomIndex];
}

// Change color every 5 seconds (5000 ms)


setInterval(changeBackgroundColor, 5000);
</script>
</body>
</html>
28

Output:
A webpage with a message:
"Background color will change every 5 seconds"

 The background color will automatically change every 5 seconds to a randomly selected color from the
predefined list.

Conclusion:
In this experiment, we successfully demonstrated the use of the Document Object Model (DOM) to dynamically
manipulate the background color of a webpage using JavaScript. The background color changes every 5 seconds
using setInterval() and DOM manipulation. This is a basic example of how front-end interactivity is handled
in Full Stack Web Development.
29

EXPERIMENT NO:8

TITLE OF EXPERIMENT: Program to create a Monolithic Application using SpringBoot


AIM: To develop a Monolithic Application using Spring Boot that serves a web page which
changes the background color every 5 seconds using DOM and JavaScript.

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


1 System 1
2 JDK 17 or later Spring Web -

Theory

 A monolithic application is a single-tiered software where the UI, business logic, and data
access layer are combined into one program.
 Spring Boot is used to build stand-alone, production-grade Spring-based applications with
minimal configuration.
 We use Thymeleaf as a server-side rendering engine to serve HTML.
 The front end uses JavaScript and DOM to dynamically change the background color of the
page.

Project Structure:
Css

monolithic-color-app/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com.example.colorapp/
│ │ │ └── ColorAppApplication.java
│ │ ├── resources/
│ │ │ ├── templates/
│ │ │ │ └── index.html
│ │ │ └── application.properties
├── pom.xml
30

1. pom.xml
Add the necessary dependencies:

<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>

<artifactId>colorapp</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>ColorApp</name>

<description>Monolithic Spring Boot App to change background color</description>

<properties>

<java.version>17</java.version>

</properties>

<dependencies>

<!-- Spring Boot Web -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!-- Thymeleaf -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>
31

</dependency>

<!-- Test (optional) -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

<build>

<plugins>

<!-- Spring Boot Plugin -->

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>
32

2. Application Class
ColorAppApplicaion.java

package com.example.colorapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@SpringBootApplication
@Controller
public class ColorAppApplication {

public static void main(String[] args) {


SpringApplication.run(ColorAppApplication.class, args);
}

@GetMapping("/")
public String home() {
return "index"; // maps to src/main/resources/templates/index.html
}
}

3. HTML Template with JavaScript


src/main/resources/templates/index.html

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<head>

<title>Spring Boot Color Changer</title>

<style>

body {

transition: background-color 1s;

font-family: Arial, sans-serif;

text-align: center;

margin-top: 20%;

color: white;

font-size: 24px;

}
33
</style>

</head>

<body>

<p>Background color will change every 5 seconds</p>

<script>

const colors = ["red", "green", "blue", "purple", "orange", "pink", "teal", "brown",
"black", "yellow"];

function changeBackgroundColor() {

const randomIndex = Math.floor(Math.random() * colors.length);

document.body.style.backgroundColor = colors[randomIndex];

// Change background color every 5 seconds

setInterval(changeBackgroundColor, 5000);

</script>

</body>

</html>

4. Run the Application


Use your terminal or IDE to run the Spring Boot application:

mvn spring-boot:run

Then open your browser and go to:


http://localhost:8080/

Output:
A simple web page will appear with the message:
"Background color will change every 5 seconds"

 The page background will change color every 5 seconds, as expected.


34

Conclusion:
In this experiment, we successfully built a Monolithic Spring Boot application that serves a web page where the
background color changes automatically using DOM and JavaScript.
This demonstrates a Full Stack Java approach where:

 The backend (Spring Boot) handles routing and template rendering.


 The frontend handles dynamic behavior using JavaScript.

This is a typical architecture in a monolithic full-stack Java application.


35

EXPERIMENT NO:9

TITLE OF EXPERIMENT: Program for Building RESTful APIs with spring boot

AIM: To develop a RESTful API using Spring Boot that returns a random background color and build a
front-end that fetches this data and changes the background color every 5 seconds.

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


1 System 1
2 JDK 17+ , Spring Boot -

Theory
 REST (Representational State Transfer) is a stateless architecture that allows communication
between client and server using HTTP.

 Spring Boot simplifies creating RESTful web services using @RestController.

 The front-end calls the REST API using JavaScript Fetch API at regular interva

Project Structure:

color-api-app/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com.example.colorapi/
│ │ │ ├── ColorApiApplication.java
│ │ │ └── controller/
│ │ │ └── ColorController.java
│ │ ├── resources/
│ │ │ ├── static/
│ │ │ │ └── index.html
│ │ │ └── application.properties
├── pom.xml
36

1. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>color-api-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Color API App</name>
<description>Spring Boot REST API for background color</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Optional Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
37

2. ColorApiApplication.java
package com.example.colorapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ColorApiApplication {

public static void main(String[] args) {


SpringApplication.run(ColorApiApplication.class, args);
}
}
3. ColorController.java
package com.example.colorapi.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;
import java.util.Map;

@RestController
public class ColorController {

private final List<String> colors = List.of(


"red", "green", "blue", "purple", "orange",
"pink", "teal", "brown", "black", "yellow"
);

private final Random random = new Random();

@GetMapping("/api/color")
public Map<String, String> getRandomColor() {
int index = random.nextInt(colors.size());
return Map.of("color", colors.get(index));
}
}
38

4. index.html (Front-End)
Place this in:
src/main/resources/static/index.html

<!DOCTYPE html>
<html>
<head>
<title>REST API Color Changer</title>
<style>
body {
transition: background-color 1s;
font-family: Arial, sans-serif;
text-align: center;
margin-top: 20%;
color: white;
font-size: 24px;
}
</style>
</head>
<body>
<p>Background color will change every 5 seconds via REST API</p>

<script>
function changeBackgroundColor() {
fetch('/api/color')
.then(response => response.json())
.then(data => {
document.body.style.backgroundColor = data.color;
})
.catch(error => console.error('Error fetching color:', error));
}

// Call initially and then every 5 seconds


changeBackgroundColor();
setInterval(changeBackgroundColor, 5000);
</script>
</body>
</html>

5 Run the Application


mvn spring-boot:run

Output:

 REST API returns:

{
"color": "blue"
}

 The frontend fetches this color and applies it to the page background.
 The page updates every 5 seconds using setInterval().
39

Conclusion:
In this experiment, we built a RESTful API using Spring Boot and connected it with a JavaScript-based front
end. The backend randomly returns a color, and the frontend updates the webpage background using that value.
This structure follows modern REST architecture and demonstrates client-server interaction in Full Stack Java
Development.
40

EXPERIMENT NO:10

TITLE OF EXPERIMENT: Creating a Single Page website using the concepts in React like
Hooks, Router, Props and States.
AIM:
To design and develop a Single Page Website (SPA) using React that utilizes the following concepts:
React Hooks ,React Router ,Props ,State management

FACILITIES REQUIRED AND PROCEDURE


Facilities required to do the experiment:

S. No. Facilities required Quantity


1 System 1
2 VS Code -

Theory
🔹 ReactJS:
A JavaScript library for building user interfaces, especially Single Page Applications (SPAs). React
is component-based and supports unidirectional data flow.
🔹 Hooks:
Hooks are functions that let you "hook into" React state and lifecycle features. Common hooks:
useState() – for state management
useEffect() – for side effects like API calls
🔹 React Router:
Used for client-side routing in a SPA, enabling navigation between components without refreshing the
page.
🔹 Props:
Short for "properties", props are used to pass data from parent to child components.
🔹 State:
State is a built-in object that stores property values that belong to the component.

Syntax Overview:
useState Hook:

const [count, setCount] = useState(0);

React Router:

<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
41

Passing Props:

<ChildComponent message="Hello" />

Using Props:

function ChildComponent(props) {
return <p>{props.message}</p>;
}

Procedure:

1. Open terminal and create a React project:

npx create-react-app spa-demo

cd spa-demo

2. Install React Router:

npm install react-router-dom

3. Create folder structure:


 components/ → For reusable components
 pages/ → For different views like Home, About
4. Implement routing, state, props, and hooks in the app.
5.Start the development server:
npm start
6.Open the browser and test the functionality.

Sample Program: Single Page Website with React


📁 Folder Structure:
src/
App.js
index.js
components/
Header.js
pages/
Home.js
About.js
42

App.js
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Header from './components/Header';
import Home from './pages/Home';
import About from './pages/About';

function App() {
return (
<BrowserRouter>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}

export default App;

Header.js (Navigation)
import React from 'react';
import { Link } from 'react-router-dom';

function Header() {
return (
<nav>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
</nav>
);
}

export default Header;

Home.js
import React, { useState } from 'react';

function Home() {
const [count, setCount] = useState(0);

return (
<div>
<h1>Welcome to Home Page</h1>
<p>Button clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
}

export default Home;


43

About.js

import React from 'react';

function About() {
const developer = "Alice";

return (
<div>
<h1>About Us</h1>
<p>This website was built by {developer} using React.</p>
</div>
);
}

export default About;

Expected Output:

 A web page with navigation links: Home | About


 Clicking "Home" shows a counter using useState
 Clicking "About" shows developer info using props/state

Conclusion:
This experiment demonstrates how to build a basic Single Page Application using React, integrating concepts
such as Hooks, Router, Props, and State. It provides hands-on experience with component-based architecture
and dynamic routing.
44
45
46
47
48
49
50
51
52

You might also like