spring mvc sets the content type of the response body

 

 How to set the content type of the response body in spring MVC ?

How to set the return type in spring MVC?

We know that the content types of response are mainly:

text/html

text/plain

application/json;charset=UTF-8

application/octet-stream

Wait

As an example, in spring mvc, json strings can be returned in the following ways:

@ResponseBody  
    @RequestMapping(value = "/upload")  
    public String upload(HttpServletRequest request, HttpServletResponse response,String contentType2)  
            throws IOException {  
        String content = null;  
        Map map = new HashMap();  
        ObjectMapper mapper = new ObjectMapper();  
  
        map.put("fileName", "a.txt");  
        try {  
            content = mapper.writeValueAsString(map);  
            System.out.println(content);  
        } catch (JsonGenerationException e) {  
            e.printStackTrace ();  
        } catch (JsonMappingException e) {  
            e.printStackTrace ();  
        } catch (IOException e) {  
            e.printStackTrace ();  
        }  
          
        return content;  
  
    }

 

 

Although it is true that the json string is returned when accessing, the content type of the response is "

text/html

"This is not what we expect, the response content type we expect is "application/json" or "application/json;charset=UTF-8", so how to achieve it?

Produces by annotating @RequestMapping

The usage is as follows:

 

@RequestMapping(value = "/upload",produces="application/json;charset=UTF-8")  

 

 

 Spring MVC official documentation:

Producible Media Types

You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the producescondition. For example:

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
    // implementation omitted
}

Just like with consumes, producible media type expressions can be negated as in !text/plain to match to all requests other than those with an Accept header value oftext/plain.

Tip
[Tip]

The produces condition is supported on the type and on the method level. Unlike most other conditions, when used at the type level, method-level producible types override rather than extend type-level producible types.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326617310&siteId=291194637