jsp+servlet实现猜数字游戏

jsp+servlet实现猜数字游戏主要用到了servlet方面的session,httpservletresponse类中的sendredirect()方法。

step1,客户访问或刷新getnumber.jsp页面时,随机给用户分配一个1-100之间的数字,将该数字存放到客户的session中。

<%@ page language="java" import="java.util.*" 
contenttype="text/html;charset=utf-8"%>
<html>
 <head> 
 </head> 
 <body>
 <%
 string message=(string)session.getattribute("message");
 %>
 <form action="handleguess" methods="post">
  <input type="text" name="guessnumber" size=8>
  <%=message %>
  <input type="submit" value="提交">
  </form>
  <form action="getnumber.jsp" method="post">
  <input type="submit" value="重新得到新的随机数">
  </form>
 </body>
</html>

step2,然后用户超廉价到inputnumber.jsp页面上,用户输入自己的猜测,并提交给handleguess类负责创建。

<%@ page language="java" import="java.util.*" pageencoding="utf-8" 
contenttype="text/html;charset=utf-8"%>
<html>
 <head>
 </head> 
 <body>
 <% session.setattribute("message", "请您猜数");
 // httpsession session =request.getsession(true);
 int randomnumber=(int)(math.random()*100)+1;//获取一个随机数
 session.setattribute("savenumber",new integer(randomnumber));
 %>
 <p>访问或刷新该页面可以随机跌倒一个1,到100之间的数字
 <br>单击下面链接可以访问去猜数字
 <a href="inputnumber.jsp" rel="external nofollow" >去猜数字</a>
 </body>
</html>

step3,该servlet类为:

import java.io.ioexception;
import java.io.printwriter;
 
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
 
public class handleguess extends httpservlet { 
 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(); 
 //获取客户猜测提交的数
 int guessnumber=integer.parseint(request.getparameter("guessnumber"));
 //获取客户的会话对象
 httpsession session=request.getsession();
 integer integer=(integer)session.getattribute("savenumber");
 int realnumber=integer.intvalue();
 system.out.println(realnumber);
 system.out.println(guessnumber);
 if(guessnumber>realnumber){
 session.setattribute("message", "您猜大了");
 system.out.println("您猜大了---no");
 response.sendredirect("inputnumber.jsp");
 }
 else if(guessnumber<realnumber){
 session.setattribute("message", "您猜小了");
 system.out.println("您猜小了---no");
 response.sendredirect("inputnumber.jsp");
 }
 else{
 session.setattribute("message", "您猜对了");
 system.out.println("您猜对了");
 response.sendredirect("inputnumber.jsp");
 }
 }
 public void doget(httpservletrequest request,httpservletresponse response)
  throws servletexception,ioexception{
 dopost(request,response);
 }
 
}

step4,web.xml配置,省略。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持硕编程。

相关文章