项目结构:
/Weixin/src/com/imooc/po/TextMessage.java
package com.imooc.po;
public class TextMessage {
private String ToUserName;
private String FromUserName;
private String CreateTime;
private String MsgType;
private String Content;
private String MsgId;
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public String getCreateTime() {
return CreateTime;
}
public void setCreateTime(String createTime) {
CreateTime = createTime;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String msgType) {
MsgType = msgType;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getMsgId() {
return MsgId;
}
public void setMsgId(String msgId) {
MsgId = msgId;
}
}
/Weixin/src/com/imooc/servlet/WeixinServlet.java
package com.imooc.servlet;
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;
import com.imooc.po.TextMessage;
import com.imooc.util.CheckUtil;
import com.imooc.util.MessageUtil;
public class WeixinServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String signature = req.getParameter("signature");
String timestamp = req.getParameter("timestamp");
String nonce = req.getParameter("nonce");
String echostr = req.getParameter("echostr"); //随机字符串
PrintWriter out = resp.getWriter();
if(CheckUtil.checkSignature(signature, timestamp, nonce)){
out.print(echostr);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
try {
Map map = MessageUtil.xmlToMap(req);
String fromUserName = map.get("FromUserName");
String toUserName = map.get("ToUserName");
String msgType = map.get("MsgType");
String content = map.get("Content");
String message = null;
if(MessageUtil.MESSAGE_TEXT.equals(msgType)){
if("1".equals(content)){
message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.firstMenu());
}else if("2".equals(content)){
message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.secondMenu());
}else if("?".equals(content) || "?".equals(content)){
message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
}else{
message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.doubushi());
}
System.out.println(message);
}else if(MessageUtil.MESSAGE_EVENT.equals(msgType)){
String eventType = map.get("Event");
if(MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)){
message = MessageUtil.initText(toUserName, fromUserName, MessageUtil.menuText());
}
}
out.print(message);
} catch (DocumentException e) {
e.printStackTrace();
}finally{
out.close();
}
}
}
/Weixin/src/com/imooc/util/CheckUtil.java
package com.imooc.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class CheckUtil {
private static final String token = "imooc";
public static boolean checkSignature(String signature,String timestamp,String nonce){
String[] arr = new String[]{token,timestamp,nonce};
//排序
Arrays.sort(arr);
//生成字符串
StringBuffer content = new StringBuffer();
for(int i=0;i < arr.length; i++){
content.append(arr[i]);
}
// sha1加密
String temp = getSha1(content.toString());
return temp.equals(signature);
}
public static String getSha1(String str){
if(str == null || str.length() == 0){
return null;
}
char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j*2];
int k = 0;
for(int i=0;i>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
}catch(Exception e){
return null;
}
}
}
/Weixin/src/com/imooc/util/MessageUtil.java
package com.imooc.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.imooc.po.TextMessage;
import com.thoughtworks.xstream.XStream;
public class MessageUtil {
public static final String MESSAGE_TEXT = "text";
public static final String MESSAGE_IMAGE = "image";
public static final String MESSAGE_VOICE = "voice";
public static final String MESSAGE_VIDEO = "video";
public static final String MESSAGE_LINK = "link";
public static final String MESSAGE_LOCATION = "location";
public static final String MESSAGE_EVENT = "event";
public static final String MESSAGE_SUBSCRIBE = "subscribe";
public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
public static final String MESSAGE_CLICK = "CLICK";
public static final String MESSAGE_VIEW = "VIEW";
/**
* xml 转 map
* @param request
* @return
* @throws IOException
* @throws DocumentException
*/
public static Map xmlToMap(HttpServletRequest request) throws IOException, DocumentException{
Map map = new HashMap();
SAXReader reader = new SAXReader();
//从 request中获取输入流
InputStream ins = request.getInputStream();
Document doc = reader.read(ins);
Element root = doc.getRootElement();
List list = root.elements();
for(Element e:list){
map.put(e.getName(), e.getText());
}
ins.close();
return map;
}
public static String textMessageToXml(TextMessage textMessage){
XStream xstream = new XStream();
xstream.alias("xml", textMessage.getClass());
return xstream.toXML(textMessage);
}
public static String initText(String toUserName,String fromUserName,String content){
TextMessage text = new TextMessage();
text.setFromUserName(toUserName);
text.setToUserName(fromUserName);
text.setMsgType(MessageUtil.MESSAGE_TEXT);
text.setCreateTime(String.valueOf(new Date().getTime()));
text.setContent(content);
return textMessageToXml(text);
}
/**
* 主菜单
* @return
*/
public static String menuText(){
StringBuffer sb = new StringBuffer();
sb.append("欢迎你的关注,请按照菜单提示进行操作:\n\n");
sb.append("1.课程介绍\n");
sb.append("2. 慕课网介绍\n");
sb.append("回复 ? 调出 此菜单...");
return sb.toString();
}
public static String firstMenu(){
StringBuffer sb = new StringBuffer();
sb.append("介绍微信公众号开发");
return sb.toString();
}
public static String secondMenu(){
StringBuffer sb = new StringBuffer();
sb.append("222222222");
return sb.toString();
}
public static String doubushi(){
StringBuffer sb = new StringBuffer();
sb.append("哈哈,都不是");
return sb.toString();
}
}
/Weixin/WebContent/WEB-INF/web.xml
Weixin
weixinServlet
com.imooc.servlet.WeixinServlet
weixinServlet
/wx.do
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp