如果将params:{}换成data:{},则客户端发送的数据类型将变为JSON类型的数据
此时
String uname = request.getParameter("uname"); String pwd = request.getParameter("pwd");
将无法获取签到前端发送的JSON类型数据,需要使用字节流来接受JSON类型数据,将其转化为string类型数据。
//1.fromJson(string,T) 将字符串转化成java object
//2.toJson(java Object) 将java object转化成json字符串,这样才能响应给客户端
package com.atguigu.axios; import com.atguigu.pojo.User; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/axios02.do") public class Axios02Servlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuffer stringBuffer = new StringBuffer(""); BufferedReader bufferedReader = request.getReader(); String str = null ; while((str=bufferedReader.readLine())!=null){ stringBuffer.append(str); } str = stringBuffer.toString() ; //已知 String //需要转化成 Java Object Gson gson = new Gson(); //Gson有两个API //1.fromJson(string,T) 将字符串转化成java object //2.toJson(java Object) 将java object转化成json字符串,这样才能响应给客户端 User user = gson.fromJson(str, User.class); System.out.println(user); } }
前端代码
02.演示Axios发送JSON格式的参数值给服务器端 uname:
pwd:
2.后端传输JSON数据给前端
1.注意一点,返回前端数据时,应声明为JSON格式
response.setContentType("application/json;charset=utf-8");
2.后端发送的json数据,通过前端的value.data可以查出来,然后引用
package com.atguigu.axios; import com.atguigu.pojo.User; import com.google.gson.Gson; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; @WebServlet("/axios03.do") public class Axios03Servlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuffer stringBuffer = new StringBuffer(""); BufferedReader bufferedReader = request.getReader(); String str = null ; while((str=bufferedReader.readLine())!=null){ stringBuffer.append(str); } str = stringBuffer.toString() ; //已知 String //需要转化成 Java Object Gson gson = new Gson(); //Gson有两个API //1.fromJson(string,T) 将字符串转化成java object //2.toJson(java Object) 将java object转化成json字符串,这样才能响应给客户端 User user = gson.fromJson(str, User.class); user.setUname("鸠摩智"); user.setPwd("123456"); //假设user是从数据库查询出来的,现在需要将其转化成json格式的字符串,然后响应给客户端 String userJsonStr = gson.toJson(user); response.setCharacterEncoding("UTF-8"); //MIME-TYPE response.setContentType("application/json;charset=utf-8"); response.getWriter().write(userJsonStr); } }
前端代码
03.演示Axios发送异步请求给服务器端,服务器响应json格式的数据给客户端 uname:
pwd:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)