2.第一个小程序(微信公众号开发实战)

项目结构

这里写图片描述

导入jar包:

dom4j-1.6.1.jar
xstream-1.3.1.jar

话不多说,直接上代码。

TextMessage


package com.jiuzhouchedai.po;

public class TextMessage {


    private String ToUserName;  //开发者微信号
    private String FromUserName;    //发送方帐号(一个OpenID)
    private long CreateTime;    //消息创建时间 (整型)
    private String MsgType; //text
    private String Content; //文本消息内容
    private String MsgId;   //消息id,64位整型
    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 long getCreateTime() {
        return CreateTime;
    }
    public void setCreateTime(long 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;
    }


}

weixinServlet

package com.jiuzhouchedai.servlet;

public class weixinServlet extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String  signature=request.getParameter("signature");
        String  timestamp=request.getParameter("timestamp");
        String  nonce=request.getParameter("nonce");
        String  echostr=request.getParameter("echostr");


        PrintWriter out=response.getWriter();
        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
            out.write(echostr);
        }

    }


    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("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)){
                TextMessage  text=new TextMessage();
                text.setFromUserName(toUserName);
                text.setToUserName(fromUserName);
                text.setMsgType("text");
                text.setCreateTime(new Date().getTime());
                text.setContent("您输入的内容为:"+content);
                message=MessageUtil.textMessageToXml(text);
            }
            out.print(message);

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            out.close();
        }



    }


}

CheckUtil

package com.jiuzhouchedai.util;

public class CheckUtil {


    public static final String token="xxxxx";
    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 < j; i++) {
                    byte byte0 = md[i];
                    buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                    buf[k++] = hexDigits[byte0 & 0xf];      
                }
                return new String(buf);
            } catch (Exception e) {
                // TODO: handle exception
                return null;
            }
        }

}

MessageUtil

package com.jiuzhouchedai.util;

public class MessageUtil {

    public static Map<String, String> xmlToMap(HttpServletRequest request) throws Exception{


        Map<String, String> map=new HashMap<String, String>();
        SAXReader reader=new SAXReader();
        InputStream ins = request.getInputStream();

        Document doc = reader.read(ins);

        Element root = doc.getRootElement();
        List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        ins.close();
        return map;



    }

    public static String textMessageToXml(TextMessage textMessage){

        XStream stream=new XStream();
        stream.alias("xml", textMessage.getClass());

        return stream.toXML(textMessage);
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>weixintest</display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>weixinServlet</servlet-name>
    <servlet-class>com.jiuzhouchedai.servlet.weixinServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>weixinServlet</servlet-name>
    <url-pattern>/wx.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值