后端响应固定格式给前端:
1,创建一个专门存储数据的类;分别存储响应状态码code,响应数据,传输的消息。
public class CommonData {
int code;
Object data;
String message;
public CommonData(int code, String message) {
this.code = code;
this.message = message;
}
public CommonData(int code, Object data, String message) {
this.code = code;
this.data = data;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2,后端向前端传输
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String account=req.getParameter("account");
String password=req.getParameter("password");
System.out.println(account);
System.out.println(password);
PrintWriter printWriter=resp.getWriter();
User user= null;
CommonData commonData=null;
try {
user = dao.logindao(account,password);
if(user==null) {
commonData=new CommonData(201,"账号或密码输入有误,请重新输入!");
}
else {
commonData=new CommonData(200,user,"登录成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
commonData=new CommonData(500,"服务器忙...请稍后重试!");
}
ObjectMapper objectMapper=new ObjectMapper();
String json=objectMapper.writeValueAsString(commonData);
printWriter.print(json);
}
3,前端接收后端传来的Json数据
login() {
this.$http.post("LoginServlet", jsonToString(this.from)).then(resp => {
if (resp.data.code == 201) {
this.$message({
message: resp.data.message,
type: 'warning'
});
} else if (resp.data.code == 200) {
this.$message({
message: resp.data.message,
type: 'success'
});
sessionStorage.setItem("account", resp.data.data.account);
this.$router.push("/main"); //在js中进行路由导航
}
})
}