xuefei
2020-12-10 eeeb7233935ea9b10e99043bdbf740ef86c9bf20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package cn.cetc54.platform.core.common.utils;
 
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author
 */
@Slf4j
public class ResponseUtil {
 
    /**
     *  使用response输出JSON
     * @param response
     * @param resultMap
     */
    public static void out(HttpServletResponse response, Map<String, Object> resultMap){
 
        ServletOutputStream out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            out = response.getOutputStream();
            out.write(new Gson().toJson(resultMap).getBytes());
        } catch (Exception e) {
            log.error(e + "输出JSON出错");
        } finally{
            if(out!=null){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    public static Map<String, Object> resultMap(boolean flag, Integer code, String msg){
 
        return resultMap(flag, code, msg, null);
    }
 
    public static Map<String, Object> resultMap(boolean flag, Integer code, String msg, Object data){
 
        Map<String, Object> resultMap = new HashMap<String, Object>(16);
        resultMap.put("success", flag);
        resultMap.put("message", msg);
        resultMap.put("code", code);
        resultMap.put("timestamp", System.currentTimeMillis());
        if(data!=null){
            resultMap.put("result", data);
        }
        return resultMap;
    }
}