Spring MVC--自定义HttpMessageConverter接收JSON格式的数据
替换默认的Jackson,使用fastjson来处理json格式的数据。
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或GETcontentType:"application/json", // 发送信息至服务器时的内容编码类型// 发送到服务器的数据。data:JSON.stringify({id : 1, name : "水滸傳"}),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>
BookController.java
package org.zhangxueliang.controller;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 org.zhangxueliang.domain.Book;import com.alibaba.fastjson.JSONObject;@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));}}
Book.java
package org.zhangxueliang.domain;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;}@Overridepublic String toString() {return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";}}
springmvc-config.xml
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-4.2.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-4.2.xsd"><!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件,如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean --><context:component-scan base-package="org.zhangxueliang.controller"/><!-- 使用默认的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>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"><!-- 定义Spring MVC的前端控制器 --><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/springmvc-config.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><!-- 让Spring MVC的前端控制器拦截所有请求 --><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 编码过滤器 --><filter><filter-name>characterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>characterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>
Spring MVC--自定义HttpMessageConverter接收JSON格式的数据相关推荐
- asp.net MVC控制器中返回JSON格式的数据时提示下载
Asp.net mvc在接收的是JSON格式的数据,但是奇怪的是在IE中提示下载文件,其他浏览器中一切正常,下载后,里面的内容就是在控制器中返回的数据.代码如下: 视图中js代码: $("# ...
- 如何在Django中接收JSON格式的数据
Django做了大量工作简化我们的Web开发工作, 这其中当然也包括接收来自客户端的数据这一普遍需求. 大部分时候,从客户端传入的数据主要是FORM的POST数据,和来自URL的GET数据, 在Dja ...
- Spring MVC 学习总结(九)——Spring MVC实现RESTful与JSON(Spring MVC为前端提供服务)...
Spring MVC 学习总结(九)--Spring MVC实现RESTful与JSON(Spring MVC为前端提供服务) 目录 一.JSON 1.1.概要 1.2.使用ModelAndView ...
- Spring MVC--接收JSON格式的数据
Spring mvc使用开源的Jackson包来处理JSON格式的请求或相应消息. index.jsp <%@ page language="java" contentTyp ...
- Spring MVC--使用Jackson返回JSON格式数据
使用Jackson返回JSON格式数据 index.jsp <%@ page language="java" contentType="text/html; cha ...
- Spring MVC自定义验证注释
在上一教程中,我展示了如何使用注释来验证表单 . 这对于简单的验证非常有用,但是最终,您需要验证一些现成的注释中没有的自定义规则. 例如,如果您需要根据输入的出生日期来验证用户已超过21岁,或者可能需 ...
- Spring MVC,Ajax和JSON第3部分–客户端代码
如果您一直关注有关Spring,Ajax和JSON的简短博客系列,那么您会回想起我到目前为止已经创建了一个Spring MVC Web应用程序,该应用程序显示一个表单,该表单允许用户选择一堆项目并向服 ...
- Spring MVC,Ajax和JSON第2部分–服务器端代码
在上一个博客中,我说过我将谈论Spring,Ajax和JSON,但是没有. 原因是我想使用(很少)可信的购物网站场景来设置场景. 在这种情况下,当用户单击"电子商务"页面链接时,服 ...
- Spring MVC 3.0 返回JSON数据的方法
Spring MVC 3.0 返回JSON数据的方法 1. 直接 PrintWriter 输出 2. 使用 JSP 视图 3. 使用Spring内置的支持 // Spring MVC 配置 <b ...
最新文章
- 构建长期共赢生态圈,英特尔至强平台加速人工智能落地
- 全排列递归实现的讨论
- Unity运行时检测Altas使用情况
- 数据算法竞赛:ICDM 2020 TOP3方案
- BZOJ2647 : [Neerc2011]Journey
- HDU 1003 Maxsum
- thymeleaf 中select下拉回显
- 所有的低谷,都是为了更上一层楼
- 阿里云新征程:通往智能之路
- u盘最大单个文件支持多少g_小身材用处大,金属U盘功能不简单
- pyspark 手写Apriori算法
- Mysql 导出导入
- windows 上面的tensorflow-GPU、cuda、cudnn 安装
- 服务器SN信息,查询服务器sn号
- QA与SQA到底有什么区别和联系?他们的职责和工作内容是什么?QC,QM又是什么?
- 【转载】2021互联网行业术语@20210311
- VSCode 的扩展包C/C++ IntelliSense, debugging, and code browsing的IntelliSense功能无法使用
- 阿里云新优惠活动,幸运券免费领取
- 南宁二中三中高考2021成绩查询,2021广西重点高中名单及排名
- [Flutter]微信分享并从分享链接跳回APP指定页面