【问题标题】:Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity多个场景@RequestMapping 与 Accept 或 ResponseEntity 一起生成 JSON/XML
【发布时间】:2023-03-07 21:06:01
【问题描述】:

我正在使用 Spring 4.0.7

关于 Spring MVC,出于研究目的,我有以下几点:

@RequestMapping(value="/getjsonperson", 
                method=RequestMethod.GET, 
                produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Person getJSONPerson(){
    logger.info("getJSONPerson - getjsonperson");
    return PersonFactory.createPerson();
}

@RequestMapping(value="/getperson.json", method=RequestMethod.GET)
public @ResponseBody Person getPersonJSON(){
    logger.info("getPerson - getpersonJSON");
    return PersonFactory.createPerson();
}

每个都可以正常工作,观察 JSON,有和没有扩展:

  • /getjsonperson
  • /getperson.json

XML 也一样

@RequestMapping(value="/getxmlperson",
                method=RequestMethod.GET,
                produces=MediaType.APPLICATION_XML_VALUE
                )
public @ResponseBody Person getXMLPerson(){
    logger.info("getXMLPerson - getxmlperson");
    return PersonFactory.createPerson();
}

@RequestMapping(value="/getperson.xml", method=RequestMethod.GET)
@ResponseBody
public Person getPersonXML(){
    logger.info("getPerson - getpersonXML");
    return PersonFactory.createPerson();
}

每个都可以正常工作,观察 XML,有和没有扩展:

  • /getxmlperson
  • /getperson.xml

现在关于 Restful 我有以下几点:

@RequestMapping(value="/person/{id}/", 
                method=RequestMethod.GET,
                produces={MediaType.APPLICATION_JSON_VALUE, 
                          MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<Person> getPersonCustomizedRestrict(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id);
    return new ResponseEntity<>(person, HttpStatus.FOUND);//302     
}

观察MediaType,它是混合的,用于 JSON 和 XML

通过 RestTemplate 我可以指定 Accept 值

    if(type.equals("JSON")){
        logger.info("JSON");
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    }
    else if(type.equals("XML")){
        logger.info("XML");
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
    }
    ….

    ResponseEntity<Person> response =
                restTemplate.exchange("http://localhost:8080/spring-utility/person/{id}/customizedrestrict",
                                      HttpMethod.GET,
                                      new HttpEntity<Person>(headers),  
                                      Person.class,
                                       id
                                     ); 

到这里为止,因此我可以使用一个 URL/URI 来获取一些 XML 或 JSON 格式的数据。效果很好

我的问题是 Spring MVC ......请考虑

@RequestMapping(value="/{id}/person", 
                method=RequestMethod.GET,
                produces={MediaType.APPLICATION_JSON_VALUE,  
                          MediaType.APPLICATION_XML_VALUE})
public @ResponseBody Person getPerson(@PathVariable Integer id){
    return personMapRepository.findPerson(id);
}

我可以通过以下方式调用或激活该处理程序方法 (@RequestMapping):

  1. jQuery 与 Ajax 一起工作,我能够指示 Accept 值(例如 JSON)
  2. Poster,通过Headers按钮,我可以设置Accept

问题一:

但是对于一个公共链接?如何设置Accept 值?有可能吗?

我想以其他方式解决这个问题。

  • http://localhost:8080/spring-utility/person/getpersonformat?format=json
  • http://localhost:8080/spring-utility/person/getpersonformat?format=xml

观察:

  • ?format

因此

@RequestMapping(value="/getpersonformat", 
                method=RequestMethod.GET,
                produces={MediaType.APPLICATION_JSON_VALUE,  
                          MediaType.APPLICATION_XML_VALUE})
public @ResponseBody Person getPerson(@RequestParam String format){
    return personMapRepository.findPerson(id);
}

问题二:

上面显示的方法必须添加什么代码来自定义返回类型格式? 我的意思是,JSON 或 XML,有可能吗?

我想到了以下几点:

@RequestMapping(value="/getpersonformataltern",
        method=RequestMethod.GET
        produces={MediaType.APPLICATION_JSON_VALUE, 
                  MediaType.APPLICATION_XML_VALUE}
        )
public ResponseEntity<Person> getPersonFormat(@RequestParam String format){
    logger.info("getPersonFormat - format: {}", format);
    HttpHeaders httpHeaders = new HttpHeaders();
    if(format.equals("json")){
        logger.info("Ok JSON");
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    }
    else{
        logger.info("Ok XML");
        httpHeaders.setContentType(MediaType.APPLICATION_XML);
    }
    return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);
}

但是:

如果我执行 URL:

  • http://localhost:8080/spring-utility/person/getpersonformataltern?format=json

我明白了

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
    <id>1</id>
    <firstName>Manuel</firstName>
    <lastName>Jordan</lastName>
…
</person>

在 XML 中是的!

注意:我可以确认控制台打印Ok JSON

如果我执行 URL:

  • http://localhost:8080/spring-utility/person/getpersonformataltern?format=xml

我明白了

This XML file does not appear to have any style information associated with it. 
The document tree is shown below.

<person>
    <id>1</id>
    <firstName>Manuel</firstName>
    <lastName>Jordan</lastName> 
    …
</person>

问题三

必须为上面显示的方法添加什么代码来修复 JSON 输出? 我不知道有什么问题或遗漏..

共有三个问题。

谢谢

阿尔法

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    Map<String,MediaType> mediaTypes = new LinkedHashMap<>();
    mediaTypes.put("json", MediaType.APPLICATION_JSON);
    mediaTypes.put("xml", MediaType.APPLICATION_XML);
    configurer.mediaTypes(mediaTypes);
    configurer.defaultContentType(MediaType.TEXT_HTML);
}

