利用jsp/servlet/Ajax,实现一个猜数字游戏!

源码:

http://download.csdn.net/detail/m1872216/4651239

Ajax的局部刷新:

input.jsp

 

 

<body>
  <div id="msg" style="color:red"></div>
 
  <form action="login.do" method="post" name="form1" οnsubmit="return onClick()">
  <table border="1">
  <tr>
  <td>
  设置数字:
  </td>
  <td>
  <input type="text" name="num"/>
  </td>
  </tr>
  <tr>
  <td colspan="2">
  <input type="submit" value="提交"/>
  </td>
  </tr>
  </table>
  </form>
  <script type="text/javascript" src="js/myAjax.js"></script>
   <script type="text/javascript">
   function onClick(){
    var num=document.form1.num.value;
    var params="num="+num;
    ajaxPost("login.do",params,function(txt){
    document.getElementById("msg").innerHTML=txt;
    });
  
  return false;
  }
   </script>
 </body>

 

 

servlet:

@Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  
  doPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  //String count=request.getParameter("count");
  response.setContentType("text/html;charset=utf-8");
  HttpSession session=request.getSession();
  //访问的次数
       if(session.getAttribute("times")==null){
        Random rd=new Random();
      int  count=rd.nextInt(10);
       System.out.println(count);
     session.setAttribute("count", count);
     session.setAttribute("times", 0);
       }
      
       ///
       if((Integer)session.getAttribute("times")==0){
        int times=(Integer)session.getAttribute("times");
        session.setAttribute("times", times+1);//初次访问
        showResult(request,response);
       
       }else{
        showResult(request,response);
       }
  
  
 }

 public void showResult(HttpServletRequest request, HttpServletResponse response) throws IOException {
  response.setContentType("text/html;charset=utf-8");
  PrintWriter out=response.getWriter();
  HttpSession session=request.getSession();
  
  //获取访问的第几次
     int times=(Integer)session.getAttribute("times");
    
     //获取客户端提交的数据
    int num=0;
     try{
     num=Integer.parseInt(request.getParameter("num"));
     }catch(NumberFormatException ne){
     out.println("非法输入");
     return;
     }
    
    
     //获取随机数
     int realnum=(Integer)session.getAttribute("count");
    
     if(num>realnum){
   out.println("再小一点");
   session.setAttribute("times", times+1);
  }else if(num<realnum){
   out.println("再大一点");
   session.setAttribute("times", times+1);
  }else{
   times=(Integer)session.getAttribute("times");
   out.println("答对了,花了"+times+"次");
   session.removeAttribute("times");
  }
    
 }
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值