OA智能办公-请假申请系统-封装返回

因为返回都是非常固定的写法,所以应该对其进行封装。

添加ResponseUtils类

package com.wu.oa.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.LinkedHashMap;
import java.util.Map;

public class ResponseUtils {
    private String code;
    private String message;
    private Map data = new LinkedHashMap();

    // 默认构造是成功返回的信息
    public ResponseUtils() {
        this.code = "0";
        this.message = "success";
    }

    // 统一对错误的处理
    public ResponseUtils(Exception exception) {
        this.code = exception.getClass().getSimpleName();
        this.message = exception.getMessage();
    }

    public ResponseUtils(String code, String message) {
        this.code = code;
        this.message = message;
    }

    // 使用setData可以链式向data添加数据
    public ResponseUtils setData(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    // 重写toString,返回JSON格式的数据
    @Override
    public String toString() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            String json = objectMapper.writeValueAsString(this);
            return json;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Map getData() {
        return data;
    }

    public void setData(Map data) {
        this.data = data;
    }
}

对比

以前的写法

// 处理登录参数,未使用ResponseUtils
Map result = new LinkedHashMap<>();
try {
    User user = userService.checkLogin(username, password);
    Map data = new LinkedHashMap();
    data.put("user",user);
    result.put("code","0");
    result.put("message","success");
    result.put("data", data);
} catch (Exception e) {
    result.put("code", e.getClass().getSimpleName());
    result.put("message",e.getMessage());
}

// 返回JSON
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
String json = objectMapper.writeValueAsString(result);
response.getWriter().println(json);

现在的写法

// 处理登录参数
PrintWriter writer = response.getWriter();
try {
    User user = userService.checkLogin(username, password);
    writer.println(new ResponseUtils().setData("user", user));
} catch (Exception e) {
    writer.println(new ResponseUtils(e));
}

可见减少了很多重复代码,而且结构也更清晰了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值