目录
java中使用JSON对象
在pom.xml中导入依赖
使用 public static String toJSONString(Object object)把自定义对象变成JSON对象
json和axios综合案例
使用的过滤器
前端代码
响应和请求都是普通字符串 和 请求时普通字符串,响应是json字符串
响应的数据是json数据
结果
json和axios综合案例进阶
在web层中,可以创建一个Result类,用来封装发给前端的数据
Servlet类
前端代码的书写
结果
java中使用JSON对象
在pom.xml中导入依赖
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>
json对象
{key:value,key:value...}//key必须是字符串类型
使用 public static String toJSONString(Object object)把自定义对象变成JSON对象
测试
public class User {private String username;private String password;public User() {}public User(String username, String password) {this.username = username;this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;} }
public class JsonTest {//将一个对象转换成json对象@Testpublic void test() {//创建一个User对象User user = new User();//赋值user.setUsername("hhh");user.setPassword("123");String jsonString = JSON.toJSONString(user);System.out.println("json=" + jsonString);//json={"password":"123","username":"hhh"}}//单列集合转换成json对象@Testpublic void test1() {//创建集合List<User> list = new ArrayList<>();Collections.addAll(list, new User("hhh", "123"), new User("aaa", "345"));String jsonString = JSON.toJSONString(list);System.out.println("json=" + jsonString);/*json=[{"password":"123","username":"hhh"},{"password":"345","username":"aaa"}]*/}//双列集合转换成json对象@Testpublic void test2(){//创建集合Map<String,Object>map=new HashMap<>();map.put("hhh1","aaa");map.put("hhh2",new User("bbb","1"));List<User> list = new ArrayList<>();Collections.addAll(list, new User("hhh", "123"), new User("aaa", "345"));map.put("hhh3",list);String jsonString = JSON.toJSONString(map);System.out.println("json="+jsonString);/*json={"hhh1":"aaa","hhh2":{"password":"1","username":"bbb"},"hhh3":[{"password":"123","username":"hhh"},{"password":"345","username":"aaa"}]}*/}}
json和axios综合案例
使用的过滤器
@WebFilter("/*") public class EncodeFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpServletResponse response = (HttpServletResponse) servletResponse;//your code..//解决请求乱码request.setCharacterEncoding("utf-8");//解决响应乱码response.setContentType("text/html;charset=utf-8");response.addHeader( "Access-Control-Allow-Origin","*");//允许所有来源访同response.addHeader( "Access-Control-Allow-Method","POST,GET");//允许访问的方式//放行filterChain.doFilter(request,response);}@Overridepublic void destroy() {} }
前端代码
<template><div id="app"><h1>axois和json综合</h1><!-- 点击此按钮就会执行method1()函数 --><input type="button" value="请求和响应都是普通字符串" @click="method1()"> <br><input type="button" value="响应数据是json字符串" @click="method2()"> <br><input type="button" value="请求数据是json字符串" @click="method3()"> <br><hr><h3>好友列表</h3><table width="500px" cellspacing="0px" cellpadding="5px" border="1px" id="myTable"><tr><th>id</th><th>name</th><th>age</th></tr></table></div> </template><script>import axios from 'axios'; export default {name: 'App',methods:{//1.响应和请求都是普通字符串method1(){//定义变量保存后端地址let url="http://localhost:8080/ajaxJsonDemo1Servlet";//定义参数let params="username=何以以&password=123";//发送请求axios.post(url,params).then(res=>{console.log(res.data);})},//请求时普通字符串,响应改成json字符串method2(){//定义变量保存后端地址let url="http://localhost:8080/ajaxJsonDemo2Servlet";//定义参数let params="username=何以以&password=123";//发送请求axios.post(url,params).then(res=>{console.log(res.data);})},method3(){//定义变量保存后端地址let url="http://localhost:8080/ajaxJsonDemo3Servlet";//json对象的 " " 每个引号之前都要加 \ 转义字符let params="{\"username\":\"何以以\",\"password\":\"145\"}";//发送请求axios.post(url,params).then(res=>{console.log(res.data);})}}}</script><style> /* #app {font-family: 'Avenir', Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px; } */ </style>
响应和请求都是普通字符串 和 请求时普通字符串,响应是json字符串
@WebServlet("/ajaxJsonDemo1Servlet") public class ajaxJsonDemo1Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取请求参数String username = request.getParameter("username");String password = request.getParameter("password");//打印输出System.out.println(username+"---"+password);//响应数据给前端response.addHeader( "Access-Control-Allow-Origin","*");//允许所有来源访同response.addHeader( "Access-Control-Allow-Method","POST,GET");//允许访问的方式response.getWriter().print("后端已经成功接收到数据");}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }
//请求时普通字符串,响应是json字符串 @WebServlet("/ajaxJsonDemo2Servlet") public class ajaxJsonDemo2Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//请求时普通字符串,响应数据是json对象//接收请求参数String username = request.getParameter("username");String password = request.getParameter("password");//创建User对象User user = new User();//将数据封装到User对象中user.setUsername(username);user.setPassword(password);//将对象变成json对象String jsonString = JSON.toJSONString(user);//响应数据给前端response.addHeader( "Access-Control-Allow-Origin","*");//允许所有来源访同response.addHeader( "Access-Control-Allow-Method","POST,GET");//允许访问的方式response.getWriter().print(jsonString);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }
响应的数据是json数据
request.getParameter("标识符");只能获取请求参数是普通字符串
如果是json字符使用:
1)使用request.getInputStream();//读取关联浏览器的字节输入流
2)使用request.getReader();//读取关联浏览器的字符输入流
所以我们可以使用获取流的方法结合JSON的方法一起解析前端提交的json数据
public static final<T> T pasreObject(InputStream is,Class<T>clazz);
参数:
is:关联的浏览器字节输入流
clazz:封装json请求参数的字节码对象
注意:要求实体类的属性名必须与json的key一致
let params="{\"username\":\"何以以\",\"password\":\"145\"}";
User实体类的属性名必须是username和password
@WebServlet("/ajaxJsonDemo3Servlet") public class ajaxJsonDemo3Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取请求参数//String username = request.getParameter("username");//获取不了,此方法只能获取普通参数的请求/*request.getParameter("标识符");只能获取请求参数是普通字符串如果是json字符使用:1)使用request.getInputStream();//读取关联浏览器的字节输入流2)使用request.getReader();//读取关联浏览器的字符输入流所以我们可以使用获取流的方法结合JSON的方法一起解析前端提交的json数据public static final<T> T pasreObject(InputStream is,Class<T>clazz);参数:is:关联的浏览器字节输入流clazz:封装json请求参数的字节码对象注意:要求实体类的属性名必须与json的key一致let params="{\"username\":\"何以以\",\"password\":\"145\"}";User实体类的属性名必须是username和password*/User user = JSON.parseObject(request.getInputStream(), User.class);System.out.println("user="+user);//user=User{username='何以以', password='145'}/* response.addHeader( "Access-Control-Allow-Origin","*");//允许所有来源访同response.addHeader( "Access-Control-Allow-Method","POST,GET");//允许访问的方式*/String jsonString = JSON.toJSONString(user);response.getWriter().print(jsonString);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);} }
结果
第二个的结果:
第三个的结果
json和axios综合案例进阶
在web层中,可以创建一个Result类,用来封装发给前端的数据
public class Result {private boolean flag;//执行结果,true为执行成功,false为执行失败private String message;//返回结果信息private Object valueDate;//返回数据(如果是查询操作就设置,增删不用设置)public Result(){}public Result(boolean flag, String message) {//失败,或者增删改this.flag = flag;this.message = message;}//成功的查询public Result(boolean flag, String message, Object valueDate) {this.flag = flag;this.message = message;this.valueDate = valueDate;}public boolean isFlag() {return flag;}public void setFlag(boolean flag) {this.flag = flag;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public Object getValueDate() {return valueDate;}public void setValueDate(Object valueDate) {this.valueDate = valueDate;} }
Servlet类
@WebServlet("/ajaxJsonDemo3Servlet") public class ajaxJsonDemo3Servlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取请求参数//String username = request.getParameter("username");//获取不了,此方法只能获取普通参数的请求/*request.getParameter("标识符");只能获取请求参数是普通字符串如果是json字符使用:1)使用request.getInputStream();//读取关联浏览器的字节输入流2)使用request.getReader();//读取关联浏览器的字符输入流所以我们可以使用获取流的方法结合JSON的方法一起解析前端提交的json数据public static final<T> T pasreObject(InputStream is,Class<T>clazz);参数:is:关联的浏览器字节输入流clazz:封装json请求参数的字节码对象注意:要求实体类的属性名必须与json的key一致let params="{\"username\":\"何以以\",\"password\":\"145\"}";User实体类的属性名必须是username和password*/User user = JSON.parseObject(request.getInputStream(), User.class);System.out.println("user="+user);/* response.addHeader( "Access-Control-Allow-Origin","*");//允许所有来源访同response.addHeader( "Access-Control-Allow-Method","POST,GET");//允许访问的方式*///模拟从数据库查出user信息的好友列表List<User> list=new ArrayList<>();Collections.addAll(list,new User("蚂蚁","123"),new User("遗迹","125"));//创建一个Result类对象Result result = new Result(true, "查询用户成功", list);//变成json对象String jsonString = JSON.toJSONString(result);//响应数据给前端response.getWriter().print(jsonString);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
发给前端的数据
前端代码的书写
<template><div id="app"><h1>axois和json综合</h1><!-- 点击此按钮就会执行method1()函数 --><input type="button" value="请求和响应都是普通字符串" @click="method1()"> <br><input type="button" value="响应数据是json字符串" @click="method2()"> <br><input type="button" value="请求数据是json字符串" @click="method3()"> <br><hr><div id="messID"></div> <br><h3>好友列表</h3><table width="500px" cellspacing="0px" cellpadding="5px" border="1px" id="myTable"><tr><th>名字</th><th>密码</th> </tr></table></div> </template><script>import axios from 'axios'; export default {name: 'App',methods:{//1.响应和请求都是普通字符串method1(){//定义变量保存后端地址let url="http://localhost:8080/ajaxJsonDemo1Servlet";//定义参数let params="username=何以以&password=123";//发送请求axios.post(url,params).then(res=>{console.log(res.data);})},//请求时普通字符串,响应改成json字符串method2(){//定义变量保存后端地址let url="http://localhost:8080/ajaxJsonDemo2Servlet";//定义参数let params="username=何以以&password=123";//发送请求axios.post(url,params).then(res=>{console.log(res.data);//从后端查到的数据{flag: true, mmessage: '查询用户成功', valueDate: Array(2)}})},method3(){//定义变量保存后端地址let url="http://localhost:8080/ajaxJsonDemo3Servlet";//json对象的 " " 每个引号之前都要加 \ 转义字符let params="{\"username\":\"何以以\",\"password\":\"145\"}";//发送请求axios.post(url,params).then(res=>{console.log(res.data);//从后端查到的数据{flag: true, message: '查询用户成功', valueDate: Array(2)}/*valueDate{password: '123', username: '蚂蚁'},{password: '125', username: '遗迹'}*/let obj=res.data;if(obj.flag){//查询成功document.getElementById("messID").innerHTML=obj.message;//设置空字符串let content="";let arr=obj.valueDate;for(let a of arr){//a是数组中的每个json对象content+=`<tr><td>${a.username}</td><td>${a.password}</td></tr>`}document.getElementById("myTable").innerHTML+=content;}})}}}</script><style> /* #app {font-family: 'Avenir', Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px; } */ </style>
结果
点击第三个按钮
由于我们会重复的从前端解析json,和发送json给前端,我们可以把那几个方法封装从工具类
public class BaseController {//静态方法解析前端提交的json数据 Class clazz=User.class//<T>定义泛型//T parseToObject,Class<T> clazz都是使用泛型public static <T> T parseToObject(HttpServletRequest request,Class<T> clazz)throws Exception{T obj= JSON.parseObject(request.getInputStream(),clazz);return obj;}//静态方法将后端的json数据响应到前端public static void responseJsonToBrowser(HttpServletResponse response,Object obj)throws Exception{//将result对象变成jsonString jsonString = JSON.toJSONString(obj);//响应数据给前端response.getWriter().print(jsonString);} }