springmvc-servlet.xml
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/my/*"/>
<bean class="com.xxx.web.interceptor.AuthInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/op/*"/>
<bean class="com.xxx.web.interceptor.OpenApiInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/news/*/newsDetail.htm"/>
<bean class="com.xxx.web.interceptor.MobileInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
public class OpenApiInterceptor extends HandlerInterceptorAdapter {
private static Logger log = LoggerFactory.getLogger(OpenApiInterceptor.class);
@Value("${permissionIp}")
private String permissionIp;
/**
* 最后执行,可用于释放资源
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
super.afterCompletion(request, response, handler, ex);
}
/**
* 显示视图前执行
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
/**
* Controller之前执行
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 请求的路径
// String contextPath = request.getContextPath();
String remoteUrl = request.getRequestURI().toString();
if (remoteUrl.endsWith("getStock.htm")) {
return true;
}
String queryString = request.getQueryString();
String remoteCid = request.getParameter("cid");
// HttpSession session = request.getSession();
String remoteIP = getRemoteIP(request);
List<String> filterIPs = getPermissionIp();
if (StringUtils.isEmpty(remoteCid)) {
log.error("remote cid is empty. remoteIP:[{}]", remoteIP);
writeResponse(response, "01", "remote cid is empty");
return false;
}
log.error("request openAPI,remoteCid:[" + remoteCid + "],remoteIP:[{}],remoteUrl:[{}],queryString:["
+ queryString + "]", remoteIP, remoteUrl);
if (filterIPs.isEmpty() || contains(filterIPs, remoteIP)) {
return true;
} else {
log.error("Invalid remote IP. remoteIP:[{}]", remoteIP);
writeResponse(response, "02", "Invalid remote IP");
}
return false;
}
private void writeResponse(HttpServletResponse resp, String retCode, String result) throws IOException {
resp.getOutputStream().write(
("{\"retCode\":" + "\"" + retCode + "\"" + ",\"retMsg\":" + "\"" + result + "\"" + "}")
.getBytes("UTF-8"));
resp.flushBuffer();
}
private List<String> getPermissionIp() {
List<String> result = new ArrayList<String>();
if (!StringUtils.isEmpty(permissionIp)) {
if (permissionIp.indexOf(",") != -1) {
String[] ip = permissionIp.split(",");
for (int i = 0, len = ip.length; i < len; i++) {
if (!StringUtils.isEmpty(ip[i])) {
result.add(ip[i]);
}
}
}
}
return result;
}
private boolean contains(List<String> list, String remoteIP) {
for (String ip : list) {
if (ip.indexOf("*") > 0) {
int end = ip.indexOf("*");
if (remoteIP.startsWith(ip.substring(0, end))) {
return true;
}
} else if (ip.equals(remoteIP)) {
return true;
}
}
return false;
}
private String getRemoteIP(HttpServletRequest req) {
String ip = req.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = req.getRemoteAddr();
// 这里主要是获取本机的ip,可有可无
if (ip.equals("127.0.0.1") || ip.endsWith("0:0:0:0:0:0:1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
log.error("获取IP异常", e);
}
ip = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ip != null && ip.length() > 15) { // "***.***.***.***".length()
// = 15
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}
}