package com.poyee.util; import com.alibaba.fastjson.JSONObject; import com.poyee.base.dto.AppBaseUser; import com.poyee.base.dto.UserInfo; import com.poyee.common.enums.I18nFormat; import com.poyee.common.exception.AuthException; import com.poyee.i18n.I18nLanguage; import com.poyee.i18n.I18nUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.*; import static com.poyee.i18n.I18nLanguage.EN; import static com.poyee.i18n.I18nLanguage.ZH_CN; import static com.poyee.i18n.I18nMessageEnums.GET_USER_INFO_ERROR; /** * 客户端工具类 * * @author zheng */ @Slf4j public class ServletUtils { /** * 定义移动端请求的所有可能类型 */ private final static String[] agent = {"Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser"}; /** * 获取String参数 */ public static String getParameter(String name) { return getRequest().getParameter(name); } /** * 获取String参数 */ public static String getParameter(String name, String defaultValue) { return Convert.toStr(getRequest().getParameter(name), defaultValue); } /** * 获取Integer参数 */ public static Integer getParameterToInt(String name) { return Convert.toInt(getRequest().getParameter(name)); } /** * 获取Integer参数 */ public static Integer getParameterToInt(String name, Integer defaultValue) { return Convert.toInt(getRequest().getParameter(name), defaultValue); } /** * 获取request */ public static HttpServletRequest getRequest() { return getRequestAttributes().getRequest(); } /** * 获取response */ public static HttpServletResponse getResponse() { return getRequestAttributes().getResponse(); } /** * 获取session */ public static HttpSession getSession() { return getRequest().getSession(); } /** * 获取session */ public static HttpSession getSession(boolean b) { return getRequest().getSession(b); } /** * @return */ public static ServletRequestAttributes getRequestAttributes() { RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); return (ServletRequestAttributes) attributes; } /** * 将字符串渲染到客户端 * * @param response 渲染对象 * @param string 待渲染的字符串 * @return null */ public static String renderString(HttpServletResponse response, String string) { try { response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); response.getWriter().print(string); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 是否是Ajax异步请求 * * @param request */ public static boolean isAjaxRequest(HttpServletRequest request) { String accept = request.getHeader("accept"); if (accept != null && accept.indexOf("application/json") != -1) { return true; } String xRequestedWith = request.getHeader("X-Requested-With"); if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) { return true; } String uri = request.getRequestURI(); if (ObjectUtil.inStringIgnoreCase(uri, ".json", ".xml")) { return true; } String ajax = request.getParameter("__ajax"); return ObjectUtil.inStringIgnoreCase(ajax, "json", "xml"); } /** * 判断User-Agent 是不是来自于手机 */ public static boolean checkAgentIsMobile(String ua) { boolean flag = false; if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) { // 排除 苹果桌面系统 if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) { for (String item : agent) { if (ua.contains(item)) { flag = true; break; } } } } return flag; } /** * @return */ public static String getIpAddress() { HttpServletRequest request = getRequest(); String ip; try { ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } catch (Exception e) { ip = "未知IP"; } return ip; } /** * 设置用户信息 * @param userInfo */ public static void setUserInfo(UserInfo userInfo){ try { getSession().setAttribute("userInfo", JSONObject.toJSONString(userInfo)); log.info(" 设置用户信息:{} ", userInfo); } catch (Exception e) { log.error(" 设置用户信息异常:{} ", e.getMessage()); throw new AuthException(I18nUtils.get(GET_USER_INFO_ERROR)); } } /** * @return */ public static UserInfo getUserInfo() { UserInfo userInfo = new UserInfo(); try { String userInfoObj = (String) getSession().getAttribute("userInfo"); userInfo = JSONObject.parseObject(userInfoObj, UserInfo.class); JSONObject jsonObject = JSONObject.parseObject(userInfoObj); String id = jsonObject.getString("id"); if(StringUtils.isBlank(id)){ id = jsonObject.getString("userId"); if(StringUtils.isNotBlank(id) && Objects.equals(id, "null")){ id = null; userInfo.setUserId(id); } } userInfo.setId(Objects.isNull(id)?null:Integer.parseInt(id)); log.info(" userInfo>>>{} ", userInfo); } catch (Exception e) { log.error(" 获取用户信息异常:", e); throw new AuthException(I18nUtils.get(GET_USER_INFO_ERROR)); } return userInfo; } /** * @return */ public static AppBaseUser getAppUserInfo() { AppBaseUser userInfo = new AppBaseUser(); try { String userInfoObj = (String) getSession().getAttribute("appBaseUser"); userInfo = JSONObject.parseObject(userInfoObj, AppBaseUser.class); JSONObject jsonObject = JSONObject.parseObject(userInfoObj); String id = jsonObject.getString("id"); userInfo.setId(Integer.parseInt(id)); log.info(" AppBaseUser>>>{} ", userInfo); } catch (Exception e) { log.error(" 获取用户信息异常:{} ", e.getMessage()); throw new AuthException(I18nUtils.get(GET_USER_INFO_ERROR)); } return userInfo; } /** * 获取XuserBase64 * @return */ public static String getXuserBase64(){ return (String) getSession().getAttribute("x-user-base64"); } /** * @return */ public static UserInfo getGeneralUser() { UserInfo userInfo = new UserInfo(); try { String userInfoObj = (String) getSession().getAttribute("userInfo"); userInfo = JSONObject.parseObject(userInfoObj, UserInfo.class); log.info(" userInfo>>>{} ", userInfo); if ("general_user".equals(userInfo.getRoleCode())) { return userInfo; } } catch (Exception e) { throw new AuthException(I18nUtils.get(GET_USER_INFO_ERROR)); } return null; } /** * * @return */ public static I18nLanguage getLanguage() { String language = (String) getSession().getAttribute("language"); if (StringUtils.isBlank(language)) { if(isI18n()){//国际版默认英文 language = EN.getCode(); }else{//国内版默认中文 language = ZH_CN.getCode(); } } return I18nLanguage.getByCode(language); } /** * 判断是否国际版 */ public static boolean isI18n() { String language = (String) getSession().getAttribute("language"); return StringUtils.isNotBlank(language); } /** * 判断接口是否支持国际版 */ public static boolean isI18nSupport() { try { return (boolean) Optional.ofNullable(getSession().getAttribute("i18n")).orElse(false); }catch (Exception e){ return false; } } /** * 检查国际化格式是否支持 * * @param formats 请求的国际化格式数组 * @return 如果支持任意一种格式,返回 true;否则返回 false */ public static boolean checkI18nFormat(I18nFormat[] formats) { if (formats == null || formats.length == 0) { return false; } I18nFormat[] supportedFormats = (I18nFormat[]) getSession().getAttribute("i18nFormat"); if (supportedFormats == null || supportedFormats.length == 0) { log.warn("未配置支持的国际化格式"); return false; } // 使用 Set 提高查找效率 Set supportedSet = new HashSet<>(Arrays.asList(supportedFormats)); for (I18nFormat format : formats) { if (supportedSet.contains(format)) { return true; } } log.warn("不支持的国际化格式: {}", Arrays.toString(formats)); return false; } }