使用一个最笨的办法就是多设置几个全局变量通过对比是微信端发出的第二次请求无效
直接上代码了
@Controller
public class CoreController {
@Autowired
CoreService coreService;
@Value("${projecturl}")
String projecturl;
String openId = null;
String bleancode="false";
// 第三方用户唯一凭证
@Value("${appId}")
String appId;
// 第三方用户唯一凭证密钥
@Value("${appSecret}")
String appSecret;
// 模板id
@Value("${TemplateId}")
String templateId;
// 通知url
@Value("${tzurl}")
String tzurl;
@Value("${mydb}")
String mydb;
// 增加日志
private static Logger log = LoggerFactory.getLogger(CoreController.class);
// 验证是否来自微信服务器的消息
@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public String checkSignature(@RequestParam(name = "signature", required = false) String signature,
@RequestParam(name = "nonce", required = false) String nonce,
@RequestParam(name = "timestamp", required = false) String timestamp,
@RequestParam(name = "echostr", required = false) String echostr) {
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
log.info("接入成功");
return echostr;
}
log.error("接入失败");
return "";
}
// 调用核心业务类接收消息、处理消息跟推送消息
@RequestMapping(value = "/", method = RequestMethod.POST)
@ResponseBody
public String post(HttpServletRequest req) throws UnsupportedEncodingException {
req.setCharacterEncoding("UTF-8");
req.setCharacterEncoding("UTF-8");
String respMessage = coreService.processRequest(req);
return respMessage;
}
@RequestMapping({ "/oath" })
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// 用户同意授权后,能获取到code
String code = request.getParameter("code");
if (bleancode.equals("false")||(!bleancode.equals(code))) {
bleancode=code;
// 用户同意授权
if (!"authdeny".equals(code)) {
// 获取网页授权access_token
WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(appId, appSecret, code);
// 用户标识
openId = weixinOauth2Token.getOpenId();
System.out.println(openId);
}
}
if (coreService.isuser(openId).size()>0) {
response.sendRedirect(projecturl + "&openid=" + openId);
return;
} else {
request.getRequestDispatcher("/xmbd?openid=" + openId).forward(request, response);
}
}