标准化后端向前端传来的Json数据

26 篇文章 0 订阅
6 篇文章 0 订阅

后端响应固定格式给前端:

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中进行路由导航
					}

				})

			}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Adellle

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值