@RequestBody and @ResponseBody annotations in Spring
Can someone explain the @RequestBody
and @ResponseBody
annotations in Spring 3? What are they for? Any examples would be great.
There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody
javadocs, @ResponseBody
javadocs
Usage examples would be something like this:
Using a JavaScript-library like JQuery, you would post a JSON-Object like this:
{ "firstName" : "Elmer", "lastName" : "Fudd" }
Your controller method would look like this:
// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}
// domain / value objects
public class UserStats{
private String firstName;
private String lastName;
// + getters, setters
}
public class Description{
private String description;
// + getters, setters, constructor
}
Now if you have Jackson on your classpath (and have an <mvc:annotation-driven>
setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody
annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody
annotation). So the Browser / Client would see this JSON result:
{ "description" : "Elmer Fudd hates wacky wabbits" }
See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852
Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.
Update
Ever since Spring 4.x, you usually won't use @ResponseBody
on method level, but rather @RestController
on class level, with the same effect.
Here is a quote from the official Spring MVC documentation:
@RestController
is a composed annotation that is itself meta-annotated with@Controller
and@ResponseBody
to indicate a controller whose every method inherits the type-level@ResponseBody
annotation and, therefore, writes directly to the response body versus view resolution and rendering with an HTML template.
@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request.
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
@ResponseBody annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public @ResponseBody String helloWorld() {
return "Hello World";
}
Alternatively, we can use @RestController annotation in place of @Controller
주석입니다.이 기능을 사용하면 이 기능을 사용할 필요가 없어집니다.@ResponseBody
.
Java 컨트롤러의 메서드의 예를 다음에 나타냅니다.
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public HttpStatus something(@RequestBody MyModel myModel)
{
return HttpStatus.OK;
}
@RequestBody 주석을 사용하면 특정 콜을 처리하기 위해 시스템에서 작성한 모델에 값을 매핑할 수 있습니다.@ResponseBody를 사용하면 요청이 생성된 장소로 어떤 것이든 다시 보낼 수 있습니다.커스텀 파서 등을 작성하지 않아도, 어느 쪽도 간단하게 매핑 할 수 있습니다.
package com.programmingfree.springshop.controller;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.programmingfree.springshop.dao.UserShop;
import com.programmingfree.springshop.domain.User;
@RestController
@RequestMapping("/shop/user")
public class SpringShopController {
UserShop userShop=new UserShop();
@RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(@PathVariable int id) {
User user=userShop.getUserById(id);
return user;
}
@RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userShop.getAllUsers();
return users;
}
}
위의 예에서는 모든 사용자 및 특정 ID 세부 정보가 표시됩니다.ID와 이름을 모두 사용하고 싶습니다.
1) localhost: 8093/plejson/shop/user <--- 이 링크는 모든 사용자 세부사항을 표시합니다.
2) localhost: 8093/plejson/shop/user/11 <---링크 수단으로 11을 사용하면 특정 사용자 11의 상세 내용이 표시됩니다.
이제 아이디와 이름을 모두 사용하고 싶다.
localhost: 8093/plejson/shop/user/11/raju <--------------------------------------------------------------------------------------------------------------------
언급URL : https://stackoverflow.com/questions/11291933/requestbody-and-responsebody-annotations-in-spring
'source' 카테고리의 다른 글
Java의 HashMap에서 키 가져오기 (0) | 2022.08.28 |
---|---|
VueJ 루트에서 완전한 URL(원점 포함)을 얻을 수 있습니까? (0) | 2022.08.28 |
vuejs 재귀적 단일 파일 구성 요소 (0) | 2022.08.28 |
파이어베이스에서 데이터 로드가 완료될 때까지 대기(vue)/'대기'가 작동하지 않음 (0) | 2022.08.28 |
int main()과 int main(void)의 차이는 무엇입니까? (0) | 2022.08.28 |