[java, spring] Get HTTP POST Body in Spring Boot with @RequestBody

Introduction

With Spring, we map requests to request handlers via the @RequestMapping annotation. Spring Boot introduced us to derived types of this annotation - @GetMapping@PostMapping@DeleteMapping, etc.

These requests contain different types of information and data - and depending on what our endpoint does with the request, we may want to retrieve the body of a POST request either for logging or further processing.

The @RequestBody annotation allows us to retrieve the request's body. We can then return it as a String or deserialize it into a Plain Old Java Object (POJO).

Spring has built-in mechanisms for deserializing JSON and XML objects into POJOs, which makes this task a lot easier as well.

In this article, we'll get the body of a POST HTTP request and pack it into a String, as well as deserialize it into a POJO.

Getting HTTP POST Body as a String

Let's start out with a @Controller class to handle an incoming request:

@ResponseBody
@Controller
@RequestMapping("/response")
public class HomeController {}

What's worth noting here is that we've added the @ResponseBody annotation to the @Controller. This way, it won't render a template as the response body, but rather, will return a response body. Specifically, we'll pack it in a String and return that.

Spring Boot introduced us to another derived type - @RestController which is just a combination of the previous two annotations. Let's use that instead for brevity:

@RestController
@RequestMapping("/response")
public class HomeController {}

Now, let's go ahead and define a request handler. Since we're handling a POST request, we'll use the @PostMapping annotation for it:

@RestController
@RequestMapping("/response")
public class HomeController {

    @PostMapping("/postbody")
    public String postBody(@RequestBody String fullName) {
        return "Hello " + fullName;
    }
}

To retrieve the body of the POST request sent to the handler, we'll use the @RequestBody annotation, and assign its value to a String. This takes the body of the request and neatly packs it into our fullName String. We've then returned this name back, with a greeting message.

Let's test this controller out via curl:

curl -X POST -H "Content-type: application/json" -d "John Smith" "http://localhost:8080/response/postbody"

This results in:

Hello John Smith

Deserialize HTTP POST into POJO

Now, typically, we won't be working with Strings, although they serve as a good example for learning. In most cases, we'll want to do some processing, or at the least, serialize the request into a POJO. Let's define a Person POJO with a firstName and lastName:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

public class Person {
    private String firstName;
    private String lastName;
    
    // Constructor, getters and setters
}

We'll perform the same process as in the previous example - with the same controller. However, this time, we'll specify that the controller is accepting JSON and XML values and that it produces JSON or XML responses back.

We'll retrieve a POST request body in JSON format, deserialize it into a POJO for further processing (saving into a database, for example) and return a JSON response.

Although Spring Boot can automatically match the JSON body to our POJO, given the variable names match, we'll explicitly set this option. We'll set the input and output formats using the consumes and produces flags in the @PostMapping:

@RestController
@RequestMapping("/response")
public class HomeController {

     @PostMapping(
        value = "/postbody",
        consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},
        produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<Person> postBody(@RequestBody Person person) {
        Person persistedPerson = personService.save(person);
        return ResponseEntity
            .created(URI
                     .create(String.format("/persons/%s", person.getFirstName())))
            .body(persistedPerson);
    }
}

Here, we're accepting JSON and XML, as well as producing it back. We've annotated the Person instance as the @RequestBody, which we'll also be expecting from the request. Then, we've used a PersonService instance to save the person to a database, which also returns the persisted object for further processing.

For brevity's sake, we've omitted the PersonService implementation as it's a standard service-layer implementation.

Finally, we've returned a ResponseEntity object. It's just an extension of the HttpEntity class that also has a status code. We've set the status code as CREATED with a URI location where the new created resource is located. Then, we've set the body of the ResponseEntity as the persistentPerson instance and built the response.

Let's test this controller out via curl again:

 

[출처] https://stackabuse.com/get-http-post-body-in-spring

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
186 [Java Web programming] Spring boot(백엔드)와 React.js(프론트엔드)의 만남 - 프론트엔드 졸리운_곰 2021.08.29 98
185 [java][spring][mybatis] [MyBatis] resultType에 넣을 수 있는 값 정리 졸리운_곰 2021.08.17 303
184 [Java Spring web programming][자바 웹 개발] 10+ Free Open Source Projects Using Spring Boot file 졸리운_곰 2021.08.12 17
183 [java 웹 프로그래밍] Spring boot - Thymeleaf 기본 문법 졸리운_곰 2021.08.11 27
182 [Java 웹 프로그래밍] Tutorial: Thymeleaf + Spring file 졸리운_곰 2021.08.10 15
181 [java][spring boot][gradle] GitHub에서 스프링 부트 & Gradle 프로젝트 Import 하기! file 졸리운_곰 2021.08.05 74
» [java, spring] Get HTTP POST Body in Spring Boot with @RequestBody 졸리운_곰 2021.06.18 15
179 [Java, jsp, jstl] [JSTL] Functions Tag - fn:contains() 사용하기 졸리운_곰 2021.06.09 38
178 [Java, jsp, jstl] [JSTL] List 갯수(size) 구하기 졸리운_곰 2021.06.02 167
177 [java, jsp, jstl] JSTL에서 변수두개사용하기 : jsp jstl list<> 두개를 졸리운_곰 2021.06.02 149
176 [Java Web, JSTL] 반복문 <c:forEach>, <c:forTokens> 졸리운_곰 2021.05.27 20
175 [Java Web] 조건문 <c:if>, <c:choose>, <c:when>, <c:otherwise> 졸리운_곰 2021.05.26 112
174 [java, web dev] forEach를 이용해서 JSTL로 출력하기 졸리운_곰 2021.05.24 70
173 [Java, Web dev] JSTL문법 <c:forEach> c:tag를 이용한 리스트 출력 file 졸리운_곰 2021.05.24 73
172 [Java][Web][Spring] vo 여러개 전달하기. LIST<VO> vo를 list 로 넘기기 / 받기 졸리운_곰 2021.05.20 1865
171 [java web dev, spring, freemaker] freemarker (개념, jsp와 차이, 문법, spring과 연동 설정, 예제) file 졸리운_곰 2021.05.17 33
170 [java web spring] [Spring] web.xml - Filter url 제외시키기 졸리운_곰 2021.05.14 143
169 [Java Web Srping mvc] Spring MVC - home.jsp의 동작원리 file 졸리운_곰 2021.05.14 37
168 [java, web, jsp] Servlet/JSP에서 Ajax 사용 file 졸리운_곰 2021.05.13 438
167 [java][JAVA WEB] [JSP] JSTL 사용 방법 - 주요 태그 문법 정리 . file 졸리운_곰 2021.04.22 13
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED