4-Creating a Web Application with Spring Boot
4-Creating a Web Application with Spring Boot
Programming
4- Creating a Web Application with
Spring Boot
Creating an Application with Spring Boot -
Creating JSON-based APIs
A key ingredient in building any web application is the ability to provide
an API. In the olden days, this was complex and hard to ensure
compatibility.
In this day and age, the world has mostly converged on a handful of
formats, many based on JSON-based structures.
One of the powerful features of Spring Boot is that when you add
Spring Web to a project, as we did at the beginning of this topic, it adds
Jackson to the classpath. Jackson is a JSON serialization/deserialization
library that has been widely adopted by the Java community.
Creating an Application with Spring Boot -
Creating JSON-based APIs
Jackson’s ability to let us define how to translate Java classes back and
forth with our preferred flavor of JSON combined with Spring Boot’s
ability to autoconfigure things means that we don’t have to lift another
finger of setup to start coding an API.
To start things off, we create a new class in the same package we’ve
been using throughout this topic. Call it ApiController. At the top, apply
the @RestController annotation.
Creating an Application with Spring Boot -
Creating JSON-based APIs
@RestController is similar to the @Controller annotation we used
earlier. It signals to Spring Boot that this class should be automatically
picked up for component scanning as a Spring bean. This bean will be
registered in the application context and also with Spring MVC as a
controller class so it can route web calls.
But it has one additional property—it switches every web method from
being template-based to JSON-based. In other words, instead of a web
method returning the name of a template that Spring MVC renders
through a templating engine, it instead serializes the results using
Jackson.
Creating an Application with Spring Boot -
Creating JSON-based APIs
• We already mentioned how the @RestController
public class ApiController {
@RestController annotation marks this as a private final VideoService videoService;
public ApiController(VideoService videoService) {
Spring MVC controller that returns JSON this.videoService = videoService;
}
• Using constructor injection, we will @GetMapping("/api/videos")
public List<Video> all() {
automatically get a copy of the same return videoService.getVideos();
VideoService we created earlier in this topic }
}
Add the following code to the ApiController class, right below the all()
method: • @PostMapping: Maps HTTP POST calls
to /api/videos onto this method
@PostMapping("/api/videos") • @RequestBody: Spring MVC’s annotation to
signal that the incoming HTTP request body
public Video newVideo(@RequestBody Video newVideo) { should be deserialized via Jackson into
return videoService.create(newVideo); the newVideo argument as a Video record
} • We then delegate the actual handling of this
incoming Video record to our VideoService,
returning back the record after it’s been added
to the system
Creating an Application with Spring Boot -
Creating JSON-based APIs
We already coded this create() operation earlier in this topic, so there’s
no need to go back into it.
Tip
Earlier in the section, we said “curl that endpoint” and saw a chunk of
JSON printed out. curl is a popular command-line tool that lets you
interact with web APIs
With our new addition to our API controller, we can interact with it
from the command line as follows:
$ curl -v -X POST localhost:8080/api/videos -d '{"name": "Learning Spring Boot 3"}' -H 'Content-
type:application/json'
Creating an Application with Spring Boot -
Creating JSON-based APIs
$ curl -v -X POST localhost:8080/api/videos -d '{"name": "Learning Spring Boot 3"}' -H 'Content-
type:application/json'
The preceding command will update package.json with the react and react-dom modules.
Now, we can start writing some JavaScript!
Create index.js inside src/main/javascript as follows:
import ReactDOM from "react-dom"
import { App } from "./App"
const app = document.getElementById("app")
ReactDOM.render(<App />, app)
Creating an Application with Spring Boot -
Creating a React.js app
import ReactDOM from "react-dom"
import { App } from "./App"
const app = document.getElementById("app")
ReactDOM.render(<App />, app)
• The first line imports ReactDOM, a key module needed to launch React
• The second line imports the custom UI we’ll build further
• The third line uses vanilla JavaScript to find the element on the web page with id="app" where we can “hang”
our app
• The fourth line actually renders the <App/> component in our soon-to-be-coded app using ReactDOM
Creating an Application with Spring Boot -
Creating a React.js app
React operates with a top-down perspective. You render a top-level component, and then that component, in
turn, renders components nested further down.
It also uses a shadow document object model (DOM) where we don’t specify the actual nodes to render, but
instead use virtual nodes. React computes the changes from whatever the current state is and generates the
changes.
To continue building this application, we need to create App.js in src/main/javascript as follows:
}
this.handleSubmit = this.handleSubmit.bind(this);
What’s important to clarify, is that properties are typically considered immutable
handleChange(event) { within the React component that has them injected. State is meant to evolve and
this.setState({name: event.target.value}) change, in turn driving our rendered elements.
}
async handleSubmit(event) {
event.preventDefault()
Our React app wouldn’t be much if we couldn’t create new entries. So, let’s create a
await fetch("/api/videos", { new component that duplicates the HTML form we created earlier in this topic in the
method: "POST", Changing the data through HTML forms section!
headers: {
"Content-type": Create NewVideo.js as shown here in src/main/javascript
"application/json"
},
body: JSON.stringify({name: this.state.name})
This React component has some of the same bits as the other one, such as the import statement as
}).then(response => well as a JavaScript class extending React.Component. But it contains some different parts, which
window.location.href = "/react")
} are as follows:
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text"
value={this.state.name}
onChange={this.handleChange}/>
<button type="submit">Submit</button>
</form>
)
}
}
export default NewVideo
References
• https://github.com/PacktPublishing/Learning-Spring-Boot-3.0-Third-
Edition