微信公众平台深度开发JAVA版第一季 22.微信猜数字活动4

select  count(*) from huo t where t.shuzi='0'

这个SQL语句查不查询得到记录取决于两个条件:第一个是数据库里面有没有这个数字,第二个是getCountByShuZi()是在saveJiLu()方法之后还是之前执行.如果getCountByShuZi()是在saveJiLu()之后执行的话,涉及到数据库事务的问题,就是说你的Connection是不是一个Connection.这个事就越说越多了,就是说你是不是在一个事务里面去执行它.要是getCountByShuZi()在saveJiLu()之后去执行,那么数据库肯定至少会有一条记录.

package net.wxinterface;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.sql.SQLException;
import java.util.Arrays;

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

import net.server.HouServer;
import wx.event.Subscribe_Unsubscribe;
import wx.in.In;
import wx.in.In_Text;
import wx.out.Out_Text;
import wx.util.Util;
@SuppressWarnings("serial")
public class WX_Interface extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public WX_Interface() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//΢�ż���ǩ��,signature����˿�������д��tocken����������е�timestamp����nonce����
		String signature = request.getParameter("signature");
		//ʱ���
		String timestamp = request.getParameter("timestamp");
		//����� 
		String nonce = request.getParameter("nonce");
		
		String echostr = request.getParameter("echostr");
		
		String tocken = "test";
		try{
			if(null != signature){
			String[] ArrTmp = {tocken,timestamp,nonce};	
			Arrays.sort(ArrTmp);
			StringBuffer sb = new StringBuffer();
			for(int i=0;i<ArrTmp.length;i++){
				sb.append(ArrTmp[i]);
			}
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			byte[] bytes = md.digest(new String(sb).getBytes());
			StringBuffer buf = new StringBuffer();
			for(int i=0;i<bytes.length;i++){
				if(((int)bytes[i] & 0xff)<0x10){
					buf.append("0");
				}
				buf.append(Long.toString((int) bytes[i] & 0xff,16));
				
			}
			if(signature.equals(buf.toString())){
				response.getOutputStream().println(echostr);
			}
		}
	}catch(Exception e){
			e.printStackTrace();
		}
		
		System.out.println("test0");

		
		System.out.println("doGet");
		System.out.println("signature     "+signature);
		System.out.println("timstamp      "+timestamp);
		System.out.println("nonce         "+nonce);
		System.out.println("echostr         "+echostr);
		
		
		System.out.println("doGet");
	
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String requestStr = Util.getStringFromRequest(request);
		In in = new In(requestStr);
		System.out.println(in);
		System.out.println(requestStr);
		System.out.println("北风网");
		/**
		 * 关注微信号时的欢迎信息
		 * 欢迎你关注本微信号
		 */
		if("event".equals(in.getMsgType())){//如果接收的消息是事件类型的话
			Subscribe_Unsubscribe subscribe_Unsubscribe = new Subscribe_Unsubscribe(requestStr);
		if("subscribe".equals(subscribe_Unsubscribe.getEvent())){
			//Out_Text out_Text = new Out_Text(in);
			Out_Text out_Text = new Out_Text(subscribe_Unsubscribe);
			out_Text.setContent("欢迎你关注本微信号。本游戏说明");
			out.print(out_Text.getStr());
		}
		//判断是text类型
		}else if("text".equals(in.getMsgType())){					
					//得到文本类型的请求对象.
					In_Text in_Text = new In_Text(requestStr);
					System.out.println(in_Text);
					//得到文本类型的被动响应对象.
					//Out_Text out_Text = new Out_Text(in);
					Out_Text out_Text = new Out_Text(in_Text);
					//out_Text.setContent("这是您选择的数字"+in_Text.getContent());
					
					/*--------------这是验证部分-------start-------------*/
					/*
					 * 需要验证的有:
					 * 必须是数字
					 * 必须在指定的范围内
					 */
					//判断,如果不是数字,抛出异常
					//提示手机用户"这不是数字"
					try {
						Integer.parseInt(in_Text.getContent());
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						//e.printStackTrace();
						out_Text.setContent("这个不是数字");
						System.out.println(out_Text.getStr());
						out.println(out_Text.getStr());
						return;
					}
					//判断,是否小于1000			
					//提示手机用户"这个数字太大了,应该小于1000"
					if(1000<Integer.parseInt(in_Text.getContent())){
						out_Text.setContent("这个数字太大了,应该小于1000");
						System.out.println(out_Text.getStr());
						out.println(out_Text.getStr());
						return;
					}
					/*--------------这是验证部分-------end-------------*/
					/*-------------验证结束--------start---------------------*/
					//记录到数据库
					try {//在Service层里面,这就需要处理异常了,要是这块真有数据库的异常比如说掉网或者是
					//说数据库怎么样怎么着了,要给用户一个提示,不能再随随便便往外抛出异常了,要友好地提示
					HouServer.saveJiLu(in.getFromUserName(),in_Text.getContent());
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				//当SQL执行异常时,给用户提示
				out_Text.setContent("现在用户很踊跃,服务器太累了,您没有参与成功,请继续参与.");
				out.println(out_Text.getStr());
				return;
			}
			/*----------------------记录到数据库-----------end------------------*/		
			
			/*----------------------查询数据库,得到这个数字在数据库中的个数-------start--------------------------------------------*/
					String str = "";
					try {
						str = HouServer.getCountByShuZi(in_Text.getContent());
						out_Text.setContent("成功,"+in_Text.getContent()+"已经有"+str+"次被猜中了。");
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						out_Text.setContent("现在用户很踊跃,服务器太累了,您没有参与成功,请继续参与.");
						e.printStackTrace();
					}
					//out_Text.setContent("成功,"+in_Text.getContent()+"已经有"+str+"次被猜中了。");
					System.out.println(out_Text.getStr());
			out.print(out_Text.getStr());
			/*-----------查询数据库-----------------------end--------------------------------*/
					}else{
			Out_Text out_Text = new Out_Text(in);
			out_Text.setContent("请选择一个数字");
			out.print(out_Text.getStr());
			
		}
		
		out.flush();
		out.close();
		System.out.println("ok");
	}

}
package wx.out;

