This guess digital game mainly uses the servlet Session, the sendredirect () method in the httpservletresponse class.
Step 1: when the customer accesses or refreshes the getnumber. jsp page, the user is randomly allocated a number ranging from 1 to store the number in the customer's session.
<% @ Page Language = "Java" Import = "Java. util. * "contenttype =" text/html; charset = UTF-8 "%> <HTML>
Step 2: The user goes to the inputnumber. jsp page at a low cost. The user enters his own guess and submits it to the handleguess class for creation.
<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "contenttype =" text/html; charset = UTF-8 "%> <HTML>
Step 3, the servlet class is:
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 (); // obtain the number of times the customer guesses to submit int guessnumber = integer. parseint (request. getparameter ("guessnumber"); // obtain the client's Session Object httpsession session = request. getsession (); integer = (integer) session. getattribute ("savenumber"); int realnumber = integer. intvalue (); system. out. println (realnumber); system. out. println (guessnumber); If (guessnumber> realnumber) {session. setattribute ("message", "You guessed it"); system. out. println ("You guessed it was too big --- no"); response. sendredirect ("inputnumber. JSP ");} else if (guessnumber <realnumber) {session. setattribute ("message", "You guessed it"); system. out. println ("you have guessed it --- no"); response. sendredirect ("inputnumber. JSP ");} else {session. setattribute ("message", "You guessed it"); system. out. println ("You guessed it"); response. sendredirect ("inputnumber. JSP ") ;}} public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {dopost (request, response );}}
Step 4: Web. xml configuration, omitted.