需要两个页面,一个jsp页面(guess.jsp)和servlet页面(servlet)。
一.jsp页面
在jsp页面中需要实现:
1.创建随机数并且保存在session中。
2.做个form表单提交猜的数字给servlet页面。
<%@page import="java.util.Random"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="servlet" method="post">
<%
Random random=new Random();
int RN=random.nextInt(100)+1;
session.setAttribute("RN", RN);
%>
有一个1~100的数字,尝试猜到它。<br>
输入你猜的数字:<input type="text" name="gn"><br>
<input type="submit"value="提交">
</form>
</body>
</html>
二.servlet页面
1.获取传来的数字,注意类型转换。
2.比较大小,打印出表单再猜或者猜中结果。
package lh.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*** Servlet implementation class servlet*/
@WebServlet("/servlet")
public class servlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public servlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.getWriter().append("Served at: ").append(request.getContextPath());}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubint guessnumber=Integer.parseInt(request.getParameter("gn"));HttpSession session=request.getSession();int RN=(Integer)session.getAttribute("RN");response.setContentType("text/html; charset=UTF-8");PrintWriter out=response.getWriter();if(guessnumber==RN){out.print("恭喜猜对,随机数为:"+RN);}else if(guessnumber>RN){out.print("猜大了。");out.print("<form action='servlet' method='post'>");out.print("输入你猜的数字:<input type='text'name='gn'>");out.print("<input type='submit'value='提交'>");out.print("</form");}else{out.print("猜小了。");out.print("<form action='servlet' method='post'>");out.print("输入你猜的数字:<input type='text'name='gn'>");out.print("<input type='submit'value='提交'>");out.print("</form");}}}
运行结果: