简体   繁体   English

使用Spring MVC在REST HTTP GET请求中传递JSON对象

[英]Passing JSON objects in a REST HTTP GET request using Spring MVC

According to this REST model and to what I think is a consensus on REST: every REST retrieval should be performed as a HTTP GET request. 根据这个REST模型以及我认为对REST的共识:每个REST 检索都应该作为HTTP GET请求执行。 The problem now is how to treat complex JSON objects as parameters in GET requests with Spring MVC. 现在的问题是如何将复杂的JSON对象作为Spring MVC的GET请求中的参数处理。 There is also another consensus I found saying "use POST for retrievals!" 还有另一个共识,我发现说“使用POST进行检索!” just because "the big companies do this!", but I have been asked to try to stick to the "REST level 2 rules". 仅仅因为“大公司这样做!”,但我被要求尝试坚持“REST级别2规则”。

First question: am I trying to do something that make sense? 第一个问题:我想做一些有意义的事吗?

I want to send via GET requests arrays / lists / sets of JSON objects, in Java with Spring MVC. 我想通过GET请求发送JSON对象的数组/列表/集合,在Java中使用Spring MVC。 I can not figure out what's wrong with my attempts, I have tried to add/remove double quotes, played around with the URL parameters, but I can not achieve this goal. 我无法弄清楚我的尝试有什么问题,我试图添加/删除双引号,使用URL参数,但我无法实现这一目标。

What's wrong with the following code? 以下代码有什么问题? The code snippet is coming from a MVC controller. 代码片段来自MVC控制器。

