当前位置:网站首页>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();
}
}
}
}
边栏推荐
- Exception (abnormal) and Error (error) difference analysis
- 接口测试框架实战(三)| JSON 请求与响应断言
- DFS's complement to pruning
- WebSocket的实际应用
- Install IIS services (Internet Information Services (Internet Information Services, abbreviated IIS, Internet Information Services)
- 在树莓派上搭建属于自己的网页(2)
- 业务表解析-余额系统
- Modified BiotinDIAZO-Biotin-PEG3-DBCO|diazo-biotin-tripolyethylene glycol-diphenylcyclooctyne
- OSI的分层特点、传输过程与三次握手、四次挥手、tcp与udp包头的描述
- 【生物素叠氮化物|cas:908007-17-0】价格_厂家
猜你喜欢
Kotlin-Flow common encapsulation class: the use of StateFlow
shell script loop statement
【HMS core】【Ads Kit】Huawei Advertising——Overseas applications are tested in China. Official advertisements cannot be displayed
常见荧光染料修饰多种基团及其激发和发射波长数据一览数据
UV 裂解的生物素-PEG2-叠氮|CAS:1192802-98-4生物素接头
WinForm的控件二次开发
FileZilla 搭建ftp服务器
VR全景展打造专属元宇宙观展空间
【Harmony OS】【FAQ】鸿蒙问题合集1
2022/08/02 学习笔记 (day22) 多线程
随机推荐
[Harmony OS] [ARK UI] ETS context basic operations
JS bottom handwriting
Flink state
探索性测试的概念及方法
1054 求平均值 (20 分)
在树莓派上搭建属于自己的网页(1)
VR全景展打造专属元宇宙观展空间
MOSN 反向通道详解
接口测试如何准备测试数据
typescript44-对象之间的类兼容器
【 Harmony OS 】 【 ano UI 】 lightweight data storage
FileZilla 搭建ftp服务器
【Harmony OS】【ARK UI】ets使用startAbility或startAbilityForResult方式调起Ability
接口和协议
【Biotin Azide|cas:908007-17-0】Price_Manufacturer
测试人员的价值体现在哪里
Interface testing framework combat (3) | JSON request and response assertion
【精讲】利用原生js实现todolist
shell script loop statement
BIOTIN ALKYNE CAS:773888-45-2价格,供应商