package com;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.DocumentException;
/**
* * Servlet implementation class WeiXinServlet
*/
public class WeiXinServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WeiXinServlet() {
super();
}
// 接入doGet
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
System.out.println("---------------------111------------");
String signature = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
String nonce = req.getParameter("nonce");
String echostr = req.getParameter("echostr");
System.out.println("---------------------222------------");
PrintWriter out = res.getWriter();
// 校验成功返回echostr
if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
}
/**
* 接收并处理微信客户端发送的请求
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/xml;charset=utf-8");
PrintWriter out = response.getWriter();
try {
Map<String, String> map = MessageUtil.xmlToMap(request);
String toUserName = map.get("ToUserName");
String fromUserName = map.get("FromUserName");
String msgType = map.get("MsgType");
String content = map.get("Content");
String message = null;
if ("text".equals(msgType)) { // 对文本消息进行处理
TextMeaasge text = new TextMeaasge();
text.setFromUserName(toUserName); // 发送和回复是反向的
text.setToUserName(fromUserName);
text.setMsgType("text");
text.setCreateTime(new Date().getTime());
text.setContent("你发送的消息是:" + content);
message = MessageUtil.textMessageToXML(text);
System.out.println(message);
}
out.print(message); // 将回应发送给微信服务器
} catch (DocumentException e) {
e.printStackTrace();
}finally{
out.close();
}
}
}