stMapping会与Accept或ResponseEntity

stMapping会与Accept或ResponseEntity

本文介绍了多个场景@RequestMapping会与Accept或ResponseEntity一起生成JSON/XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring 4.0.7

I am working with Spring 4.0.7

关于Spring MVC,出于研究目的,我有以下内容:

About Spring MVC, for research purposes, I have the following:

@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:

Each one works fine, observe both for JSON, with and without extension:

  • /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:

Each one works fine, observe both for XML, with and without extension:

  • /getxmlperson
  • /getperson.xml

现在关于娱乐,我有以下内容:

Now about Restful I have the following:

@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,它是混合的

Observe the MediaType, it is mixed, for JSON and 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格式的一些数据.效果很好

Until here, therefore I am able to use one URL/URI to get some data in either XML or JSON formats. It works fine

我的问题是Spring MVC…考虑一下

My problem is with Spring MVC … just consider

@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):

I can call or activate that handler method (@RequestMapping) through:

  1. 使用Ajax的jQuery,我能够指出Accept值(例如JSON)
  2. 海报,通过Headers按钮,我可以设置Accept
  1. jQuery working with Ajax, I am able to indicate the Accept value (JSON for example)
  2. Poster, through the Headers button, I can set the Accept

问题一:

但是要建立公共链接?如何设置Accept值?有可能吗?

But for a common link? how I can set the Accept value? is possible?

我以其他方式解决了这个问题.

I thought in other way to around this problem.

  • http://localhost:8080/spring-utility/person/getpersonformat?format=json
  • http://localhost:8080/spring-utility/person/getpersonformat?format=xml
  • 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,可以吗?

What code for the method shown above must be added to customize the return type format?I mean, JSON or XML, Is possible?

我想以下:

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

但是:

如果我执行网址:

  • 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

Note: I can confirm the Console prints Ok JSON

如果我执行网址:

  • 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输出?我不知道是哪里错了或丢失了..

What code for the method shown above must be added to fix the JSON output?I don't know what is wrong or is missing..

有三个问题.

谢谢

Alpha

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

推荐答案

使用Accept标头很容易从REST服务中获取json或xml格式.

Using Accept header is really easy to get the format json or xml from the REST service.

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

This is my Controller, take a look produces section.

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

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

In order to consume the REST service we can use the code below where header can be MediaType.APPLICATION_JSON_VALUE or 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,请添加此依赖项

In order to work with application/xml, add this dependency

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

这篇关于多个场景@RequestMapping会与Accept或ResponseEntity一起生成JSON/XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 05:57