【问题讨论】:

  • 查看内容协商。
  • 参见Alpha 部分。它有效,记住我也在 URL 中使用 .json 和 .xml。
  • 如果你想使用 URL,你不能设置内容类型,你只能在控制调用的情况下这样做(如在 JavaScript 中)。您可以做的一件事是将服务器上的默认内容类型设置为 JSON(而不是现在的 HTML)。无法控制内容类型是合乎逻辑的,因为来自 HTML 的链接应该生成 HTML。
  • @M.Deninum 哦,我明白了,遗憾的是这是不可能的。感谢您的回复
  • 你总是可以使用 curl 来测试你想要的任何一种格式的响应。对于 JSON,使用 curl -H "Accept: application/json" ,对于 XML,使用 curl -H "Accept: application/xml"

标签: spring rest spring-mvc spring-3 spring-4


【解决方案1】:

我更喜欢对以参数为中心的内容类型使用 params 过滤器。我相信它应该与produces属性结合使用。

@GetMapping(value="/person/{id}/", 
            params="format=json",
            produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id);
    return ResponseEntity.ok(person);
} 
@GetMapping(value="/person/{id}/", 
            params="format=xml",
            produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
    return GetPerson(id); // delegate
}

【讨论】:

  • 如果所有rest控制器之间的所有REST URI都使用了format参数,那么其中的代码会增加很多倍
【解决方案2】:

您所有的问题都是您将内容类型协商与参数传递混合在一起。它们是不同层次的东西。更具体地说,对于您的问题 2,您使用要返回的媒体类型构建了响应标头。实际的内容协商基于请求标头中的接受媒体类型,而不是响应标头。在执行到达方法getPersonFormat的实现时,我不确定内容协商是否已经完成。取决于实施。如果没有,并且您想让它工作,您可以用您想要返回的内容覆盖请求标头接受类型。

return new ResponseEntity(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

【讨论】:

    【解决方案3】:

    使用 Accept header 很容易从 REST 服务中获取 json 或 xml 格式。

    这是我的控制器,看看生产部分。

    @RequestMapping(value = "properties", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = RequestMethod.GET)
        public UIProperty getProperties() {
            return uiProperty;
        }
    

    为了使用 REST 服务,我们可以使用下面的代码,其中 header 可以是 MediaType.APPLICATION_JSON_VALUE 或 MediaType.APPLICATION_XML_VALUE

    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", header);
    
    HttpEntity entity = new HttpEntity(headers);
    
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/properties", HttpMethod.GET, entity,String.class);
    return response.getBody();
    

    编辑 01:

    为了使用application/xml,添加这个依赖

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>
    

    【讨论】:

    • 在适当的时候,让我测试一下您的解决方案。现在我又在服务器端了。谢谢
    • 节省我的时间!忘记在 pom 中添加jackson-dataformat-xml
    • 第一个产生参数定义默认格式(对于没有接受头的请求),例如如果客户端未使用accept 标头指定格式,则使用produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE } 端点将发送XML
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2018-02-14
    相关资源
    最近更新 更多