Java Exercise
In this exercise, you will create a Java program using Spring Boot to develop a simple web application. The goal is to familiarize yourself with configuring a Spring Boot project, creating controllers, and managing HTTP routes. You will begin by creating a Spring Boot project, configuring a controller to handle web requests, and returning a simple response. This exercise will help you understand the fundamental principles of Spring Boot and how to get started building web applications with Java.
Instructions:
- Set up your development environment and install the necessary tools to work with Spring Boot.
- Create a new Spring Boot project using Spring Initializr or your preferred IDE.
- Develop a controller that responds to an HTTP GET request on a specific route (for example, "/greeting").
- Configure a simple response in text or HTML format to be sent when that route is accessed.
- Run your application and verify that you can access the route from a web browser or a tool like Postman.
This exercise will give you a solid understanding of Spring Boot fundamentals, enabling you to build basic web applications quickly and efficiently.
View Example Code
package com.example.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class SpringBootApplicationExample {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplicationExample.class, args);
}
}
@RestController
class GreetingController {
@GetMapping("/greeting")
public String greeting() {
return "<html><body><h1>Hello, welcome to Spring Boot!</h1></body></html>";
}
}
Output:
<html>
<body>
<h1>¡Hello, welcome to Spring Boot!</h1>
</body>
</html>
This program demonstrates how to create a basic web application with Spring Boot. The controller responds to the /greeting
route with a simple HTML page displaying a welcome message. This is a basic way to get started with Java web applications using Spring Boot.