ResponseUtils 工具类

说明

需要依赖 jackson ,将 java对象 转成 json 字符串

代码

package com.stdspringboot.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResponseUtils {
    /**
     * 打印字符串
     * @param response
     * @param content
     * @throws IOException
     */
    public static void print(HttpServletResponse response,String content) throws IOException {
        // 一定要在获取流之前调用,否则无效
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8"); // 有时不写也可以
        PrintWriter out=response.getWriter();
        out.print(content);
        out.flush();// 在springboot、springmvc中,必须加此行代码,否则可能报错
        out.close();
    }
    /**
     * 向前端输出JSON字符串,设置字符集是 UTF-8
     * @param response
     * @param json
     * @throws IOException
     */
    public static void sendJSON(HttpServletResponse response,String json) throws IOException {
        // 一定要在获取流之前调用,否则无效
        response.setContentType("application/json; charset=UTF-8");
        //response.setCharacterEncoding("UTF-8"); // 有时不写也可以
        PrintWriter out=response.getWriter();
        out.write(json);
        out.flush();// 在springboot、springmvc中,必须加此行代码,否则可能报错
        out.close();
    }


    public static void sendJSON(HttpServletResponse response,Object obj) throws IOException {

        // 调用 jackson,将javabean转换成json字符串
        ObjectMapper om=new ObjectMapper();
        String json=om.writeValueAsString(obj);
        sendJSON(response,json);
    }


}