Spring MVC在数据绑定的过程中,需要对传递数据的格式和类型进行转换,它既可以转换String登类型的数据,也可以转换JSON等其他类型的数据。
JSON(JavaScript Object Notation JS对象标记)是一种轻量级的数据交换格式,与XML一样,JSON也是基于纯文本的数据格式 它有以下两种数据结构
对象结构以{开始 }结束,中间部分由0个或多个以英文,分割的key/value对构成,key和value之间以英文:分割,语法结构如下
{
key1:value1,
key2:value2,
...
}
数组结构以[开始以]结束,中间部分由0个活多个以英文,分割的值的列表组成 语法结构如下
[
value1,
value2.
...
]
为实现浏览器与控制器类之间的JSON数据交互,Spring MVC提供了MappingJackson2HttpMessageConverter实现类默认处理JSON格式请求响应。该实现类利用Jackson开源包读取JSON数据,将Java对象转换为JSON对象和XML文档,同时也可以将JSON对象和XML文档转换为Java对象
在使用注解开发时,需要用到两个重要的JSON格式转换注解
用于将请求体的数据绑定到方法的形参上,该注解应用在方法的形参上
用于直接返回JSON对象 该注解应用在方法上
下面通过一个实例来演示JSON数据交互过程
Webconfig类代码如下
- package config;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRegistration.Dynamic;
- import org.springframework.web.WebApplicationInitializer;
- import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
- import org.springframework.web.servlet.DispatcherServlet;
- public class WebConfig implements WebApplicationInitializer{
- @Override
- public void onStartup(ServletContext arg0) throws ServletException {
- AnnotationConfigWebApplicationContext ctx
- = new AnnotationConfigWebApplicationContext();
- ctx.register(SpringMVCConfig.class);//注册Spring MVC的Java配置类SpringMVCConfig
- ctx.setServletContext(arg0);//和当前ServletContext关联
- /**
- * 注册Spring MVC的DispatcherServlet
- */
- Dynamic servlet = arg0.addServlet("dispatcher", new DispatcherServlet(ctx));
- servlet.addMapping("/");
- servlet.setLoadOnStartup(1);
- }
- }
SpringMVCConfig类代码如下
- package config;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.EnableWebMvc;
- import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
- import org.springframework.web.servlet.view.InternalResourceViewResolver;
- @Configuration
- @EnableWebMvc
- @ComponentScan("controller")
- public class SpringMVCConfig implements WebMvcConfigurer {
- /**
- * 配置视图解析器
- */
- @Bean
- public InternalResourceViewResolver getViewResolver() {
- InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
- viewResolver.setPrefix("/WEB-INF/jsp/");
- viewResolver.setSuffix(".jsp");
- return viewResolver;
- }
- /**
- * 配置静态资源
- */
- @Override
- public void addResourceHandlers(ResourceHandlerRegistry registry) {
- registry.addResourceHandler("/js/**").addResourceLocations("/js/");
- }
- }
首先去官方网站http://jquery.com/download/下载jQuery插件 然后复制到WebContent目录下
创建JSP文件index.jsp 代码如下
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.2.1.min.js"></script>
- <script type="text/javascript">
- function testJson() {
- //获取输入的值pname为id
- var pname = $("#pname").val();
- var password = $("#password").val();
- var page = $("#page").val();
- $.ajax({
- //请求路径
- url : "${pageContext.request.contextPath }/testJson",
- //请求类型
- type : "post",
- //data表示发送的数据
- data : JSON.stringify({pname:pname,password:password,page:page}),
- //定义发送请求的数据格式为JSON字符串
- contentType : "application/json;charset=utf-8",
- //定义回调响应的数据格式为JSON字符串,该属性可以省略
- dataType : "json",
- //成功响应的结果
- success : function(data){
- if(data != null){
- //返回一个Person对象
- //alert("输入的用户名:" + data.pname + ",密码:" + data.password + ",年龄:" + data.page);
- //ArrayList<Person>对象
- /**for(var i = 0; i < data.length; i++){
- alert(data[i].pname);
- }**/
- //返回一个Map<String, Object>对象
- //alert(data.pname);//pname为key
- //返回一个List<Map<String, Object>>对象
- for(var i = 0; i < data.length; i++){
- alert(data[i].pname);
- }
- }
- }
-
- });
- }
- </script>
- </head>
- <body>
- <form action="">
- 用户名:<input type="text" name="pname" id="pname"/><br>
- 密码:<input type="password" name="password" id="password"/><br>
- 年龄:<input type="text" name="page" id="page"/><br>
- <input type="button" value="测试" onclick="testJson()"/>
- </form>
- </body>
- </html>
在src目录上创建pojo包并创建Person实体类
- package pojo;
- public class Person {
- private String pname;
- private String password;
- private Integer page;
- public String getPname() {
- return pname;
- }
- public void setPname(String pname) {
- this.pname = pname;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public Integer getPage() {
- return page;
- }
- public void setPage(Integer page) {
- this.page = page;
- }
- }
TestController类代码如下
- package controller;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import pojo.Person;
- @Controller
- public class TestController {
- /**
- * 接收页面请求的JSON数据,并返回JSON格式结果
- */
- @RequestMapping("/testJson")
- @ResponseBody
- public List<Map<String, Object>> testJson(@RequestBody Person user) {
- //打印接收的JSON格式数据
- System.out.println("pname=" + user.getPname() +
- ", password=" + user.getPassword() + ",page=" + user.getPage());
- //返回Person对象
- //return user;
- /**ArrayList<Person> allp = new ArrayList<Person>();
- Person p1 = new Person();
- p1.setPname("陈恒1");
- p1.setPassword("123456");
- p1.setPage(80);
- allp.add(p1);
-
- Person p2 = new Person();
- p2.setPname("陈恒2");
- p2.setPassword("78910");
- p2.setPage(90);
- allp.add(p2);
- //返回ArrayList<Person>对象
- return allp;
- **/
-
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("pname", "陈恒2");
- map.put("password", "123456");
- map.put("page", 25);
- //返回一个Map<String, Object>对象
- //return map;
- //返回一个List<Map<String, Object>>对象
- List<Map<String, Object>> allp = new ArrayList
- allp.add(map);
- Map<String, Object> map1 = new HashMap<String, Object>();
- map1.put("pname", "陈恒3");
- map1.put("password", "54321");
- map1.put("page", 55);
- allp.add(map1);
- return allp;
- }
- }
选择Run命令发布并运行应用即可