JSP和servlet结合案例

【使用JSP技术实现猜数字游戏】

设计一个web app,有一个随机数字,给5次机会让客户猜测这个数字:

1)如果客户猜的数字比产生的数字值大,则提示“可惜,大了点”。

2)如果客户猜的数字比产生的数字值小,则提示“可惜,小了点”

猜对了给出相对应的提示


 

对于应的代码

首先是jsp页面(主要是处理逻辑)

<%@page language="java" import="java.util.*" pageEncoding="UTF-8"%>
	<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
	<html>
<head>
<base href="<%=basePath%>">
<title>猜数字游戏</title>

</head>
<body>
	<%
    			String value=(String)request.getAttribute("answer");
    			Integer times = (Integer)request.getAttribute("times");
  	 			
        %>
	<i><h1>请猜猜这个数字</h1>
	<hr>
	<form action="<%=request.getContextPath()%>/GuessServlet" method="post">

		<input type="text" name="number"> <input type="submit"
			value="确定">
		<%
    		if(times!=null){
    	       %>
		<input type="hidden" name="times" value="<%=times %>" />
		<%
    		if(value.equals("=")){
    			out.print("<p style='color:green'>啦啦啦,恭喜你答对啦,");
    		}else{
    			out.print("<p style='color:red'>你还有"+(5-times)+"次机会!同时你猜的有点"+value);
    		}
    	
    	       %></p>
		<%
    	}
    	 %>
	</form> </i>
</body>
	</html>

  然后就是servlet的代码:

package com.gqx.work;

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;

public class GuessServlet extends HttpServlet {

	/**
	 * 产生一个随机的数字(666),给5次机会让客户猜测这个数字
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String num=request.getParameter("number");
		Integer time=1;
		String times=request.getParameter("times");
		String value="";
		int key;
		System.out.println(times);
		if (times !=null  &&  !times.equals("")) {
				time=Integer.parseInt(times)+1;
		}
		if (num=="" || num==null) {
			value="请填入数字";
		}else {
			key=Integer.parseInt(num);
			if (key==666) {
				value="=";
			}else if (key>666) {
				value="大";
			}else {
				value="小";
			}
			request.setAttribute("answer", value);
		}

		if (time>4) {
			response.getWriter().write("游戏结束,<a href='"+request.getContextPath()+"/work1/guess.jsp'>再来一局</a>");
			return;
		}
		request.setAttribute("times", time);
		request.getRequestDispatcher("work1/guess.jsp").forward(request, response);
	

	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}

  运行的截图;

 

posted @ 2016-11-10 20:21  晓乎  阅读(1051)  评论(0编辑  收藏  举报
总访问: counter for blog 次