spring 配置使用 @RequestBody 注解

本文介绍如何在Spring MVC框架下配置Jackson进行JSON数据的序列化和反序列化,解决版本冲突问题,并展示了前后端数据交互的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、版本描述
spring 版本 5.0
jackson-annotations-2.9.7
jackson-core-2.9.7
jackson-databind-2.9.7

二、springmvc-config.xml 配置

<mvc:annotation-driven />
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name = "supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="text"/>
<constructor-arg index="1" value="plain"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="*"/>
<constructor-arg index="1" value="*"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="text"/>
<constructor-arg index="1" value="*"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="application"/>
<constructor-arg index="1" value="json"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
</list>
</property>
</bean>

三、clean项目重启 TOMCAT

四、问题
Caused by: java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException
原因:spring 5.0 与 jackson-databind-2.5.5 的版本不匹配,把jackson-databind-2.5.5 解压出来使用 InvalidDefinitionException
在解压后的文件夹中搜索没有 InvalidDefinitionException这个类,但 spring 5.0 要求使用这个类。
解决办法:把  jackson-annotations 、jackson-core 、jackson-databind 都换成 5.9.7 的版本。

 

五、后端 contorller

package org.fkit.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.fkit.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.fkit.domain.Book;

@Controller
public class BookController {
	
	
	@RequestMapping(value="/bookList")
	public void bookList(@RequestBody List<Book> bookList,HttpServletRequest request, HttpServletResponse response
			 ) throws IOException {
		for (Book book : bookList) {
			System.out.println(book.getAuthor());
			System.out.println(book.getName());
			System.out.println(book.getPrice());
		}
		
		
		JSONArray jsonObject = JSONArray.fromObject(bookList);
		 response.setCharacterEncoding("UTF-8");  
	     response.getWriter().println(jsonObject); 
	}
}

六、后端实体类

package org.fkit.domain;

import java.io.Serializable;
import java.util.Date;

public class Book implements Serializable {
	private Integer id;
	private String name;
	private String author;
	private String publication;
	private Date publlicationdate;
	private Double price;
	private String image;
	private String remark;
	
	public Book() {
		super();
	}
	// 有参数构造器
	public Book(Integer id,String name,String author,
			String publication,Date publicationdate,
			Double price,String image,String remark) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
		this.publication = publication;
		this.publlicationdate = publlicationdate;
		this.price = price;
		this.image =  image;
		this.remark = remark;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getId() {
		return id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getAuthor() {
		return author;
	}
	public void setPublication(String publication) {
		this.publication =  publication;
	}
	public String getPublication() {
		return publication;
	}
	public void setPubllicationdate(java.util.Date date) {
		this.publlicationdate = date;
	}
	public Date getPubllicationdate() {
		return publlicationdate;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	public Double getPrice() {
		return price;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public String getImage() {
		return image;
	}
    public void setRemark(String remark) {
    	this.remark = remark;
    }	
    public String getRemark() {
    	return remark;
    }
}

七、前端 JSP页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<script src="/fkbookapp/js/jquery-3.3.1.min.js" type="text/javascript"></script> 
<script type="text/javascript">



  
   var books = [
	   {"author":"李非","name":"spring开发","price":100},
	   {"author":"孔子","name":"论语","price":200},
	   {"author":"李白","name":"李白诗集","price":300}
   ];
   function bookList() {
	   $.ajax({
			      url :"/fkbookapp/bookList.do",
			         dataType : "json",
			            type  : "post",
			            contentType: 'application/json;charset=UTF-8',
			            data:JSON.stringify(books),
			            //data:'{"author":"李非","name":"spring开发","price":100}',
			            //data:{"author":"李非","name":"spring开发","price":100},
			            async : true,
			            success : function(data) {
			               console.log(data);
			               $("#id").html(data.id);
			               $("#name").html(data.name);
			               $("#author").html(data.author)
			            },
			            error:function() {
			               alert("数据发送失败");
			            }
			            });
	  
   }
   
   $(function() {
	   bookList();
   })
</script>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
  <style type="text/css">
     table{border-collapse:collapse;border-spacing:0:border-left:1px solid #888;
     border-top:1px solid #888;background:#efefef;}
     th,td{border-right:1px solid #888;border-bottom:1px solid #888;
     padding:5px15px;}
     th{font-weight:bold;background:#ccc;}
  </style>
</head>
<body>
欢迎访问
<br>
<form  action="setParameter" method="post">
  <table id="t1">
     <tr>
        <th>参数名</th><th>参数值</th><th>编辑参数</th>
     </tr>
      
  </table>
</form>



</body>
</html>

注意:

contentType: 'application/json;charset=UTF-8' 表示使用JSON 格式传输数据到服务端。这里必须指定为 JSON格式。

data:JSON.stringify(books) 表示把 JSON 对象转换为 JSON 格式的字符串传输给服务端,因为网络只能传输字符串,无法传输对象所以要把 JSON 对象转换为字符串。

前端 JSON对象的KEY一定要与后端的实体类的属性一致,并且实体类所有属性都必须有get和set方法,前端传过去的数据才能绑定到后端接受参数的对象。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值