Json前后端数据交互
1.idea创建一个maven项目
2.引入项目需要的依赖
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> <!--<dependency>--> <!--<groupId>org.springframework</groupId>--> <!--<artifactId>spring-core</artifactId>--> <!--<version>5.2.8.RELEASE</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.springframework</groupId>--> <!--<artifactId>spring-context</artifactId>--> <!--<version>5.2.8.RELEASE</version>--> <!--</dependency>--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency>
3.web.xml文件中配置springmvc
<servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置springMVC需要加载的配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 匹配所有请求 --> <url-pattern>/</url-pattern> </servlet-mapping>
4.配置spring-mvc.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 注解请求映射 默认是ISO-88859-1,避免乱码这里设置为UTF-8 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes" value="text/html;charset=UTF-8" /> </bean> <!-- 启动JSON格式的配置,自动将格式转换成JSON格式,不需要其他类 --> <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes" value="application/json;charset=UTF-8" /> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <mvc:default-servlet-handler/> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.cai.controller" /> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
5.编写controller类
package com.cai.controller; import com.cai.entity.User; import com.cai.utils.JsonUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.xml.crypto.Data; import java.util.ArrayList; import java.util.Date; import java.util.List; @Controller @RequestMapping("/json") public class JsonController{ @RequestMapping(value = "/json1") @ResponseBody public List<User> json() throws JsonProcessingException { //需要一个jackson的对象映射器,就是一个类,可以将对象转换成json字符串 ObjectMapper om = new ObjectMapper(); List<User> list = new ArrayList(); User u1 = new User("json",12); User u2 = new User("鎏金",12); User u3 = new User("蔡松坡",12); list.add(u1); list.add(u2); list.add(u3); //将java对象转换成json字符串 //String s = om.writeValueAsString(list); return list; } @RequestMapping(value = "/json2") @ResponseBody public String json2() throws JsonProcessingException { //需要一个jackson的对象映射器,就是一个类,可以将对象转换成json字符串 // ObjectMapper om = new ObjectMapper(); // om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); // User u1 = new User("json",12); // // //将java对象转换成json字符串 // String s = om.writeValueAsString(u1); User u1 = new User("json",12); return JsonUtil.getJson(u1); } @RequestMapping(value = "/json3") @ResponseBody public String json3() throws JsonProcessingException { Date date = new Date(); return JsonUtil.getJson(date); } }
6.编写JsonUtil类
package com.cai.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.text.SimpleDateFormat; public class JsonUtil { public static String getJson(Object obj){ return getJson(obj,"yyyy-MM-dd HH:mm:ss"); } public static String getJson(Object obj,String pattern){ ObjectMapper om = new ObjectMapper(); //关闭时间戳 om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); SimpleDateFormat sdf = new SimpleDateFormat(pattern); om.setDateFormat(sdf); try { return om.writeValueAsString(obj); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } }
7.编写实体类
package com.cai.entity; public class User { private String name; private Integer age; public User() { } public User(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
8.启动服务器测试