zoukankan      html  css  js  c++  java
  • 自定义Jackson2HttpMessageConverter,适应.html后缀url

    Jackson2HttpMessageConverter

    用处

    • SpringMVC中,controller中的方法返回java Bean对象,mvc将此对象转换成字符串
    • 默认支持的mediaType: MediaType.APPLICATION_JSON, new MediaType("application", "*+json"),也就json请求

    为什么改造

    想让url以.html结尾的请求走json请求的逻辑

    现状

    当后端使用如下方法编码时,url以.html为后缀,最终会响应406状态页面
    后端@RestController返回java对象

    @RequestMapping(value = "/data", method = {RequestMethod.POST, RequestMethod.GET})
    public ApiResult data(HttpServletRequest httpServletRequest, String type, String param, Model model) {
        return new ApiResult(2);
    }
    

    目标

    修改后/data.html返回

    { "code" : 2 }
    

    修改方式

    /**
    * 自定义的jackson到httpmessage的转换器
    * Created by cdliujian1 on 2018/1/27.
     */
    public class JMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
    
    /**
     * Construct a new {@link MappingJackson2HttpMessageConverter} using default configuration
     * provided by {@link Jackson2ObjectMapperBuilder}.
     */
    public JMappingJackson2HttpMessageConverter() {
        this(Jackson2ObjectMapperBuilder.json().build());
    }
    
    /**
     * Construct a new {@link MappingJackson2HttpMessageConverter} with a custom {@link ObjectMapper}.
     * You can use {@link Jackson2ObjectMapperBuilder} to build it easily.
     * @see Jackson2ObjectMapperBuilder#json()
     */
    public JMappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
        super(objectMapper);
        List<MediaType> mediaTypes = getSupportedMediaTypes();
        List<MediaType> newMediaTypes = new ArrayList<>();
        newMediaTypes.add(MediaType.TEXT_HTML);
        newMediaTypes.addAll(mediaTypes);
        setSupportedMediaTypes(newMediaTypes);
    }
    
    }
    

    构造函数中,调用setSupportedMediaTypes方法,将MediaType.TEXT_HTML添加到当前HttpMessageConverter支持媒体类型中
    这样当.html后缀结尾的链接到后端时,可以进入到MappingJackson2HttpMessageConverter的处理流程

    MvcConfiguration

    @Configuration
    //@EnableWebMvc
    public class MvcConfiguration extends WebMvcConfigurerAdapter {
    
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
                .indentOutput(true)
                .dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    
        converters.add(new JMappingJackson2HttpMessageConverter(builder.build()));
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.xml().build()));
    }
    }
  • 相关阅读:
    orcal中创建和删除表空间和用户
    tomcat常用的优化和配置
    tomcat中如何禁止和允许主机或地址访问
    velocity生成静态页面代码
    java下载文件
    java上传文件
    数据库行列转换
    JDBC连接数据库详解
    java中插入myslq的datetime类型的
    简单的邮件发送mail.jar
  • 原文地址:https://www.cnblogs.com/windliu/p/8366375.html
Copyright © 2011-2022 走看看