简体   繁体   English

Spring中的@RequestBody和@ResponseBody注解

[英]@RequestBody and @ResponseBody annotations in Spring

Can someone explain the @RequestBody and @ResponseBody annotations in Spring 3?有人可以解释一下 Spring 3 中的@RequestBody@ResponseBody注释吗? 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 . 在文档中有一个名为16.3.3.4的完整章节,其中将请求主体与@RequestBody批注进行映射 And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation . 还有一个叫做16.3.3.5的映射,它使用@ResponseBody注释映射响应主体 I suggest you consult those sections. 我建议您查阅这些部分。 Also relevant: @RequestBody javadocs, @ResponseBody javadocs 也相关: @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: 使用像JQuery这样的JavaScript库,您将像这样发布JSON对象:

{ "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). 现在,如果您在类路径中具有Jackson (并且具有<mvc:annotation-driven>设置),Spring会将传入的JSON从帖子正文转换为UserStats对象(因为您添加了@RequestBody批注)并将其序列化返回的对象为JSON(因为您添加了@ResponseBody批注)。 So the Browser / Client would see this JSON result: 因此,浏览器/客户端将看到以下JSON结果:

{ "description" : "Elmer Fudd hates wacky wabbits" }

See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852 有关完整的工作示例,请参见我的先前答案: 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. 注意:RequestBody / ResponseBody当然不限于JSON,两者都可以处理多种格式,包括纯文本和XML,但是JSON可能是最常用的格式。


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. 因为春天4.x版以来,你通常不会使用@ResponseBody在方法层面,而是@RestController上一流水平,具有同样的效果。

Here is a quote from the official Spring MVC documentation : 这是Spring MVC官方文档的引文:

@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. @RestController是一个组合的批注 ,其本身使用@Controller@ResponseBody进行了元注释 ,以指示一个控制器,其每个方法都继承了类型级别的@ResponseBody批注,因此直接将其写入响应主体(与视图分辨率相对)并使用HTML模板。

@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request. @RequestBody :指示方法参数的注释应绑定到HTTP请求的正文。

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). 可以将@ResponseBody批注放置在方法上,并指示应将返回类型直接写到HTTP响应主体(而不是放置在Model中或解释为视图名称)。

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 annotation. 另外,我们可以使用@RestController注释代替@Controller注释。 This will remove the need to using @ResponseBody . 这将消除使用@ResponseBody的需要。

for more details 更多细节

Below is an example of a method in a Java controller. 以下是Java控制器中方法的示例。

@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public HttpStatus something(@RequestBody MyModel myModel) 
{
    return HttpStatus.OK;
}

By using @RequestBody annotation you will get your values mapped with the model you created in your system for handling any specific call. 通过使用@RequestBody批注,您的值将与您在系统中创建的用于处理任何特定调用的模型映射。 While by using @ResponseBody you can send anything back to the place from where the request was generated. 使用@ResponseBody时,您可以将任何内容发送回生成请求的位置。 Both things will be mapped easily without writing any custom parser etc. 无需编写任何自定义解析器等,这两件事都将轻松映射。

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;
 }


}

In the above example they going to display all user and particular id details now I want to use both id and name, 在上面的示例中,他们现在要显示所有用户和特定ID的详细信息,我想同时使用ID和名称,

1) localhost:8093/plejson/shop/user <---this link will display all user details 1)localhost:8093 / plejson / shop / user <-此链接将显示所有用户详细信息
2) localhost:8093/plejson/shop/user/11 <----if i use 11 in link means, it will display particular user 11 details 2)localhost:8093 / plejson / shop / user / 11 <----如果我在链接中使用11,它将显示特定的用户11详细信息

now I want to use both id and name 现在我想同时使用id和name

localhost:8093/plejson/shop/user/11/raju <-----------------like this it means we can use any one in this please help me out..... 本地主机:8093 / plejson / shop / user / 11 / raju <-----------------像这样,这意味着我们可以在其中使用任何一个,请帮帮我.... 。

@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 So instead of marking your class as @Controller use @RestController instead and remove the @requestbody annotation from you class @RestController是一个组合注解,它本身用@Controller@ResponseBody进行元注解,以指示 controller,其每个方法都继承了类型级别的@ResponseBody 注解,因此直接写入响应主体而不是视图解析和渲染HTML 模板因此,不要将 class 标记为@Controller ,而是使用@RestController并从你的 class 中删除 @requestbody 注释

heres an example: @RestController这是一个例子:@RestController

public class MomController {

    @RequestMapping("/sugar") // maped to the url /sugar
    public String addSugar() {
        return "here is your sugar";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM