yonge il y a 6 ans
Parent
commit
ac190354ef

+ 5 - 0
pom.xml

@@ -119,6 +119,11 @@
           </exclusion>
         </exclusions>
       </dependency>
+      
+      <dependency>
+        <groupId>org.apache.commons</groupId>
+        <artifactId>commons-lang3</artifactId>
+      </dependency>
 	</dependencies>
 
 	<build>

+ 31 - 0
src/main/java/com/ym/mec/collectfee/config/WebMvcConfig.java

@@ -0,0 +1,31 @@
+package com.ym.mec.collectfee.config;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+import com.ym.mec.collectfee.interceptor.RequestInterceptor;
+
+@Configuration
+public class WebMvcConfig implements WebMvcConfigurer {
+	
+	@Override
+    public void addInterceptors(InterceptorRegistry registry) {
+		// addPathPatterns 用于添加拦截规则, 这里假设拦截 /url 后面的全部链接
+        List<String> includePathPatterns = new ArrayList<String>();
+        includePathPatterns.add("/**");
+        
+        // excludePathPatterns 用户排除拦截
+        List<String> excludePathPatterns = new ArrayList<String>();
+        excludePathPatterns.add("/login");
+        
+        registry.addInterceptor(getRequestInterceptor()).addPathPatterns(includePathPatterns).excludePathPatterns(excludePathPatterns);
+    }
+	
+	public RequestInterceptor getRequestInterceptor(){
+		return new RequestInterceptor();
+	}
+}

+ 48 - 0
src/main/java/com/ym/mec/collectfee/core/BaseController.java

@@ -0,0 +1,48 @@
+package com.ym.mec.collectfee.core;
+
+import org.springframework.http.HttpStatus;
+
+public class BaseController {
+
+	public static HttpResponseResult succeed(Object object) {
+		return getResponseData(true, HttpStatus.OK, object, "");
+	}
+
+	public static HttpResponseResult succeed() {
+		return getResponseData(true, HttpStatus.OK, null, "");
+	}
+
+	public static HttpResponseResult succeed(String message) {
+		return failed(HttpStatus.OK, message);
+	}
+
+	public static HttpResponseResult succeedData(Object obj) {
+		return getResponseData(true, HttpStatus.OK, obj, "操作成功");
+	}
+
+	public static HttpResponseResult warned(String message) {
+		return failed(HttpStatus.MULTI_STATUS, message);
+	}
+
+	public static HttpResponseResult failed() {
+		return failed("");
+	}
+
+	public static HttpResponseResult failed(String msg) {
+		return failed(HttpStatus.INTERNAL_SERVER_ERROR, msg);
+	}
+
+	public static HttpResponseResult failed(HttpStatus statusCode, String msg) {
+		return getResponseData(false, statusCode, null, msg);
+	}
+
+	private static HttpResponseResult getResponseData(boolean status, HttpStatus statusCode, Object data, String message) {
+		HttpResponseResult obj = new HttpResponseResult();
+		obj.setStatus(status);
+		obj.setCode(statusCode.value());
+		obj.setData(data);
+		obj.setMsg(message);
+		return obj;
+	}
+
+}

+ 36 - 0
src/main/java/com/ym/mec/collectfee/core/BasicControllerAdvice.java

@@ -0,0 +1,36 @@
+package com.ym.mec.collectfee.core;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+@ControllerAdvice
+public class BasicControllerAdvice extends BaseController {
+
+	private final static Logger logger = LoggerFactory.getLogger(BasicControllerAdvice.class);
+
+	/**
+	 * 处理一般异常
+	 * 
+	 * @param ex
+	 * @param request
+	 * @return
+	 */
+	@ExceptionHandler(Exception.class)
+	@ResponseBody
+	public HttpResponseResult handleException(Exception ex, HttpServletRequest request) {
+		Throwable e = ExceptionUtils.getRootCause(ex);
+		if (e == null) {
+			e = ex;
+		}
+
+		logger.error("System Error", e);
+		return failed("系统内部错误:"+e.getMessage());
+	}
+
+}

+ 65 - 0
src/main/java/com/ym/mec/collectfee/core/HttpResponseResult.java

@@ -0,0 +1,65 @@
+package com.ym.mec.collectfee.core;
+
+/**
+ * HttpResponse 返回结果
+ */
+public class HttpResponseResult {
+
+	public final static int TIME_OUT = -1;
+
+	private boolean status = true;
+	private String msg;
+	private Object data;
+	private int code;
+
+	public HttpResponseResult(boolean status, int code, Object data, String message) {
+		this.status = status;
+		this.msg = message;
+		this.data = data;
+		this.code = code;
+	}
+
+	public HttpResponseResult() {
+	}
+
+	public int getCode() {
+		return code;
+	}
+
+	public void setCode(int code) {
+		this.code = code;
+	}
+
+	public boolean getStatus() {
+		return status;
+	}
+
+	public void setStatus(boolean status) {
+		this.status = status;
+	}
+
+	public String getMsg() {
+		return msg;
+	}
+
+	public void setMsg(String msg) {
+		this.msg = msg;
+	}
+
+	public Object getData() {
+		return data;
+	}
+
+	public void setData(Object data) {
+		this.data = data;
+	}
+
+	public void success() {
+		this.status = true;
+	}
+
+	public void fail() {
+		this.status = false;
+	}
+
+}

+ 34 - 0
src/main/java/com/ym/mec/collectfee/interceptor/RequestInterceptor.java

@@ -0,0 +1,34 @@
+package com.ym.mec.collectfee.interceptor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.slf4j.MDC;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+
+import com.ym.mec.collectfee.utils.WebUtil;
+
+public class RequestInterceptor extends HandlerInterceptorAdapter {
+
+	private static final String IP = "ip";
+
+	private static final String USERNAME = "username";
+
+	@Override
+	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+
+		String username = "";
+		String userId = "";
+		// 存储userId以及IP
+		MDC.put(USERNAME, username + "@" + userId);
+		MDC.put(IP, WebUtil.getRemoteIp(request));
+
+		return true;
+	}
+
+	@Override
+	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+		MDC.remove(USERNAME);
+		MDC.remove(IP);
+	}
+}

+ 43 - 0
src/main/java/com/ym/mec/collectfee/utils/MobileChecker.java

@@ -0,0 +1,43 @@
+package com.ym.mec.collectfee.utils;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * 检测是否为移动端设备访问
+ * 
+ */
+class MobileChecker {
+
+	// \b 是单词边界(连着的两个(字母字符 与 非字母字符) 之间的逻辑上的间隔),
+	// 字符串在编译时会被转码一次,所以是 "\\b"
+	// \B 是单词内部逻辑间隔(连着的两个字母字符之间的逻辑上的间隔)
+	static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i" + "|windows (phone|ce)|blackberry"
+			+ "|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp" + "|laystation portable)|nokia|fennec|htc[-_]"
+			+ "|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
+	static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser" + "|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
+
+	// 移动设备正则匹配:手机端、平板
+	static Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
+	static Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);
+
+	/**
+	 * 检测是否是移动设备访问
+	 * 
+	 * @param userAgent 浏览器标识
+	 * @return true:移动设备接入,false:pc端接入
+	 */
+	public static boolean check(String userAgent) {
+		if (null == userAgent) {
+			userAgent = "";
+		}
+		// 匹配
+		Matcher matcherPhone = phonePat.matcher(userAgent);
+		Matcher matcherTable = tablePat.matcher(userAgent);
+		if (matcherPhone.find() || matcherTable.find()) {
+			return true;
+		} else {
+			return false;
+		}
+	}
+}

+ 195 - 0
src/main/java/com/ym/mec/collectfee/utils/WebUtil.java

@@ -0,0 +1,195 @@
+/**
+ * WebUtil.java 
+ * Copyright © 2015-2015
+ * 
+ * @author pengdc
+ * @create 2015年7月15日
+ */
+package com.ym.mec.collectfee.utils;
+
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * 
+ */
+public class WebUtil {
+
+	public static String getRandomUUID() {
+		UUID uuid = UUID.randomUUID();
+		String str = uuid.toString();
+		String uuidStr = StringUtils.replace(str, "-", "");
+		return uuidStr;
+	}
+
+	public static void addCookie(String cookieName, String cookeValue, int age, String domain, String path, HttpServletResponse response) {
+		Cookie cookie = new Cookie(cookieName, cookeValue);
+		cookie.setMaxAge(age);// 单位:秒
+		if (StringUtils.isNotBlank(domain)) {
+			cookie.setDomain(domain);
+		}
+		if (StringUtils.isNotBlank(path)) {
+			cookie.setPath(path);
+		}
+		response.addCookie(cookie);
+		// response.addHeader("Set-Cookie", "HttpOnly");// 防止XSS
+	}
+
+	public static String getCookie(String key, HttpServletRequest request) {
+		Cookie[] cookies = request.getCookies();
+		if (cookies != null) {
+			for (Cookie cookie : cookies) {
+				if (cookie.getName().equals(key)) {
+					return cookie.getValue();
+				}
+			}
+		}
+		return null;
+	}
+
+	public static void removeCookie(String key, String domain, String path, HttpServletResponse response) {
+		Cookie cookie = new Cookie(key, null);
+		cookie.setMaxAge(0);
+		cookie.setPath(path);
+		cookie.setDomain(domain);
+		response.addCookie(cookie);
+	}
+
+	/**
+	 * 获取参数
+	 * 
+	 * @param queryString
+	 *            查询字符串
+	 * @param encoding
+	 *            编码格式
+	 * @param name
+	 *            参数名称
+	 * @return 参数
+	 */
+	public static Object getParameter(HttpServletRequest request, String name) {
+		Map<String, Object> parameterMap = getParameterMap(request);
+		return parameterMap.get(name);
+	}
+
+	/**
+	 * 获取所有参数
+	 * 
+	 */
+	@SuppressWarnings("rawtypes")
+	public static Map<String, Object> getParameterMap(HttpServletRequest request) {
+		Map<String, Object> parameterMap = new HashMap<String, Object>();
+		Object object = null;
+		Object[] objs = null;
+		Map params = request.getParameterMap();
+		Enumeration enu = request.getParameterNames();
+		while (enu.hasMoreElements()) {
+			String paraName = (String) enu.nextElement();
+			object = params.get(paraName);
+			if (object != null) {
+				if (object.getClass().isArray()) {
+					objs = (Object[]) object;
+					parameterMap.put(paraName, objs.length == 1 ? objs[0] : objs);
+				} else {
+					parameterMap.put(paraName, object);
+				}
+			}
+		}
+		return parameterMap;
+	}
+
+	/**
+	 * 获取所有Header参数
+	 * 
+	 */
+	@SuppressWarnings("rawtypes")
+	public static Map<String, Object> getHeaderMap(HttpServletRequest request) {
+		Map<String, Object> parameterMap = new HashMap<String, Object>();
+		Enumeration enu = request.getHeaderNames();
+		while (enu.hasMoreElements()) {
+			String paraName = (String) enu.nextElement();
+			Enumeration headerValues = request.getHeaders(paraName);
+			while (headerValues.hasMoreElements()) {
+				parameterMap.put(paraName, headerValues.nextElement());
+			}
+		}
+		return parameterMap;
+	}
+
+	/**
+	 * 获取客户端ip地址
+	 * @param request
+	 * @return
+	 */
+	public static String getRemoteIp(HttpServletRequest request) {
+		String remoteIp = request.getHeader("x-forwarded-for");
+		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
+			remoteIp = request.getHeader("X-Real-IP");
+		}
+		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
+			remoteIp = request.getHeader("Proxy-Client-IP");
+		}
+		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
+			remoteIp = request.getHeader("WL-Proxy-Client-IP");
+		}
+		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
+			remoteIp = request.getHeader("HTTP_CLIENT_IP");
+		}
+		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
+			remoteIp = request.getHeader("HTTP_X_FORWARDED_FOR");
+		}
+		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
+			remoteIp = request.getRemoteAddr();
+		}
+		if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
+			remoteIp = request.getRemoteHost();
+		}
+		if (remoteIp != null && remoteIp.indexOf(",") != -1) {
+			remoteIp = remoteIp.substring(remoteIp.lastIndexOf(",") + 1, remoteIp.length()).trim();
+		}
+		return remoteIp;
+	}
+
+	/**
+	 * 检查访问方式是否为移动端
+	 * @param domain cookie所在的域
+	 * @param request
+	 * @param response
+	 */
+	public static boolean isFromMobile(String domain, HttpServletRequest request, HttpServletResponse response) {
+		boolean isFromMobile = false;
+		String cookieKey = "access_resouce__";
+
+		String accessSource = getCookie(cookieKey, request);
+		// 检查是否已经记录访问方式(移动端或pc端)
+		if (null == accessSource) {
+			try {
+				// 获取ua,用来判断是否为移动端访问
+				String userAgent = request.getHeader("USER-AGENT").toLowerCase();
+				if (null == userAgent) {
+					userAgent = "";
+				}
+				isFromMobile = MobileChecker.check(userAgent);
+
+				// 判断是否为移动端访问
+				if (isFromMobile) {
+					addCookie(cookieKey, "mobile", -1, domain, "/", response);
+				} else {
+					addCookie(cookieKey, "pc", -1, domain, "/", response);
+				}
+			} catch (Exception e) {
+			}
+		} else {
+			isFromMobile = "mobile".equals(accessSource);
+		}
+
+		return isFromMobile;
+	}
+}