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

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

This question is related to spring rest spring-mvc spring-3 spring-4

The answer is


All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

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


I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.

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

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to rest

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Returning data from Axios API Access Control Origin Header error using Axios in React Web throwing error in Chrome JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value How to send json data in POST request using C# How to enable CORS in ASP.net Core WebAPI RestClientException: Could not extract response. no suitable HttpMessageConverter found REST API - Use the "Accept: application/json" HTTP Header 'Field required a bean of type that could not be found.' error spring restful API using mongodb MultipartException: Current request is not a multipart request

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Examples related to spring-3

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity When use ResponseEntity<T> and @RestController for Spring RESTful applications Understanding Spring @Autowired usage Difference between <context:annotation-config> and <context:component-scan> What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

Examples related to spring-4

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET) How to return JSON data from spring Controller using @ResponseBody Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity When use ResponseEntity<T> and @RestController for Spring RESTful applications