Skip to content

Commit 7c453f7

Browse files
committed
feat: 添加 Web 工具类和写入响应 JSON 方法
1 parent 82a42aa commit 7c453f7

2 files changed

Lines changed: 38 additions & 1 deletion

File tree

simple-common/src/main/java/top/cadecode/common/enums/FrameErrorEnum.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ public enum FrameErrorEnum implements ResponseCode {
1414
JSON_TO_STR_ERROR(1000, "对象转 json 字符串出错"),
1515
JSON_TO_OBJ_ERROR(1001, "json 字符串转对象出错"),
1616
JWT_CREATE_ERROR(1003, "创建 token 出错"),
17-
JWT_VERIFY_ERROR(1003, "解析 token 出错"),
17+
JWT_VERIFY_ERROR(1004, "解析 token 出错"),
18+
RES_WRITE_JSON_ERROR(1005, "向响应对象写入 JSON 出错 "),
1819
;
1920

2021
private final String code;
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package top.cadecode.common.util;
2+
3+
import org.springframework.http.MediaType;
4+
import top.cadecode.common.core.exception.CommonException;
5+
import top.cadecode.common.enums.FrameErrorEnum;
6+
7+
import javax.servlet.http.HttpServletResponse;
8+
import java.io.IOException;
9+
import java.io.PrintWriter;
10+
11+
/**
12+
* @author Cade Li
13+
* @date 2021/12/11
14+
* @description Web 工具类
15+
*/
16+
public class WebUtil {
17+
18+
/**
19+
* 向响应对象写入 JSON
20+
*
21+
* @param response 响应对象
22+
* @param jsonString JSON 字符串
23+
*/
24+
public static void writeJsonToResponse(HttpServletResponse response, String jsonString) {
25+
try {
26+
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
27+
response.setCharacterEncoding("UTF-8");
28+
PrintWriter writer = response.getWriter();
29+
writer.print(jsonString);
30+
writer.flush();
31+
} catch (IOException e) {
32+
throw CommonException.of(FrameErrorEnum.RES_WRITE_JSON_ERROR)
33+
.suppressed(e);
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)