1. 程式人生 > >關於ResponseBody註解

關於ResponseBody註解

@ResponseBody註解時: 根據Request物件header部分的Accept屬性,逐一按accept中的型別,去遍歷找到能處理的HttpMessageConverter


private void writeWithMessageConverters(Object returnValue,
                HttpInputMessage inputMessage, HttpOutputMessage outputMessage)
                throws IOException, HttpMediaTypeNotAcceptableException {
            List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
            if (acceptedMediaTypes.isEmpty()) {
                acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
            }
            MediaType.sortByQualityValue(acceptedMediaTypes);
            Class<?> returnValueType = returnValue.getClass();
            List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
            if (getMessageConverters() != null) {
                for (MediaType acceptedMediaType : acceptedMediaTypes) {
                    for (HttpMessageConverter messageConverter : getMessageConverters()) {
                        if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
                            messageConverter.write(returnValue, acceptedMediaType, outputMessage);
                            if (logger.isDebugEnabled()) {
                                MediaType contentType = outputMessage.getHeaders().getContentType();
                                if (contentType == null) {
                                    contentType = acceptedMediaType;
                                }
                                logger.debug("Written [" + returnValue + "] as \"" + contentType +
                                        "\" using [" + messageConverter + "]");
                            }
                            this.responseArgumentUsed = true;
                            return;
                        }
                    }
                }
                for (HttpMessageConverter messageConverter : messageConverters) {
                    allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
                }
            }
            throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
        }


如果 @ResquestMapping中指明瞭produces={"application/json"}那麼ResponseBody會自動加上Content-Type為application/json

如果@ResquestMapping中未指明produces型別,則ResponseBody會根據request中accept的值來作為Content-Type


如果不寫@ResponseBody而且返回值是String型別的話,那麼SpringMVC會把這個返回值當做View頁面去查詢,出現404錯誤


為了避免出現亂碼,建議指定生產編碼produces = {"application/json;charset=UTF-8"})