JSP第四次作业:使用javabean记录次数的猜数游戏

题目与思想详见第二次作业。

感觉javabean用起来比session方便,毕竟是一个自己定义可以随便使用的java类。

javabean:(guess.java)

package anyi;

public class guess {
	private int num;
	private int tem;
	private int time=1;
	public guess() {
		
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public int getTem() {
		return tem;
	}
	public void setTem(int tem) {
		this.tem = tem;
	}
	public int getTime() {
		return time;
	}
	public void setTime(int time) {
		this.time = time;
	}
}

  

第一个JSP页面:(frist.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="anyi.guess" %>
<jsp:useBean id="p1" class="anyi.guess" scope="session"/>
<!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 name="f1" method="post" action="second.jsp">
		随机数生成成功!范围[1,100],现在开始猜这个数:
		<input	type="text" name="tem">
		<input type="submit" name = "sub" value="确定">
	</form>
	<%
		int num = (int) (Math.random() * 100) + 1;
		p1.setNum(num);
	%>
</body>
</html>

  

第二个JSP页面:(second.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="anyi.guess"%>
<jsp:useBean id="p1" class="anyi.guess" scope="session" />
<!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>
<%request.setCharacterEncoding("utf-8");%>
	<jsp:setProperty name="p1" property="tem" />
	<%
		if (p1.getNum() == p1.getTem()) {
			out.print("恭喜您猜对了!要猜的数是" + p1.getNum() + ",您输入的数是" + p1.getTem() + ",您一共猜了" + p1.getTime() + "次!");
			out.print("<br><br><a href=\"frist.jsp\">欢迎再玩儿一次</a>");
		} else if (p1.getNum() < p1.getTem()) {
			out.print("抱歉,您猜大了!请重新尝试");
	%>
	<br><br>
	<form name="f1" method="post" action="">
		请输入您猜测的数: <input type="text" name="tem"> <input type="submit"
			name="sub" value="确定">
	</form>
	<%
		}
		else {
			out.print("抱歉,您猜小了!请重新尝试");
	%>
	<br><br>
	<form name="f1" method="post" action="">
		请输入您猜测的数: <input type="text" name="tem"> <input type="submit"
			name="sub" value="确定">
	</form>
	<jsp:setProperty name="p1" property="tem" />
	<%
		}
		p1.setTime(p1.getTime() + 1);
	%>
	<jsp:setProperty name="p1" property="tem" />
</body>
</html>

  

posted @ 2021-05-12 13:13  anyiya  阅读(200)  评论(0编辑  收藏  举报