Program 8
Create industry oriented application using Spring Framework
Project Structure:
1. Spring Boot Application: The entry point of the application.
2. Controller: REST API endpoint.
Step-by-Step Implementation:
1. Spring Boot Application
First, create a new Spring Boot project using Spring Initializr (https://start.spring.io/) with the
following dependencies:
Spring Web
2. Controller (WelcomeController.java)
packagecom.example.demo.controller;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RestController;
@RestController
public class WelcomeController {
@GetMapping("/welcome")
public String welcome() {
return "Welcome to the Spring Boot Application!";
}
}
3. Main Class (DemoApplication.java)
packagecom.example.demo;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Running the Application:
1. Make sure you have Java and Maven installed.
2. Build the project using Maven: mvn clean install.
3. Run the application: mvnspring-boot:run.
4. Access the API endpoint via http://localhost:8080/welcome.
Practical 9
Testing RESTful Web Services with Spring Boot.
Pre-requisites
Java Development Kit (JDK) installed
Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or VS Code
Maven or Gradle installed
Basic understanding of Spring Boot and RESTful web services
Step 1: Set Up Spring Boot Application
1.1. Create a New Spring Boot Project
1. Go to Spring Initializr.
2. Choose the following settings:
o Project: Maven Project
o Language: Java
o Spring Boot: Latest stable version
o Project Metadata:
Group: com.example
Artifact: rest-service
Name: rest-service
Package Name: com.example.restservice
o Dependencies:
Spring Web
Spring Boot DevTools
Spring Boot Starter Test
3. Click "Generate" to download the project as a ZIP file.
4. Extract the ZIP file and open it in your IDE.
Step 2: Create RESTful Endpoints
2.1. Create a Controller
1. In the src/main/java/com/example/restservice directory, create a package named
controller.
2. Inside the controller package, create a class named HelloController.
packagecom.example.restservice.controller;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
2.2. Main Application Class
Ensure your main application class is set up to run your Spring Boot application:
packagecom.example.restservice;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestServiceApplication {
public static void main(String[] args) {
SpringApplication.run(RestServiceApplication.class, args);
}
}
Step 3: Writing Tests for RESTful Endpoints
3.1. Add Dependencies for Testing
Ensure your pom.xml includes the Spring Boot Starter Test dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
3.2. Create a Test Class
1. In the src/test/java/com/example/restservice directory, create a package named
controller.
2. Inside the controller package, create a class named HelloControllerTest.
packagecom.example.restservice.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
importorg.junit.jupiter.api.Test;
importorg.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
privateMockMvcmockMvc;
@Test
public void testSayHello() throws Exception {
mockMvc.perform(get("/api/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, World!"));
}
}
Step 4: Run the Tests
1. In your IDE, locate the test class HelloControllerTest.
2. Right-click on the class and select "Run HelloControllerTest" to execute the tests.
3. Alternatively, you can run the tests using Maven from the command line:
./mvnw test
Practical 10
Test a frontend web application that interacts with a Spring Boot.
Prerequisites
Java Development Kit (JDK)
Integrated Development Environment (IDE)
Node.js and npm
Steps
Step 1: Set Up Spring Boot Backend
1. Create a Spring Boot Project:
o Use Spring Initializr.
o Group: com.example
o Artifact: backend-service
o Dependencies: Spring Web, Spring Boot DevTools, Spring Boot Starter Test
2. Create a REST Controller:
packagecom.example.backendservice.controller;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class GreetingController {
@GetMapping("/greeting")
public String greeting(@RequestParam(value = "name", defaultValue = "World") String
name) {
returnString.format("Hello, %s!", name);
}
}
3. Main Application Class:
packagecom.example.backendservice;
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BackendServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BackendServiceApplication.class, args);
}
}
Step 2: Set Up React Frontend
1. Create a React App:
npx create-react-app frontend-app
cd frontend-app
2. Create a Component to Fetch Data:
// src/Greeting.js
import React, { useState, useEffect } from 'react';
function Greeting() {
const [greeting, setGreeting] = useState('');
useEffect(() => {
fetch('http://localhost:8080/api/greeting?name=React')
.then(response =>response.text())
.then(data =>setGreeting(data));
}, []);
return (
<div>
<h1>{greeting}</h1>
</div>
);
}
export default Greeting;
3. Update App.js:
import React from 'react';
import './App.css';
import Greeting from './Greeting';
function App() {
return (
<div className="App">
<header className="App-header">
<Greeting />
</header>
</div>
);
}
export default App;
Step 3: Testing
1. Backend Testing:
// src/test/java/com/example/backendservice/GreetingControllerTest.java
packagecom.example.backendservice;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
importorg.junit.jupiter.api.Test;
importorg.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
public class GreetingControllerTest {
@Autowired
privateMockMvcmockMvc;
@Test
public void testGreeting() throws Exception {
mockMvc.perform(get("/api/greeting?name=React"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, React!"));
}
}
Run the backend tests using your IDE or with Maven:
./mvnw test
2. Frontend Testing:
Install testing dependencies:
npm install --save-dev @testing-library/react @testing-library/jest-dom
Create a test for the Greeting component:
// src/Greeting.test.js
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import Greeting from './Greeting';
global.fetch = jest.fn(() =>
Promise.resolve({
text: () =>Promise.resolve('Hello, React!'),
})
);
test('renders greeting', async () => {
render(<Greeting />);
awaitwaitFor(() =>screen.getByText('Hello, React!'));
expect(screen.getByText('Hello, React!')).toBeInTheDocument();
});
Run the frontend tests:
npm test