当前位置:网站首页>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();
}
}
}
}
边栏推荐
- Jmeter 模拟多用户登录的两种方法
- Presto installation and deployment tutorial
- 私域流量引流方法?分享购火爆的商业模式,你值得拥有
- 接口和协议
- MCM box model modeling method and source analysis of atmospheric O3
- 常见荧光染料修饰多种基团及其激发和发射波长数据一览数据
- 1. 两数之和
- 【 Harmony OS 】 【 ano UI 】 lightweight data storage
- 13.< tag-动态规划和回文字串>lt.647. 回文子串 + lt.516.最长回文子序列
- Coordinate knowledge in digital twin campus scenarios
猜你喜欢

Concepts and Methods of Exploratory Testing

接口和抽象

typescript46-函数之间的类型兼容性

UV decomposition of biotin - PEG2 - azide | CAS: 1192802-98-4 biotin connectors

Unity2D horizontal board game tutorial 6 - enemy AI and attack animation

超好用的画图工具推荐

UV 裂解的生物素-PEG2-叠氮|CAS:1192802-98-4生物素接头

13.
lt.647. Palindromic substring + lt.516. Longest palindrome subsequence 
接口和协议

Peptides mediated PEG DSPE of phospholipids, targeted functional materials - PEG - RGD/TAT/NGR/APRPG
随机推荐
Fluorescent marker peptides FITC/AMC/FAM/Rhodamine TAMRA/Cy3 / Cy5 / Cy7 - Peptide
Shell conditional statement judgment
业务表解析-余额系统
用户密码验证
【Harmony OS】【ArkUI】ets开发 图形与动画绘制
1. 两数之和
1058 选择题 (20 分)(C语言)
【Harmony OS】【ARK UI】Date 基本操作
高可用 两地三中心
Presto installation and deployment tutorial
WinForm的控件二次开发
Build your own web page on the Raspberry Pi (2)
Install PostgreSQL on Windows
获取Ip工具类
[Developers must see] [push kit] Collection of typical problems of push service service 2
MOSN 反向通道详解
2022暑假牛客多校联赛第一场
超好用的画图工具推荐
13.< tag-动态规划和回文字串>lt.647. 回文子串 + lt.516.最长回文子序列
探索性测试的概念及方法