当前位置:网站首页>Response 重写设置返回值
Response 重写设置返回值
2022-08-03 05:09:00 【飞四海】
前几天因为要实现一个功能,修改response 默认的返回码中的 message,所以重写了一下response,
主要就是这个方法:
public static final void response(HttpServletResponse response, String text)
import cn.dolphin.core.exception.IoRuntimeException;
import cn.dolphin.core.result.ApiResult;
import cn.dolphin.core.util.Utf8Util;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class ResponseUtil {
private static final String DOWN_TYPE = "applicatoin/octet-stream";
private static final String DOWN_HEADER1 = "Content-Disposition";
private static final String DOWN_HEADER2 = "attachment; filename=";
private static final String EXCEL_TYPE = "application/vnd.ms-excel;charset=utf-8";
public static final String CACHE_CONTROL = "Cache-Control";
public static final String NO_CACHE = "no-cache";
public static final String PRAGMA = "Pragma";
public static final String EXPIRESS = "Expires";
public static final String FORWARD = "forward:";
public static final String REDIRECT = "redirect:";
private ResponseUtil() {
}
public static HttpServletResponse getResponse() {
return ((ServletRequestAttributes)((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())).getResponse();
}
public static final void setDownloadHeader(HttpServletResponse response, String fileName) {
response.reset();
response.setContentType("applicatoin/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + Utf8Util.utf2iso(fileName));
}
public static final void setNocachHeader(HttpServletResponse response) {
response.reset();
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0L);
}
public static final void setExcelHeader(HttpServletResponse response, String fileName) {
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + Utf8Util.utf2iso(fileName));
}
public static final void response(String text) {
response(getResponse(), text);
}
public static final void response(HttpServletResponse response, String text) {
cors(response, (String)null);
response.setStatus(HttpStatus.OK.value());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(text);
} catch (IOException var11) {
throw new IoRuntimeException("发送JSON响应失败", var11);
} finally {
try {
writer.close();
} catch (Exception var10) {
var10.printStackTrace();
}
}
}
public static final void responseText(String text) {
responseText(getResponse(), text);
}
public static final void responseText(HttpServletResponse response, String text) {
try {
response.getWriter().write(text);
response.getWriter().flush();
} catch (IOException var10) {
throw new IoRuntimeException("发送文字响应失败", var10);
} finally {
try {
response.getWriter().close();
} catch (Exception var9) {
var9.printStackTrace();
}
}
}
public static final String forward(String url) {
return "forward:" + url;
}
public static final void sendForward(HttpServletRequest request, HttpServletResponse response, String url) {
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (IOException | ServletException var4) {
throw new IoRuntimeException("转发失败:url = " + url, var4);
}
}
public static final void sendForward(String url) {
sendForward(RequestUtil.getRequest(), getResponse(), url);
}
public static final String redirect(String url) {
return "redirect:" + url;
}
public static final void sendRedirect(HttpServletResponse response, String url) {
try {
response.sendRedirect(url);
} catch (IOException var3) {
throw new IoRuntimeException("重定向失败:url = " + url, var3);
}
}
public static final void sendRedirect(String url) {
sendRedirect(getResponse(), url);
}
public static final void responseFile(byte[] bs, String fileName) {
responseFile(bs, fileName, getResponse());
}
public static final void responseFile(byte[] bs, String fileName, HttpServletResponse response) {
setDownloadHeader(response, fileName);
ServletOutputStream output = null;
try {
output = response.getOutputStream();
output.write(bs);
output.flush();
} catch (IOException var12) {
throw new IoRuntimeException("发送文件响应失败", var12);
} finally {
try {
output.close();
} catch (Exception var11) {
var11.printStackTrace();
}
}
}
public static final void cors(HttpServletResponse response, String origin) {
if (StringUtils.isBlank(response.getHeader("Access-Control-Allow-Origin"))) {
response.setHeader("Access-Control-Allow-Origin", origin == null ? "*" : origin);
}
}
public static final void sse() {
getResponse().setHeader("X-Accel-Buffering", "no");
}
public static void errorToken(HttpServletResponse httpResponse, String msg) throws IOException {
ApiResult result = ApiResult.error(msg);
String json = JSON.toJSONString(result);
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json;charset=UTF-8");
httpResponse.setHeader("Content-type", "application/json;charset=UTF-8");
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setStatus(401);
httpResponse.getWriter().write(json);
}
public static void errorToken(HttpServletResponse httpResponse, String code, String msg) throws IOException {
ApiResult result = ApiResult.error(code, msg);
String json = JSON.toJSONString(result);
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json;charset=UTF-8");
httpResponse.setHeader("Content-type", "application/json;charset=UTF-8");
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setStatus(401);
httpResponse.getWriter().write(json);
}
public static void errorAuth(HttpServletResponse httpResponse, String code, String msg) throws IOException {
ApiResult result = ApiResult.error(code, msg);
String json = JSON.toJSONString(result);
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json;charset=UTF-8");
httpResponse.setHeader("Content-type", "application/json;charset=UTF-8");
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setStatus(401);
httpResponse.getWriter().write(json);
}
public static void printJSON(HttpServletResponse response, Object object) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
PrintWriter printWriter = response.getWriter();
printWriter.write(JSON.toJSONString(object));
printWriter.flush();
printWriter.close();
}
public static void responseData(HttpServletResponse response, Object resData) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(resData);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(jsonString);
} catch (IOException var9) {
var9.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
边栏推荐
- Where is the value of testers
- CobalStrike(CS)基础超级详细版
- shell script loop statement
- 获取Ip工具类
- 接口测试如何准备测试数据
- Interface test practice | Detailed explanation of the difference between GET / POST requests
- Build your own web page on the Raspberry Pi (2)
- [Developers must see] [push kit] Collection of typical problems of push service service 2
- Windows 安装PostgreSQL
- 【Harmony OS】【ARK UI】Date 基本操作
猜你喜欢

13.< tag-动态规划和回文字串>lt.647. 回文子串 + lt.516.最长回文子序列

2. 两数相加

Jmeter 模拟多用户登录的两种方法

2022/08/02 Study Notes (day22) Multithreading

Kotlin-Flow common encapsulation class: the use of StateFlow

Where is the value of testers

【Harmony OS】【ArkUI】ets开发 图形与动画绘制

在树莓派上搭建属于自己的网页(1)

GIS数据漫谈(五)— 地理坐标系统

High availability, two locations and three centers
随机推荐
Build your own web page on raspberry pie (1)
【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed
1. 两数之和
IO process thread -> thread -> day5
业务表解析-余额系统
DFS's complement to pruning
OSI的分层特点、传输过程与三次握手、四次挥手、tcp与udp包头的描述
接口和协议
Shell conditional statement judgment
typescript49-交叉类型
js中的闭包
Installation of Apache DolphinScheduler version 2.0.5 distributed cluster
FileZilla 搭建ftp服务器
UV 裂解的生物素-PEG2-叠氮|CAS:1192802-98-4生物素接头
阿里云对象存储oss私有桶生成链接
【软件工程之美 - 专栏笔记】35 | 版本发布:软件上线只是新的开始
Odps temporary query can write SQL, turned out to a named?
closures in js
JS底层手写
Online password generator tool recommendation