在interceptor包下创建ApiInterceptor和WebConfig
ApiInterceptor
``` package com.media.weappapi.interceptor;
import com.media.common.po.config.TCmsSite;
import com.media.common.util.MD5Util;
import com.media.common.util.MsgUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.Map.Entry;
@Component
public class ApiInterceptor implements HandlerInterceptor {
private static Logger logger = LoggerFactory.getLogger(ApiInterceptor.class);
public static final String SIGNATURE = "signature";
public static final String SITEID = "siteId";
public static final String APISIGN = "apiSign";
private Map<String,String> apiSignMap = new HashMap<String, String>();
{
apiSignMap.put(SITEID, APISIGN);
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//开发者模式时runType参数添加test不进行拦截
if ("test".equals(request.getParameter("runType"))) {
return true;
}
logger.info("—————————————————进入拦截模式————————————————————————————");
//判断是否是文件上传,文件上传的请求不拦截
// String contentType=request.getHeader("Content-Type");
// logger.info("contentType:"+contentType);
// if(StringUtils.isNotBlank(contentType) && contentType.startsWith("multipart")){
// return true;
// }
String signature = request.getParameter(SIGNATURE);
logger.info(request.toString()+"\t" +"signature:"+"\t"+signature);
logger.info(request.toString()+"\t" +"url:"+"\t"+request.getRequestURI());
String siteId = request.getParameter("siteId");
String currentTimeMillis = request.getParameter("currentTimeMillis");
if (StringUtils.isBlank(siteId)) {
response.getWriter().println(MsgUtil.fail("站点id不能为空"));
return false;
}
if (StringUtils.isBlank(currentTimeMillis)) {
response.getWriter().println(MsgUtil.fail("时间戳不能为空"));
return false;
}
// 判断签名是否正确
StringBuffer sbf = new StringBuffer();
sbf.append(siteId);
sbf.append(currentTimeMillis);
logger.info("paramList加密前参数:" + sbf.toString());
String createSign = MD5Util.getMD5String(sbf.toString());
logger.info("paramList加密后:" + createSign);
if(!(signature.equals(createSign))){
logger.info(MsgUtil.fail("签名错误"));
response.getWriter().append(MsgUtil.fail("签名错误"));
}else{
logger.info(MsgUtil.success("签名正确"));
}
return (signature.equals(createSign));
}
}
、、、