ServletUtils.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. package com.poyee.util;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.poyee.base.dto.AppBaseUser;
  4. import com.poyee.base.dto.UserInfo;
  5. import com.poyee.common.enums.I18nFormat;
  6. import com.poyee.common.exception.AuthException;
  7. import com.poyee.i18n.I18nLanguage;
  8. import com.poyee.i18n.I18nUtils;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.springframework.web.context.request.RequestAttributes;
  11. import org.springframework.web.context.request.RequestContextHolder;
  12. import org.springframework.web.context.request.ServletRequestAttributes;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import javax.servlet.http.HttpSession;
  16. import java.io.IOException;
  17. import java.util.*;
  18. import static com.poyee.i18n.I18nLanguage.EN;
  19. import static com.poyee.i18n.I18nLanguage.ZH_CN;
  20. import static com.poyee.i18n.I18nMessageEnums.GET_USER_INFO_ERROR;
  21. /**
  22. * 客户端工具类
  23. *
  24. * @author zheng
  25. */
  26. @Slf4j
  27. public class ServletUtils {
  28. /**
  29. * 定义移动端请求的所有可能类型
  30. */
  31. private final static String[] agent = {"Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser"};
  32. /**
  33. * 获取String参数
  34. */
  35. public static String getParameter(String name) {
  36. return getRequest().getParameter(name);
  37. }
  38. /**
  39. * 获取String参数
  40. */
  41. public static String getParameter(String name, String defaultValue) {
  42. return Convert.toStr(getRequest().getParameter(name), defaultValue);
  43. }
  44. /**
  45. * 获取Integer参数
  46. */
  47. public static Integer getParameterToInt(String name) {
  48. return Convert.toInt(getRequest().getParameter(name));
  49. }
  50. /**
  51. * 获取Integer参数
  52. */
  53. public static Integer getParameterToInt(String name, Integer defaultValue) {
  54. return Convert.toInt(getRequest().getParameter(name), defaultValue);
  55. }
  56. /**
  57. * 获取request
  58. */
  59. public static HttpServletRequest getRequest() {
  60. return getRequestAttributes().getRequest();
  61. }
  62. /**
  63. * 获取response
  64. */
  65. public static HttpServletResponse getResponse() {
  66. return getRequestAttributes().getResponse();
  67. }
  68. /**
  69. * 获取session
  70. */
  71. public static HttpSession getSession() {
  72. return getRequest().getSession();
  73. }
  74. /**
  75. * 获取session
  76. */
  77. public static HttpSession getSession(boolean b) {
  78. return getRequest().getSession(b);
  79. }
  80. /**
  81. * @return
  82. */
  83. public static ServletRequestAttributes getRequestAttributes() {
  84. RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
  85. return (ServletRequestAttributes) attributes;
  86. }
  87. /**
  88. * 将字符串渲染到客户端
  89. *
  90. * @param response 渲染对象
  91. * @param string 待渲染的字符串
  92. * @return null
  93. */
  94. public static String renderString(HttpServletResponse response, String string) {
  95. try {
  96. response.setContentType("application/json");
  97. response.setCharacterEncoding("utf-8");
  98. response.getWriter().print(string);
  99. } catch (IOException e) {
  100. e.printStackTrace();
  101. }
  102. return null;
  103. }
  104. /**
  105. * 是否是Ajax异步请求
  106. *
  107. * @param request
  108. */
  109. public static boolean isAjaxRequest(HttpServletRequest request) {
  110. String accept = request.getHeader("accept");
  111. if (accept != null && accept.indexOf("application/json") != -1) {
  112. return true;
  113. }
  114. String xRequestedWith = request.getHeader("X-Requested-With");
  115. if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
  116. return true;
  117. }
  118. String uri = request.getRequestURI();
  119. if (ObjectUtil.inStringIgnoreCase(uri, ".json", ".xml")) {
  120. return true;
  121. }
  122. String ajax = request.getParameter("__ajax");
  123. return ObjectUtil.inStringIgnoreCase(ajax, "json", "xml");
  124. }
  125. /**
  126. * 判断User-Agent 是不是来自于手机
  127. */
  128. public static boolean checkAgentIsMobile(String ua) {
  129. boolean flag = false;
  130. if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
  131. // 排除 苹果桌面系统
  132. if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
  133. for (String item : agent) {
  134. if (ua.contains(item)) {
  135. flag = true;
  136. break;
  137. }
  138. }
  139. }
  140. }
  141. return flag;
  142. }
  143. /**
  144. * @return
  145. */
  146. public static String getIpAddress() {
  147. HttpServletRequest request = getRequest();
  148. String ip;
  149. try {
  150. ip = request.getHeader("x-forwarded-for");
  151. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  152. ip = request.getHeader("Proxy-Client-IP");
  153. }
  154. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  155. ip = request.getHeader("WL-Proxy-Client-IP");
  156. }
  157. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  158. ip = request.getHeader("HTTP_CLIENT_IP");
  159. }
  160. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  161. ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  162. }
  163. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  164. ip = request.getRemoteAddr();
  165. }
  166. } catch (Exception e) {
  167. ip = "未知IP";
  168. }
  169. return ip;
  170. }
  171. /**
  172. * 设置用户信息
  173. * @param userInfo
  174. */
  175. public static void setUserInfo(UserInfo userInfo){
  176. try {
  177. getSession().setAttribute("userInfo", JSONObject.toJSONString(userInfo));
  178. log.info(" 设置用户信息:{} ", userInfo);
  179. } catch (Exception e) {
  180. log.error(" 设置用户信息异常:{} ", e.getMessage());
  181. throw new AuthException(I18nUtils.get(GET_USER_INFO_ERROR));
  182. }
  183. }
  184. /**
  185. * @return
  186. */
  187. public static UserInfo getUserInfo() {
  188. UserInfo userInfo = new UserInfo();
  189. try {
  190. String userInfoObj = (String) getSession().getAttribute("userInfo");
  191. userInfo = JSONObject.parseObject(userInfoObj, UserInfo.class);
  192. JSONObject jsonObject = JSONObject.parseObject(userInfoObj);
  193. String id = jsonObject.getString("id");
  194. if(StringUtils.isBlank(id)){
  195. id = jsonObject.getString("userId");
  196. if(StringUtils.isNotBlank(id) && Objects.equals(id, "null")){
  197. id = null;
  198. userInfo.setUserId(id);
  199. }
  200. }
  201. userInfo.setId(Objects.isNull(id)?null:Integer.parseInt(id));
  202. log.info(" userInfo>>>{} ", userInfo);
  203. } catch (Exception e) {
  204. log.error(" 获取用户信息异常:", e);
  205. throw new AuthException(I18nUtils.get(GET_USER_INFO_ERROR));
  206. }
  207. return userInfo;
  208. }
  209. /**
  210. * @return
  211. */
  212. public static AppBaseUser getAppUserInfo() {
  213. AppBaseUser userInfo = new AppBaseUser();
  214. try {
  215. String userInfoObj = (String) getSession().getAttribute("appBaseUser");
  216. userInfo = JSONObject.parseObject(userInfoObj, AppBaseUser.class);
  217. JSONObject jsonObject = JSONObject.parseObject(userInfoObj);
  218. String id = jsonObject.getString("id");
  219. userInfo.setId(Integer.parseInt(id));
  220. log.info(" AppBaseUser>>>{} ", userInfo);
  221. } catch (Exception e) {
  222. log.error(" 获取用户信息异常:{} ", e.getMessage());
  223. throw new AuthException(I18nUtils.get(GET_USER_INFO_ERROR));
  224. }
  225. return userInfo;
  226. }
  227. /**
  228. * 获取XuserBase64
  229. * @return
  230. */
  231. public static String getXuserBase64(){
  232. return (String) getSession().getAttribute("x-user-base64");
  233. }
  234. /**
  235. * @return
  236. */
  237. public static UserInfo getGeneralUser() {
  238. UserInfo userInfo = new UserInfo();
  239. try {
  240. String userInfoObj = (String) getSession().getAttribute("userInfo");
  241. userInfo = JSONObject.parseObject(userInfoObj, UserInfo.class);
  242. log.info(" userInfo>>>{} ", userInfo);
  243. if ("general_user".equals(userInfo.getRoleCode())) {
  244. return userInfo;
  245. }
  246. } catch (Exception e) {
  247. throw new AuthException(I18nUtils.get(GET_USER_INFO_ERROR));
  248. }
  249. return null;
  250. }
  251. /**
  252. *
  253. * @return
  254. */
  255. public static I18nLanguage getLanguage() {
  256. String language = (String) getSession().getAttribute("language");
  257. if (StringUtils.isBlank(language)) {
  258. if(isI18n()){//国际版默认英文
  259. language = EN.getCode();
  260. }else{//国内版默认中文
  261. language = ZH_CN.getCode();
  262. }
  263. }
  264. return I18nLanguage.getByCode(language);
  265. }
  266. /**
  267. * 判断是否国际版
  268. */
  269. public static boolean isI18n() {
  270. String language = (String) getSession().getAttribute("language");
  271. return StringUtils.isNotBlank(language);
  272. }
  273. /**
  274. * 判断接口是否支持国际版
  275. */
  276. public static boolean isI18nSupport() {
  277. try {
  278. return (boolean) Optional.ofNullable(getSession().getAttribute("i18n")).orElse(false);
  279. }catch (Exception e){
  280. return false;
  281. }
  282. }
  283. /**
  284. * 检查国际化格式是否支持
  285. *
  286. * @param formats 请求的国际化格式数组
  287. * @return 如果支持任意一种格式,返回 true;否则返回 false
  288. */
  289. public static boolean checkI18nFormat(I18nFormat[] formats) {
  290. if (formats == null || formats.length == 0) {
  291. return false;
  292. }
  293. I18nFormat[] supportedFormats = (I18nFormat[]) getSession().getAttribute("i18nFormat");
  294. if (supportedFormats == null || supportedFormats.length == 0) {
  295. log.warn("未配置支持的国际化格式");
  296. return false;
  297. }
  298. // 使用 Set 提高查找效率
  299. Set<I18nFormat> supportedSet = new HashSet<>(Arrays.asList(supportedFormats));
  300. for (I18nFormat format : formats) {
  301. if (supportedSet.contains(format)) {
  302. return true;
  303. }
  304. }
  305. log.warn("不支持的国际化格式: {}", Arrays.toString(formats));
  306. return false;
  307. }
  308. }