@RequestMapping(
        value = "/parseJsonDataStructures",
        params = {
                "language",
                "jsonBeanObject"

        }, method = RequestMethod.GET, headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public HttpEntity<ParsedRequestOutputObject> parseJsonDataStructures(

        @RequestParam String language,
        @RequestParam CustomJsonBeanObject[] customJsonBeanObjects){

    try {
        ParsedRequestOutputObject responseFullData = customJsonBeanObjectService.parseJsonDataStructures(customJsonBeanObjects, language);

        return new ResponseEntity<>(responseFullData, HttpStatus.OK);
    } catch (Exception e) {
        // TODO
    }
}

I've tried multiple ways to build the URL request (always getting HTTP code 400 Bad Request), this is an example: 我已经尝试了多种方法来构建URL请求(总是得到HTTP代码400 Bad Request),这是一个例子:

http://[...]/parseJsonDataStructures?language=en&jsonBeanObject={"doubleObject":10, "enumObject":"enumContent", "stringObject":"stringContent"}

The JSON object variables ar of type: 类型的JSON对象变量ar:

  • Double (not the primitive) 双(不是原始的)
  • enum 枚举
  • String

I am assuming I can pass multiple jsonBeanObject parameters one after the other. 我假设我可以一个接一个地传递多个jsonBeanObject参数。

The jsonBeanObject Java bean is: jsonBeanObject Java bean是:

public class CustomJsonBeanObject {

    private Double doubleObject;
    private CustomEnum enumObject;
    private String stringObject;

    /**
     * Factory method with validated input.
     *
     * @param doubleObject
     * @param enumObject
     * @param stringObject
     * @return
     */
    public static CustomJsonBeanObject getNewValidatedInstance(Double doubleObject, CustomEnum enumObject, String stringObject) {
        return new CustomJsonBeanObject
                (
                        doubleObject ,
                        enumObject   ,
                        stringObject
                );
    }

    private CustomJsonBeanObject(Double doubleObject, CustomEnum enumObject, String stringObject) {
        this.doubleObject = doubleObject;
        this.enumObject = enumObject;
        this.stringObject = stringObject;
    }


    public CustomJsonBeanObject() {}

    // getter setter stuff

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

First create a request bean which should encapsulate the parameters you expect as part of request. 首先创建一个请求bean,它应该封装您期望作为请求的一部分的参数。 Will call it as SomeRequest 将其称为SomeRequest

Second in the controller use @RequestBody instead of @RequestParam 控制器中的第二个使用@RequestBody而不是@RequestParam

@ResponseBody public HttpEntity<ParsedRequestOutputObject> parseJsonDataStructures(@RequestBody SomeRequest someRequest) { ... }

Third use RestTemplate as client to invoke your REST services. 第三,使用RestTemplate作为客户端来调用REST服务。 Sample code below - 示例代码如下 -

SomeRequest someRequest = new SomeRequest();
// set the properties on someRequest
Map<String, String> userService = new HashMap<String, String>();
RestTemplate rest = new RestTemplate();
String url = endPoint + "/parseJsonDataStructures";
ResponseEntity<SomeResponse> response = rest.getForEntity(url, someRequest,
      SomeResponse.class, userService);
SomeResponse resp = response.getBody();

Your statement about only using GET or POST is for REST completely incorrect. 您关于仅使用GET或POST的声明对于REST完全不正确。 The HTTP method used depends on the action you are performing. 使用的HTTP方法取决于您正在执行的操作。 For retrieval, you are supposed to use a GET, for add/create a POST, for remove/delete a DELETE, and for replace a PUT. 对于检索,您应该使用GET,添加/创建POST,删除/删除DELETE,以及替换PUT。 Also, to be "true" REST you should only change state through self-documented actions provided by the server response (read up on HATEOAS ). 此外,要成为“真正的”REST,您应该只通过服务器响应提供的自行记录操作来更改状态(在HATEOAS阅读 )。 Most people don't do the latter. 大多数人不做后者。

As an aside, I tried searching for "REST level 2" and also got nothing by sites about beds and Dungeons'and'Dragons. 顺便说一句,我试图搜索“REST级别2”,并且没有任何网站关于床和龙与地下城的任何内容。 I have personally never heard of it, so it is apparently so new that there are not a lot of sites talking about it or it may be called something else. 我个人从来没有听说过它,所以它显然是如此新鲜,以至于没有很多网站在谈论它,或者它可能被称为别的东西。

To your point about how to send a JSON object, Spring MVC can handle that out-of-the-box. 关于如何发送JSON对象,Spring MVC可以处理开箱即用的问题。 You can read up on it here , which uses the @RequestBody to pull in the entire HTTP request body then parses it using your JSON processor of choice. 你可以在这里阅读它,它使用@RequestBody引入整个HTTP请求体,然后使用你选择的JSON处理器解析它。 There are plenty of code samples there describing how to handle lists and such. 那里有很多代码示例描述了如何处理列表等。

package com.lightaria.json;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class StatusController {

@RequestMapping("/lkg.latest")
public MainStatus stat() throws IOException{
    byte[] jsonData = Files.readAllBytes(Paths.get("/home/admin/StatusPage/Downloads/JSON/lkg-latest.json"));
    ObjectMapper objectMapper =new ObjectMapper();
    MainStatus stat1 = objectMapper.readValue(jsonData, MainStatus.class);
    System.out.println("Status\n"+stat1);
    return stat1;
}
}

I have used the above method to parse a JSON file and store it as JSON object. 我使用上面的方法来解析JSON文件并将其存储为JSON对象。 One can easily replace the path by a URL. 可以通过URL轻松替换路径。 Hope it helps. 希望能帮助到你。

Don't forget to make a application.properties file consisting port and various other configs. 不要忘记创建一个包含端口和各种其他配置的application.properties文件。 for ex - (to run the RESTful application on port 8090, the application.properties file should have server.port=8090 . 对于ex - (要在端口8090上运行RESTful应用程序,application.properties文件应该有server.port = 8090

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

相关问题 使用Spring Mvc的REST请求上的HTTP 400错误请求 - HTTP 400 Bad Request on REST request using Spring Mvc 批量分配不安全的活页夹配置 Rest 框架,JSON http 请求:我没有使用 Spring MVC - mass assignment insecure binder configuration Rest framework , JSON http request :I am not using Spring MVC 使用Spring MVC将对象数组传递给控制器 - Passing Array of Objects to Controller using Spring MVC 处理从REST Spring MVC方法返回的JSON时的HTTP GET问题 - HTTP GET issue when processing JSON returned from REST Spring MVC method 使用REST模板和JSON响应格式在Spring MVC上返回的Http Status 500 - Http Status 500 returned on Spring MVC Using REST Templates and JSON Response Format 在Spring MVC中使用HTTP请求参数 - using http request parameters in spring mvc Spring MVC在单个HTTP请求中处理多个REST命令 - Spring MVC handle multiple REST commands in a single HTTP request 在春天将带有嵌套对象列表的JSON传递给rest控制器时出错 - Error with passing this JSON with nested list of objects to a rest controller in spring 如何使用自定义注释从Spring MVC中的HTTP请求中获取请求标头值? - How to get request header value from http request in spring mvc using custom annotaion? Spring MVC中REST响应对象的部分JSON序列化 - Partial JSON serialization of REST response objects in Spring MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM