Spring 开发Springboot

SpringBoot 解决 application/octet-

2019-05-13  本文已影响22人  殷天文

前端为了兼容IE8和跨域做了很多操作(我也不懂),之后发现了一个问题,IE8下所有的ajax请求都是 application/octet-stream,这造成后端Controller中参数为@RequestBody XXBean data的方法全部报错 application/octet-stream not supported

版本

SpringBoot 2.1.3.RELEASE

思路

image.png image.png image.png

解决

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new CustomHttpMessageConverter());
    }

    private class CustomHttpMessageConverter extends AbstractJackson2HttpMessageConverter {
        @Nullable
        private String jsonPrefix;


        public CustomHttpMessageConverter() {
            this(Jackson2ObjectMapperBuilder.json().build());
        }

        public CustomHttpMessageConverter(ObjectMapper objectMapper) {
            super(objectMapper,
                    MediaType.APPLICATION_JSON,
                    new MediaType("application", "*+json"),
                    MediaType.APPLICATION_OCTET_STREAM);
        }


        /**
         * Specify a custom prefix to use for this view's JSON output.
         * Default is none.
         *
         * @see #setPrefixJson
         */
        public void setJsonPrefix(String jsonPrefix) {
            this.jsonPrefix = jsonPrefix;
        }

        /**
         * Indicate whether the JSON output by this view should be prefixed with ")]}', ". Default is false.
         * <p>Prefixing the JSON string in this manner is used to help prevent JSON Hijacking.
         * The prefix renders the string syntactically invalid as a script so that it cannot be hijacked.
         * This prefix should be stripped before parsing the string as JSON.
         *
         * @see #setJsonPrefix
         */
        public void setPrefixJson(boolean prefixJson) {
            this.jsonPrefix = (prefixJson ? ")]}', " : null);
        }


        @Override
        protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
            if (this.jsonPrefix != null) {
                generator.writeRaw(this.jsonPrefix);
            }
        }

    }

}

CustomHttpMessageConverter 代码和 MappingJackson2HttpMessageConverter 一致,只不过在构造方法中添加了 MediaType.APPLICATION_OCTET_STREAM

备注

上一篇 下一篇

猜你喜欢

热点阅读