JSON
web1.0时代
早期网站,登录,如果失败,需要刷新页面,才能重新登录;不点击提交按钮,就不知道自己密码输错了;
现在大多数的网站,都是局部刷新,不刷新整个页面的情况下,实现页面更新;
注册的时候,发现手机已经注册过了,但是你只是输入了,没有提交,然后他就提示了。
Web2.0时代,最重要的一个因素就是Ajax。
JSON
前后端分离,数据交互变得异常重要;JSON就是王者!
json.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="text/javascript">
//编写一个对象
var user ={
name: "冯鹏",
age: 18,
sex: "男"
}
//输出一下这个对象
console.log(user)
//将js对象转换为json字符串;
var str = JSON.stringify(user);
console.log(str) //{"name":"冯鹏","age":18,"sex":"男"}
var obj = JSON.parse(str);
console.log(obj)
</script>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--1.注册servlet-->
<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:springmvc-servlet.xml</param-value>
</init-param>
<!-- 启动顺序,数字越小,启动越早 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--所有请求都会被springmvc拦截 -->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
</web-app>
resources
springmvc-servlet.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: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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.feng.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven>
<!--JSON格式乱码处理方式-->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<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>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
pojo
package com.feng.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @auther fengpeng
* @date 2022/9/6
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
utils
JsonUtils
package com.feng.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
/**
* @auther fengpeng
* @date 2022/9/12
*/
public class JsonUtils {
public static String getJson(Object object){
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
public static String getJson(Object object,String dateFormat){
ObjectMapper mapper = new ObjectMapper();
//1.如何让他不返回时间戳!所以我们要关闭它的时间戳功能
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//2.时间格式化问题!自定日期格式对象;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//3.让mapper指定时间日期格式为simpleDateFormat;
mapper.setDateFormat(sdf);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
controller
UserController
package com.feng.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.feng.pojo.User;
import com.feng.utils.JsonUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @auther fengpeng
* @date 2022/9/6
*/
@Controller
public class UserController {
@RequestMapping("/json1")
//思考问题,我们正常返回它会走视图解析器,而json需要返回的是一个字符串;
//市面上有很多的第三方jar包可以实现这个功能,jackson,只需要一个简单的注解就可以实现了;
//@ResponseBody ,将服务器端返回的对象转换为json对象响应回去;
@ResponseBody
public String json1() throws JsonProcessingException {
//需要一个jackson的对象映射器,就是一个类,使用它可以直接将对象转换为json字符串;
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
User user = new User("冯鹏1号", 1, "男");
System.out.println(user);
//将Java对象转换为json字符串;
String str = mapper.writeValueAsString(user);
System.out.println(str);
return str;//由于使用了@ResponseBody注解,这里会将str以json格式的字符串返回,十分方便;
}
//发现了一个问题,乱码了,怎么解决?给@RequestMapping加一个属性
//发现出现了乱码问题,我们需要设置一下他的编码方式utf-8,以及它返回的类型;
//通过RequestMapping的produces属性来实现,修改下代码
//produces:指定响应体返回类型和编码
@RequestMapping(value = "/json2",produces = "application/json;charset=utf-8")
@ResponseBody
public String json2() throws JsonProcessingException {
User user = new User("冯鹏1号", 1, "男");
return new ObjectMapper().writeValueAsString(user);//由于使用了@ResponseBody注解,这里会将str以json格式的字符串返回,十分方便;
}
@RequestMapping(value = "/json3")
@ResponseBody
public String json3() throws JsonProcessingException {
User user = new User("冯鹏1号", 1, "男");
User user2 = new User("冯鹏2号", 1, "男");
User user3 = new User("冯鹏3号", 1, "男");
User user4 = new User("冯鹏4号", 1, "男");
List<User> list = new ArrayList<>();
list.add(user);
list.add(user2);
list.add(user3);
list.add(user4);
return new ObjectMapper().writeValueAsString(list);//由于使用了@ResponseBody注解,这里会将str以json格式的字符串返回,十分方便;
}
@RequestMapping(value = "/time1")
@ResponseBody
public String json4() throws JsonProcessingException {
Date date = new Date();
System.out.println(date);
//发现问题:时间默认返回的json字符串变成了时间戳的格式:1662950664829 Timestamp
return new ObjectMapper().writeValueAsString(date);//由于使用了@ResponseBody注解,这里会将str以json格式的字符串返回,十分方便;
}
@RequestMapping(value = "/time2")
@ResponseBody
public String json5() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//1.如何让他不返回时间戳!所以我们要关闭它的时间戳功能
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//2.时间格式化问题!自定日期格式对象;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//3.让mapper指定时间日期格式为simpleDateFormat;
mapper.setDateFormat(sdf);
//写一个日期对象
Date date = new Date();
return mapper.writeValueAsString(date);
}
//发现问题,重复代码太多,给它编写一个工具类;
@RequestMapping(value = "/time3")
@ResponseBody
public String json6() throws JsonProcessingException {
return JsonUtils.getJson(new Date());
}
}
标签:mapper,String,json,JSON,User,new,import
From: https://www.cnblogs.com/fengpeng123/p/16846055.html