import java.util.Date;

import wx.in.In;

public class Out_Text {
	private String ToUserName = null;//	是	接收方帐号(收到的OpenID)
	private String FromUserName = null;//	是	开发者微信号
	private String CreateTime = null;//	是	消息创建时间 (整型)
	private String MsgType =null;//	 是	text
	private String Content = null;//	是	回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)
	StringBuffer strb = new StringBuffer();
	StringBuffer strb_ = new StringBuffer();
	public Out_Text(In in) {
	//public Out_Text(In in,String str) {
		super();
		// TODO Auto-generated constructor stub
		Date date = new Date();

		strb.append("             <ToUserName><![CDATA["+in.getFromUserName()+"]]></ToUserName>                   ");
		strb.append("         <FromUserName><![CDATA["+in.getToUserName()+"]]></FromUserName>                       ");
		strb.append("         <CreateTime>"+date.getTime()+"</CreateTime>                       ");
		strb.append("          <MsgType><![CDATA[text]]></MsgType>   ");
	    //this.setContent(str);
	}

	//public String getStr(String str){
	public String getStr(){

		strb_.append("           <xml>                     ");    
		strb_.append(strb);
		//strb_.append("            <Content><![CDATA["+str+"]]></Content>                    ");
		strb_.append("            <Content><![CDATA["+this.getContent()+"]]></Content>                    ");
		strb_.append("            </xml>                    ");
		return strb_.toString();

		
	}
	
	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;
	}

	@Override
	public String toString() {
		return "Out_Text []"+strb_;
	}
	
	
	
}
package wx.event;

