当前位置:网站首页>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();
}
}
}
}
边栏推荐
- 接口管理工具YApi怎么用?颜值高、易管理、超好用
- 2022/08/02 学习笔记 (day22) 多线程
- 探索性测试的概念及方法
- 测试人员的价值体现在哪里
- Installation of Apache DolphinScheduler version 2.0.5 distributed cluster
- 接口测试实战| GET/POST 请求区别详解
- Harmony OS ets ArkUI 】 【 】 the development basic page layout and data connection
- typescript41-class类的私有修饰符
- How to use the interface management tool YApi?Beautiful, easy to manage, super easy to use
- 1095 解码PAT准考证 (25 分)(C语言)
猜你喜欢
【Harmony OS】【FAQ】鸿蒙问题合集1
BIOTIN ALKYNE CAS:773888-45-2价格,供应商
【Biotin Azide|cas:908007-17-0】Price_Manufacturer
Alienware上线首个数字时装AR试穿体验
Interface Test Framework Practice | Process Encapsulation and Test Case Design Based on Encrypted Interface
CobalStrike(CS)基础超级详细版
测试人员的价值体现在哪里
Peptides mediated PEG DSPE of phospholipids, targeted functional materials - PEG - RGD/TAT/NGR/APRPG
How to prepare for the test interface test data
在树莓派上搭建属于自己的网页(2)
随机推荐
接口测试框架实战(三)| JSON 请求与响应断言
typescript40-class类的保护修饰符
2022/08/02 学习笔记 (day22) 多线程
Flink state
【Harmony OS】【FAQ】鸿蒙问题合集1
Talking about GIS Data (5) - Geographic Coordinate System
Get the Ip tool class
私域流量时代来临,电商企业如何布局?
JS底层手写
私域流量引流方法?分享购火爆的商业模式,你值得拥有
Jmeter 模拟多用户登录的两种方法
Coordinate knowledge in digital twin campus scenarios
Detailed explanation of MOSN reverse channel
内部类、static关键字、final
GIS数据漫谈(五)— 地理坐标系统
【Harmony OS】【FAQ】Hongmeng Questions Collection 1
Build your own web page on raspberry pie (1)
【HMS core】【Ads Kit】华为广告——海外应用在国内测试正式广告无法展示
获取Ip工具类
1058 选择题 (20 分)(C语言)