Java 如何在spring MVC中将@RequestParam绑定到对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36003330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:21:43  来源:igfitidea点击:

How to bind @RequestParam to object in spring MVC?

javajsonajaxspringspring-mvc

提问by user3029929

I want to make a POST request through AJAX, and I also want to bind the whole class object to the request, and I want to receive that request with @requestParamannotation. I know it can be done with @requestBodyannotation, but I am curious to know: can we do it with @requestParamannotation?

我想通过 AJAX 发出 POST 请求,并且我还想将整个类对象绑定到该请求,并且我想通过@requestParam注释接收该请求。我知道它可以通过@requestBody注释来完成,但我很想知道:我们可以用@requestParam注释来完成吗?

An Ajax code:

一个 Ajax 代码:

var restDTO{
    id: 3,
    name: "hello"
}

 $.ajax({
          url: url, 
          type: 'POST',
          dataType: 'json',
          contentType: 'application/json',
          mimeType: 'application/json',
          data: JSON.stringify({RestDTO : restDTO}),          
          success: function(data) 
    {
    }

I do have RestDTO

我有 RestDTO

Class RestDTO 
{

    int id;
    String name;

    //getter and setter

}

In controller

在控制器中

public String content(@RequestParam RestDTO restDTO){...}

What should I do the make this code run?

我该怎么做才能运行此代码?

What should I change in sending data from ajax?

从ajax发送数据我应该改变什么?

Do I need to change on server to receive an RestDto object with @requestParamannotation?

我是否需要在服务器上进行更改以接收带有@requestParam注释的 RestDto 对象?

回答by Master Slave

If you're sending your data as classic request params, you can bind to object by simply omitting the @RequestParam, so

如果您将数据作为经典请求参数发送,则可以通过简单地省略 来绑定到对象@RequestParam,因此

public String content(RestDTO restDTO){...}

If you're sending json, you have to use @RequestBody.

如果您要发送json,则必须使用@RequestBody.

If whysoever you're insisting on the @RequestParam, note that you can bind multiple values against a map, so

如果您坚持使用@RequestParam,请注意您可以针对地图绑定多个值,因此

public String content(@RequestParam Map<String, String> restDTO){...}

From the @RequestParamdoc

@RequestParam文档

If the method parameter is Map or MultiValueMap and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.

如果方法参数是 Map 或 MultiValueMap 并且未指定参数名称,则使用所有请求参数名称和值填充 map 参数。

回答by Ken Bekov

You can't, because @RequestParamjust indicates, that onemethod's parameter should be bound to a oneweb request's parameter. It can't do mapping to objects. For use @RequestParamyou should change ajax request:

你不能,因为@RequestParam只是表明,一个方法的参数应该绑定到一个web 请求的参数。它不能映射到对象。要使用,@RequestParam您应该更改 ajax 请求:

var restDTO{
   id: 3,
   name: "hello"
}

 $.ajax({
          url: url, 
          type: 'POST',
          data: restDTO,          
          success: function(data){
             ....
          }
});

JQuery will send request as application/x-www-form-urlencodedand will process data to parameters automatically. You controller's method should look like following:

JQuery 将发送请求application/x-www-form-urlencoded并自动处理数据到参数。您的控制器方法应如下所示:

@RequestMapping("/url")
public String content(@RequestParam Long id, @RequestParam String name){...}

For automatically map parameters to object you can use @ModelAttributeannotation:

要自动将参数映射到对象,您可以使用@ModelAttribute注释:

@RequestMapping("/url")
public String content(@ModelAttribute RestDTO restDTO){...}

In this case, names in javascript map should match to names of properties in RestDTO.

在这种情况下,javascript 映射中的名称应与RestDTO.

Generally, @ModelAttributeand @RequestBodycreated for same purposes: for binding data from request to method (whether objects of primitive type).

通常,@ModelAttribute并且@RequestBody出于相同目的而创建:用于将数据从请求绑定到方法(无论是原始类型的对象)。

I consider, that @ModelAttributeis more convenient, when you working with html-forms and plain objects. There is ready to use Spring abilities like modelAttributeand path.

我认为,@ModelAttribute当您使用 html 表单和普通对象时,这更方便。有准备使用 Spring 能力,如modelAttributepath

In its turn, @RequestBodymore flexible, when you need manual control over data. Also, it is more convenient, when you're working with complex objects.

反过来,@RequestBody当您需要手动控制数据时,它会更加灵活。此外,当您处理复杂对象时,它更方便。

Personally me would prefer @RequestBodyand json.

我个人更喜欢@RequestBody和json。

回答by Alexandru Godri

In spring web you have these annotations:

在 spring web 中,您有这些注释:

RequestParam - used for get params (/path?name=)

RequestParam - 用于获取参数 (/path?name=)

PathVariable - used for path params (/path/{name})

PathVariable - 用于路径参数 (/path/{name})

RequestBody - used for post/put/patch etc. body

RequestBody - 用于 post/put/patch 等。 body

RequestHeader - for headers

RequestHeader - 用于标头

So you can't use RequestParam for post params, doesn't matter if json or not

所以你不能将 RequestParam 用于 post params,不管是否 json