import java.util.Date;

import wx.in.In;
import wx.util.Util;



public class Subscribe_Unsubscribe extends In{
/*	private String ToUserName =null;//	开发者微信号
	private String FromUserName = null;//	发送方帐号(一个OpenID)
	private String CreateTime = null;//	消息创建时间 (整型)
	private String MsgType = null;//	消息类型,event
*/	private String Event = null;//	事件类型,subscribe(订阅)、unsubscribe(取消订阅)
	
	
	
	public Subscribe_Unsubscribe() {
		super();
	}
	public Subscribe_Unsubscribe(String requestStr) {
		Date date = new Date();	
		this.setToUserName(Util.getStrByXML(requestStr,"ToUserName"));
		this.setFromUserName(Util.getStrByXML(requestStr,"FromUserName"));
		this.setCreateTime(date.getTime()+"");
		//this.setCreateTime(String.valueOf(date.getTime()));
		//this.setMsgType("MsgType");
        this.setCreateTime(Util.getStrByXML(requestStr,"CreateTime"));
        this.setMsgType(Util.getStrByXML(requestStr,"MsgType"));
		this.setEvent(Util.getStrByXML(requestStr,"Event"));
		//this.setEvent("event");
	}
	/*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 getEvent() {
		return Event;
	}
	public void setEvent(String event) {
		Event = event;
	}
	@Override
	public String toString() {
		return "Subscribe_Unsubscribe [Event=" + Event + "]";
	}
	
	
}
package net.server;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import net.db.DBUtil;

public class HouServer {
	/**
	 * 保存记录
	 * @param openid
	 * @param shuzi
	 * @throws SQLException 
	 */
    public static void saveJiLu(String openid,String shuzi) throws SQLException{//Server层的异常推荐使用向外抛出异常的方式.
    	//因为你要通知外面这个Server执行的有错误.
    	Connection conn = DBUtil.getConn();
    	Statement stmt = conn.createStatement();
    	//conn.prepareStatement(sql);//PrepareStatement是预编译/预处理,Statement就不行了
    	//Statement是PrepareSatement的父类/父接口.
    	String sql = "insert into huo (openid,shuzi) values ('"+openid+"','"+shuzi+"');";
    	//String sql = "insert into huo (openid,shuzi) values ('"+openid+"','"+shuzi+"')";
    	stmt.executeUpdate(sql);
    	if(null!=stmt){
    		stmt.close();
    	}
    	//关Connection涉及到一个数据源的问题.数据源/连接池,什么时候是真关闭(物理关闭),什么时候是逻辑关闭
    	//有人会用自己开发的数据源对Connection进行管理.关于数据库操作这一部分求职的时候会很容易被问到.
    	if(null!=conn){
    		conn.close();
    	}
    }
    /**
     * 根据数字查询数据库.得到这个数字在数据库中的个数。
     * @param shuZi
     * @return
     * @throws SQLException
     */
    public static String getCountByShuZi(String shuZi) throws SQLException{
    	String str = "";
    	/*得到Connection*/
    	Connection conn = DBUtil.getConn();
    	/*得到Statement*/
    	Statement stmt = conn.createStatement();
    	
    	String sql = "select  count(*) count_ from huo t where t.shuzi='"+shuZi+"'";
		//依赖注入的事,可能是拼接一个字符串
    	/*得到ResultSet*/
    	ResultSet rs = stmt.executeQuery(sql);
    	if(rs.next()){
    		str = rs.getString("count_");
    	}
    	
    	
    	/*关闭rs*/
    	if(null != rs){
    		rs.close();
    	}
    	/*关闭stmt*/
    	if(null != stmt){
    		stmt.close();
    	}
    	/*关闭conn*/
    	if(null != conn){
    		conn.close();
    	}
    	return str;
    	
    }
}

 

转载于:https://my.oschina.net/u/3206447/blog/906531

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值