ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
``` /** * @author 张跃帅 * @Description: HttpServlet获取当前request和response-工具 * @date 2020/08/12 */ public class HttpServletUtil { /** * 获取当前请求的request对象 */ public static HttpServletRequest getRequest() { // 获取请求属性 ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); // 判断 if (null == requestAttributes) { // 抛出异常 throw new MyException(CommonExceptionEnum.ERROR_400.getCode(), "当前请求参数为空或数据缺失,请检查"); } else { // 返回 return requestAttributes.getRequest(); } } /** * 获取当前请求的response对象 */ public static HttpServletResponse getResponse() { // 获取请求属性 ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); // 判断 if (null == requestAttributes) { // 抛出异常 throw new MyException(CommonExceptionEnum.ERROR_400.getCode(), "当前请求参数为空或数据缺失,请检查"); } else { // 返回 return requestAttributes.getResponse(); } } /** * 获取-请求参数key的值 */ public static String getReqParamKeyOfVal(String paramKey) { // 获取当前请求的request对象 HttpServletRequest request = getRequest(); // 从请求体里面读取 String paramVal = request.getParameter(paramKey); // 判断 if (StrUtil.isBlank(paramVal)) { // 从header里读取 paramVal = request.getHeader(paramKey); } // 判断 if (StrUtil.isBlank(paramVal)) { // 从cookie里读取 Cookie[] cookies = request.getCookies(); // 判断 if (ObjectUtil.isNotEmpty(cookies)) { // 遍历 for (Cookie cookie : cookies) { // 获取参数 String cookieName = cookie.getName(); // 判断 if (cookieName.equals(cookieName)) { // 返回 return cookie.getValue(); } } } } // 返回 return paramVal; } }