天天看點

spring mvc設定應答體的content type

spring mvc中如何設定傳回類型呢?

我們知道response 的content type主要有:

text/html

text/plain

application/json;charset=utf-8

application/octet-stream

先舉一個例子,spring mvc中可以通過如下方式傳回json字元串:

spring mvc設定應答體的content type

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

        } catch (ioexception e) {  

        }  

        return content;  

    }  

 雖然通路時傳回的确實是json字元串,但是response 的content type是"

"這不是我們期望的,我們期望的response content type是"application/json"或者"application/json;charset=utf-8",那麼如何實作呢?

通過注解@requestmapping 中的produces

用法如下:

spring mvc設定應答體的content type

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

 spring mvc官方文檔:

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:

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

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.