你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

j2ee实现猜数游戏(网页版)

2021-11-28 8:51:47

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
</head>
<body>
<h1>猜数游戏</h1>
    <form action="guess.jsp" method="post" onsubmit="return check()">
        <input type="text" name="name" id="name">
        <input type="submit" name="submit" value="猜数">
        <input type="reset" name="reset" value="reset">
    </form>
    <script>
        function check() {
            var num = document.getElementById("name").value;
            if (num >= 0 && num <= 100) {
                return true;
            }
            alert("数不对");
            return false;
        }
    </script>
</body>
</html>

guess.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%
        if (session.getAttribute("randNum")==null){
            Integer randNum=(int) (Math.random()*100);
            session.setAttribute("randNum", randNum);
        }
        if (request.getParameter("name")!=null){
            int randNum=(Integer) session.getAttribute("randNum");
            Integer i1=Integer.valueOf(request.getParameter("name"));
            if (i1<randNum){
                out.print("猜小了");
            }
            else if (i1>randNum){
                out.print("猜大了");
            }else {
                out.print("猜对了");
                session.removeAttribute("randNum");
            }
            out.println("<a href=index.jsp>再来一次</a>");
        }
        else
        {
//            request.getAttribute()
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    %>
</body>
</html>