1.配置修改
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:util="http://www.springframework.org/schema/util"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.2.xsd
- http://www.springframework.org/schema/util
- http://www.springframework.org/schema/util/spring-util-4.2.xsd">
- <!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,
- 如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean -->
- <context:component-scan base-package="com.control"/>
- <!-- 使用默认的Servlet来响应静态文件 -->
- <mvc:default-servlet-handler/>
- <!-- 设置配置方案 -->
- <mvc:annotation-driven>
- <!-- 设置不使用默认的消息转换器 -->
- <mvc:message-converters register-defaults="false">
- <!-- 配置Spring的转换器 -->
- <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
- <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
- <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
- <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
- <!-- 配置fastjson中实现HttpMessageConverter接口的转换器 -->
- <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
- <!-- 加入支持的媒体类型:返回contentType -->
- <property name="supportedMediaTypes">
- <list>
- <!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 -->
- <value>text/html;charset=UTF-8</value>
- <value>application/json;charset=UTF-8</value>
- </list>
- </property>
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
- <!-- 视图解析器 -->
- <bean id="viewResolver"
- class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <!-- 前缀 -->
- <property name="prefix">
- <value>/WEB-INF/content/</value>
- </property>
- <!-- 后缀 -->
- <property name="suffix">
- <value>.jsp</value>
- </property>
- </bean>
- </beans>
注:以上的配置文件和和之前的配置文件重点的区别在于,之前使用的是spring中默认的Mapping-Jackson2HttpMessageConverter,这样只需要配置默认的<mvc:annotation-driven/>就可以了。而现在使用了第三方的fastjson处理json数据,则需要另行配置HttpMessageConverter。
2.前端
index.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>测试接收JSON格式的数据</title>
- <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
- <script type="text/javascript" src="js/json2.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- testRequestBody();
- });
- function testRequestBody(){
- $.ajax("${pageContext.request.contextPath}/json/testRequestBody",// 发送请求的URL字符串。
- {
- dataType : "json", // 预期服务器返回的数据类型。
- type : "post", // 请求方式 POST或GET
- contentType:"application/json", // 发送信息至服务器时的内容编码类型
- // 发送到服务器的数据。
- data:JSON.stringify({id : 1, name : "Spring MVC企业应用实战"}),
- async: true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
- // 请求成功后的回调函数。
- success :function(data){
- console.log(data);
- $("#id").html(data.id);
- $("#name").html(data.name);
- $("#author").html(data.author);
- },
- // 请求出错时调用的函数
- error:function(){
- alert("数据发送失败");
- }
- });
- }
- </script>
- </head>
- <body>
- 编号:<span id="id"></span><br>
- 书名:<span id="name"></span><br>
- 作者:<span id="author"></span><br>
- </body>
- </html>
3.后端
Book.Java
- package com.bean;
- import java.io.Serializable;
- public class Book implements Serializable {
- private Integer id;
- private String name;
- private String author;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getAuthor() {
- return author;
- }
- public void setAuthor(String author) {
- this.author = author;
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
- }
- }
BookController.java
- package com.control;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import com.alibaba.fastjson.JSONObject;
- import com.bean.Book;
- @Controller
- @RequestMapping("/json")
- public class BookController {
- private static final Log logger = LogFactory.getLog(BookController.class);
- // @RequestBody根据json数据,转换成对应的Object
- @RequestMapping(value="/testRequestBody")
- public void setJson(@RequestBody Book book,HttpServletResponse response) throws Exception{
- // JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包。
- // 使用JSONObject将book对象转换成json输出
- logger.info(JSONObject.toJSONString(book));
- book.setAuthor("海哥");
- response.setContentType("text/html;charset=UTF-8");
- // 将book对象转换成json写出到客户端
- response.getWriter().println(JSONObject.toJSONString(book));
- }
- }
4.截图