Hello world!
The main goal of this article is to help beginner developers handle HTTP requests in Spring Boot.
?In the examples I do not cover all the code required for the MVC app, just some parts to demonstrate the difference in data processing.
Recently, I’ve been working on an engineering project with other students in my class. It introduced us to a new technology stack, as we were required to build upon an “old” codebase. The codebase included Java, Spring Boot, and Thymeleaf. The project's aim was to create a clone of a popular social network.
The core functionality was fairly typical: users can create posts, and others can comment on or like those posts.
To add some visual dynamism, we decided to combine Thymeleaf with JavaScript. This way, when a post is displayed on the page, users can click to like or comment, and the changes will be processed in the back end. At this point, we needed a JavaScript function to send requests to the server for all the standard CRUD operations.
The question was: how do we properly pass data to the server using POST, PUT, or DELETE methods? GET is more or less clear, so I skip examples with GET.
Here are the possible ways.
URL Parameters (PathVariable)
URL Example: HTTP://myapp.com/posts/1
Suitable for: DELETE, PUT
Cases: You work with a specific entity on a back end - a single post in my examples.
Annotation Example:
@DeleteMapping("/posts/{post_id}") public ResponseEntity<String> deletePost(@PathVariable("post_id") Long post_id) { // Some logic here... return ResponseEntity.ok("Deleted successfully"); }
Example of a corresponding JS code:
// Some pre-logic here to pass postId to the function, // or you can use const deletePost = async(postId)=>{} to pass postId directly const deletePost = async () => { // Some pre-checks and error handling go here... const requestOption = { method:'DELETE', headers:{ 'Content-type':'application/json' } }; await fetch(`/posts/${postId}`, requestOptions); // Some post-checks and error handling go here... }
Form data (RequestParam)
URL Example: HTTP://myapp.com/posts or HTTP://myapp.com/posts/1 for editing
Suitable for: PUT, POST
Cases: You are creating or updating an entity with one or two parameters. In my example, it’s a post content (a text message).
Annotation Example:
@PutMapping("/posts/{post_id}") public ResponseEntity<String> editPost(@PathVariable("post_id") Long post_id, @RequestParam("content") String content) { // Some logic goes here... return ResponseEntity.ok("Post updated successfully"); }
Example of a corresponding JS code:
// Some pre-logic here to pass postId and content to the function, // or you can use const deletePost = async(postId, updatedContent)=>{} to pass // them directly directly const updatePost = async ()=> { // Some pre-checks and error handling go here... const formData = new FormData(); formData.append("content",updatedContent); requestOptions = { method:'PUT', body: formData }; await fetch(`/posts/${postId}`,requestOptions); // Some post-checks and error handling go here... }
JSON Body (RequestBody)
Suitable for: PUT, POST
Cases: You are creating or updating a complex entity (e.g. object with 3 or more parameters).
Annotation Example:
@PutMapping("/posts/{post_id}") public ResponseEntity<String> editPost(@PathVariable("post_id") Long post_id, @RequestBody Post post) { // Some logic goes here... // It requires the whole object to be passed. // After that it's possible to access values via getters of your object's model return ResponseEntity.ok("Post updated successfully"); }
Example of a corresponding JS code:
const updatePost = async ()=> { // Some pre-checks and error handling go here... requestOptions = { method:'PUT', headers: { 'Content-type':'application/json' }, body: JSON.stringify({'content':updatedContent}) }; await fetch(`/posts/${postId}`,requestOptions); // Some post-checks and error handling go here... }
This is it. Hope it will be helpful.
Cheers!
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!