Jackson converter and Javax Validation (annotation) not working together

不羁的心 提交于 2019-12-24 10:38:49

问题


If I use the following configuration then jackson converter works (mvc declaration is last)

<!-- Configure to plugin JSON as request and response in method handler -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter"/>
        </list>
    </property>
</bean>

<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter"      class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
<context:component-scan base-package="com.base" />
<mvc:annotation-driven />

If I use this configuration in dispatcher.xml then validation works but conversion does not. (mvc declaration first)

<context:component-scan base-package="com.base" />

<mvc:annotation-driven />

<!-- Configure to plugin JSON as request and response in method handler -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter"/>
        </list>
    </property>
</bean>

<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>

Any help greatly appreciated. Spring version 4.0.6


回答1:


I chose the part where validation is working and added this in the code base.

@RequestMapping(value = "url", method = RequestMethod.GET)
protected void getLocationAsJson(@PathVariable("id")   Integer id,
 @RequestParam("cid") Integer cid, HttpServletResponse response) {
    MappingJacksonHttpMessageConverter jsonConverter = 
            new MappingJacksonHttpMessageConverter();
    Location loc= new Location(id);
    MediaType jsonMimeType = MediaType.APPLICATION_JSON;
    if (jsonConverter.canWrite(requestedLocation.getClass(), jsonMimeType)) {
    try {
        jsonConverter.write(requestedLocation, jsonMimeType,
                               new ServletServerHttpResponse(response));
        } catch (IOException m_Ioe) {
            // TODO: announce this exception somehow
        } catch (HttpMessageNotWritableException p_Nwe) {
            // TODO: announce this exception somehow
        }
    }
}

Now the validation works as well as JSON returning. The method is not returning anything.




回答2:


RequestMappingHandlerAdapter's xml configuration is bit complicated. The problem with this configuration is, it removes spring default configuration for converters. It is better to use coding version of this configuration. Spring default configuration will be intact this way. Here is sample configurations.

Suggested solution, posted on numerous blogs. But not working in my case.

https://dzone.com/articles/customizing http://www.java-allandsundry.com/2014/09/customizing-httpmessageconverters-with.html

@Configuration
public class MessageConvertorConfiguration extends WebMvcConfigurationSupport {
    @Bean
    public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        Custom360DateFormat dateFormat = new Custom360DateFormat();
        dateFormat.setDateFormat(new SimpleDateFormat("MM/dd/yyyy"));
        dateFormat.setDateTimeFormat(new SimpleDateFormat("MM/dd/yyyy hh:mm a"));

        objectMapper.setDateFormat(dateFormat);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jsonConverter.setObjectMapper(objectMapper);
        return jsonConverter;
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(customJackson2HttpMessageConverter());
        super.addDefaultHttpMessageConverters(converters);
    }
}

Working Solution

@Configuration
public class MessageConvertorConfiguration  {

    private MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        Custom360DateFormat dateFormat = new Custom360DateFormat();
        dateFormat.setDateFormat(new SimpleDateFormat("MM/dd/yyyy"));
        dateFormat.setDateTimeFormat(new SimpleDateFormat("MM/dd/yyyy hh:mm a"));

        objectMapper.setDateFormat(dateFormat);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jsonConverter.setObjectMapper(objectMapper);
        return jsonConverter;
    }

   @Autowired
public void updateJacksonConvertor(RequestMappingHandlerAdapter handlerAdapter) {

    //remove default jakson convertor
    Iterator<HttpMessageConverter<?>> convertorsIterator = handlerAdapter.getMessageConverters().iterator();
    while (convertorsIterator.hasNext()) {
        HttpMessageConverter converter = convertorsIterator.next();
        if(converter instanceof AbstractJackson2HttpMessageConverter) {
            convertorsIterator.remove();
        }
    }

    handlerAdapter.getMessageConverters().add(customJackson2HttpMessageConverter());
}

}


来源:https://stackoverflow.com/questions/26289981/jackson-converter-and-javax-validation-annotation-not-working-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!