SpringMVC过程中@RequestBody接收Json的问题 总是报415

时间:2022-04-23
本文章向大家介绍SpringMVC过程中@RequestBody接收Json的问题 总是报415,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在SpringMVC中用@RequestBody接收Json的问题,总是报415,经过一翻查找

前台js的post:

var postdata = '{"title":"这是一个标题","describe":"这是一个描述"}';
            $.ajax({
                type : 'POST',
                contentType : 'application/json',
                url : '/home/requestbodybind',
                processData : false,
                dataType : 'json',
                data : postdata,
                success : function(data) {
                    alert('title : '+data.title+'ndescribe : '+data.describe);
                },
                error : function() {
                    alert('error...');
                }
            });

该有的都有

后台:

 @RequestMapping(value = "modelautobind", method = RequestMethod.POST)
    public String modelAutoBind(HttpServletRequest request, @ModelAttribute("accountmodel") NewsModel newsModel, @ModelAttribute("sessionaccountmodel") NewsModel newsModel1) {
        newsModel.setTitle("视图");
        newsModel1.setTitle("session视图");
        //model.addAttribute("accountmodel", newsModel);
        return "modelautobind";//视图名字
    }

网上说需要加入 consumes = "application/json",加了 还是一样报错,后面去掉后也没影响

springmvc的配置文件中有:<mvc:annotation-driven />  

后来有查到对json的解析需要引入

     <dependency>  
            <groupId>com.fasterxml.jackson.core</groupId>  
            <artifactId>jackson-databind</artifactId>  
            <version>2.5.3</version>  
        </dependency>  

在springmvc配置中用得到

            <bean 
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 
                <property name="objectMapper"> 
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper"> 
                        <property name="dateFormat"> 
                            <bean class="java.text.SimpleDateFormat"> 
                                <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" /> 
                            </bean> 
                        </property> 
                    </bean> 
                </property> 
            </bean> 

加上重新跑,这时通过

以上就是整个解决过程。