spring mvc 接入微信公众平台 注解方式的写法


package com.meiparty.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wechat.model.WeChat;
import com.wechat.service.CoreService;
import com.wechat.util.SignUtil;

/**
* 微信核心 web 入口
*
* @author leson
* @see 用户微信接口的相关接入工作。
*/
@Controller
@RequestMapping("wechat")
public class WeChatController {
private Logger log = Logger.getLogger(WeChatController.class);

/**
* 校验信息是否是从微信服务器发过来的。
*
* @param weChat
* @param out
*/
@RequestMapping(method = { RequestMethod.GET }, produces = "application/json;charset=UTF-8")
public void valid(WeChat weChat, PrintWriter out) {
String signature = weChat.getSignature(); // 微信加密签名
String timestamp = weChat.getTimestamp(); // 时间戳
String nonce = weChat.getNonce();// 随机数
String echostr = weChat.getEchostr();// 随机字符串

// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
} else {
System.out.println("不是微信服务器发来的请求,请小心!");
}
out.flush();
out.close();
}

/**
* 微信消息的处理
*
* @param request
* @param out
* @throws IOException
*/
@RequestMapping(method = { RequestMethod.POST }, produces = "application/xml;charset=UTF-8")
public void dispose(HttpServletRequest request, HttpServletResponse response)
throws IOException {
/* 消息的接收、处理、响应 */

// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");

// 调用核心业务类接收消息、处理消息
String respMessage = CoreService.processRequest(request);
log.info(respMessage);
// 响应消息
PrintWriter out = response.getWriter();
out.print(respMessage);
out.close();
}

}



[img]http://dl2.iteye.com/upload/attachment/0097/4908/d375a0d0-304e-3584-8467-1dd99c3860e1.png[/img]

当然,你也可以将方法上加个路径,只要保证这两个方法,路径一样就行,否则微信服务器是无法给你指定的url 发请求的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值