问题描述:前端如何通过发送axios网络请求向后端的servlet接口进行进行数据交互
这里我通过登录系统这个例子进行说明
前端代码
在vue文件中引入axios,也可以在main.js中引入
import axios from "axios";
发送网络请求的代码
axios({
method: 'POST', //提交方法
url: 'http://localhost:8080/PPFM/userLogin', //后端的servlet登录接口
data: {
userName: this.ruleForm.username, //传输的用户名
password: this.ruleForm.password, //传输的密码
},
}).then(res => {
console.log(res); //对后端servlet接口返回的数据进行输出
//获取返回数据中的信息
console.log(res.data.msg);
console.log(res.data.data.userName);
})
后端代码
后端servlet登录接口代码
package servlet;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import dao.userInfo.UserInfoMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import pojo.UserInfo;
import utils.MybatisUtils;
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;
import java.util.HashMap;
import java.util.List;
@WebServlet("/userLogin")
public class UserLogin extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置传值的编码
resp.setContentType("text/html;charset=UTF-8");
req.setCharacterEncoding("utf-8");
//数据流获取信息
StringBuilder sb = new StringBuilder();
BufferedReader reader = req.getReader();
char[] buf = new char[1024];
int len;
while ((len = reader.read(buf)) != -1){
sb.append(buf,0,len);
}
//转json
String str = sb.toString();
JSONObject jsonObject = JSONObject.parseObject(str);
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
HashMap<String, String> map = new HashMap<>();
//获取前端传入数据中的用户名和密码,到数据库中进行查询
map.put("name",jsonObject.getString("userName"));
map.put("password",jsonObject.getString("password"));
List<UserInfo> userInfos = mapper.queryUserInfo(map);
for (UserInfo userInfo : userInfos) {
System.out.println(userInfo);
}
//用Google的Gson把list对象转化为json数据格式
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(userInfos);
JsonObject jsonObject1 = new JsonObject();
jsonObject1.add("data",jsonElement);
if (userInfos.size() != 0) {
//查询成功返回0
jsonObject1.addProperty("msg","0");
} else {
//查询失败返回1
jsonObject1.addProperty("msg","1");
}
String s = gson.toJson(jsonObject1);
//将json数据进行一个输出打印
PrintWriter writer = resp.getWriter();
writer.write( s );
writer.flush();
writer.close();
sqlSession.close();
}
}