JSON
前后端分离
后端部署后端,提供接口:提供接口
JSON
前端独立部署,负责渲染后端的数据:
JSON(JavaScript Object Notation,JS 对象标记)是一种轻量级的数据交换格式
JSON采用完全独立于编程语言的文本格式来存储和表示数据
简洁和清晰的层次结构使得JSON成为理想的数据交换语言
易于人阅读和编写,同时也易于机器解析和生成。并有效的提升网络传输效率
在JavaScript语言中,一切都是对象。因此,任何JavaScript支持的类型都可以通过JSON来表示,例如字符串、数字、对象、数组等。
- 对象为键值对时,数据由逗号分隔
- 花括号保存对象
- 方括号保存数组
JSON键值对是用来保存JavaScript对象的一种方式,和JavaScript对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号 "" 包裹,使用冒号:分隔,然后紧接着值:
{"name": "Qinjiang"}
{"age": "3"}
{"sex": "男"}
JSON和JavaScript对象的关系
- JSON是JavaScript对象的字符串表示法,它使用文本表示一个JS对象的信息,本质是一个字符串
var obj = {a: 'hello', b: 'world'}; //对象
var json = '{"a" : "Hello", "b": "world"}'; //JSON字符串
JSON和JavaScript对象互转
- 要实现从JSON字符串转换为JavaScript对象,使用JSON.parse()方法:
var obj = JSON.parse('{"a": "hello, "b": "world"}'); //结果为 " "
- 要实现从JavaScript对象转换为JSON字符串,使用JSON.stringify()方法:
var json = JSON.stringify({a: 'hello', b: 'world'}); //结果为 ' '
测试
<script type="text/javascript">
//编写一个JavaScript对象
var user = {
name : "张磊",
age : 3,
sex: "男"
};
//将js对象转换为JSON对象
var json = JSON.stringify(user);
console.log(json);
console.log("================");
//将JSON对象转换为JavaScript对象
var obj = JSON.parse(json);
console.log(obj)
</script>
Controller返回JSON数据
- Jackson应该是目前比较好的json解析工具了
- 当然工具不止这一个,比如还有阿里巴巴的fastjson等等
- 我们这里使用Jackson,使用它还需要导入它的jar包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
乱码解决:
<!-- JSON乱码-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
@Controller
public class UserController {
@RequestMapping("/j1")
@ResponseBody //不会走视图解析器,直接返回一个字符串
public String json1() throws JsonProcessingException {
//jackson, ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
User user = new User("张磊",22,"男");
String s = mapper.writeValueAsString(user);
return s;
}
}
FastJson
fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。实现json的转换方法很多,最后的实现结果都是一样的。
依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
System.out.println("*******Java对象 转 JSON字符串*******");
String str1 = JSON.toJSONString(list);
System.out.println("JSON.toJSONString(list)==>"+str1);
String str2 = JSON.toJSONString(user1);
System.out.println("JSON.toJSONString(user1)==>"+str2);
System.out.println("\n****** JSON字符串 转 Java对象*******");
User jp_user1=JSON.parseObject(str2,User.class);
System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);
System.out.println("\n****** Java对象 转 JSON对象 ******");
JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));
System.out.println("\n****** JSON对象 转 Java对象 ******");
User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
文件上传
准备工作
文件上传是项目开发中最常见的功能之一 ,springMVC 可以很好的支持文件上传,但是SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理文件上传工作。如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver。
前端表单要求:为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器;
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- 文件上传-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40968"/>
</bean>
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接回到首页!
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名 : "+uploadFileName);
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
InputStream is = file.getInputStream(); //文件输入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流
//读取写出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
/*
* 采用file.Transto 来保存上传的文件
*/
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
return "redirect:/index.jsp";
}