Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

Manuel Jordan

I am working with Spring 4.0.7

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

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

  • /getjsonperson
  • /getperson.json

Same for 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();
}

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     
}

Observe the MediaType, it is mixed, for JSON and XML

Through RestTemplate I can indicate the Accept value

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

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

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

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

  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

Question One:

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

Observe:

  • ?format

Therefore

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

Question Two:

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

I thought in the following:

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

But:

If I execute the URL:

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

I get

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

Yes in XML!

Note: I can confirm the Console prints Ok JSON

If I execute the URL:

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

I get

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>

Question Three

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..

There are three questions.

Thank You

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);
}
Eddú Meléndez

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

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();

Edit 01:

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

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

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

@RequestMapping for multiple pages

分類Dev

Gherkin scenario outlines or multiple scenarios?

分類Dev

Accept multiple styles in Firebug

分類Dev

Update regex expression to consider multiple scenarios

分類Dev

How to show enum value in multiple join scenarios?

分類Dev

@RequestMappingに「headers」属性と「produces」属性を自動的に追加します

分類Dev

Method parameter to accept multiple types

分類Dev

Are weight values required in an Accept Header with multiple values?

分類Dev

Chaining multiple Select2 together

分類Dev

How to bind multiple elements to scroll together?

分類Dev

Padding multiple fields together in python logger

分類Dev

R: arranging multiple plots together using gridExtra

分類Dev

Multiple SQL tables added together without a JOIN

分類Dev

Spring ResponseEntity

分類Dev

debugging cgo in visual studio code produces "multiple definition of" error

分類Dev

Can I create an Eclipse Project that produces multiple executable Jars?

分類Dev

Attempting to label bars in chart, but produces text multiple times

分類Dev

Using multiple bokeh HoverTool instances together with the models API

分類Dev

Three.js - How to group together multiple imported models

分類Dev

How to wait for multiple observable streams to resolve and return them together

分類Dev

Get multiple regex expressions working together to match complex set of strings

分類Dev

How to add multiple lists together, while keeping them as elements in Python?

分類Dev

Multiple field separator in awk (Field separator being together )

分類Dev

How to pass multiple values of type NSString together for a query?

分類Dev

How to lookup multiple items add their corresponding values together and generate a percentage

分類Dev

Spring ResponseEntity <JSONObject> HttpMediaTypeNotAcceptableException

分類Dev

Spring ResponseEntity <JSONObject> HttpMediaTypeNotAcceptableException

分類Dev

コントローラに@RequestMapping(produces = ...)がある場合にのみ、SpringのHandlerInterceptorAdapterが2回呼び出されるのはなぜですか?

分類Dev

using ggplot2 with data.table to produce multiple .pdfs produces all data on each plot

Related 関連記事

  1. 1

    @RequestMapping for multiple pages

  2. 2

    Gherkin scenario outlines or multiple scenarios?

  3. 3

    Accept multiple styles in Firebug

  4. 4

    Update regex expression to consider multiple scenarios

  5. 5

    How to show enum value in multiple join scenarios?

  6. 6

    @RequestMappingに「headers」属性と「produces」属性を自動的に追加します

  7. 7

    Method parameter to accept multiple types

  8. 8

    Are weight values required in an Accept Header with multiple values?

  9. 9

    Chaining multiple Select2 together

  10. 10

    How to bind multiple elements to scroll together?

  11. 11

    Padding multiple fields together in python logger

  12. 12

    R: arranging multiple plots together using gridExtra

  13. 13

    Multiple SQL tables added together without a JOIN

  14. 14

    Spring ResponseEntity

  15. 15

    debugging cgo in visual studio code produces "multiple definition of" error

  16. 16

    Can I create an Eclipse Project that produces multiple executable Jars?

  17. 17

    Attempting to label bars in chart, but produces text multiple times

  18. 18

    Using multiple bokeh HoverTool instances together with the models API

  19. 19

    Three.js - How to group together multiple imported models

  20. 20

    How to wait for multiple observable streams to resolve and return them together

  21. 21

    Get multiple regex expressions working together to match complex set of strings

  22. 22

    How to add multiple lists together, while keeping them as elements in Python?

  23. 23

    Multiple field separator in awk (Field separator being together )

  24. 24

    How to pass multiple values of type NSString together for a query?

  25. 25

    How to lookup multiple items add their corresponding values together and generate a percentage

  26. 26

    Spring ResponseEntity <JSONObject> HttpMediaTypeNotAcceptableException

  27. 27

    Spring ResponseEntity <JSONObject> HttpMediaTypeNotAcceptableException

  28. 28

    コントローラに@RequestMapping(produces = ...)がある場合にのみ、SpringのHandlerInterceptorAdapterが2回呼び出されるのはなぜですか?

  29. 29

    using ggplot2 with data.table to produce multiple .pdfs produces all data on each plot

ホットタグ

アーカイブ