servlet和jsp交互的第一个典型例子

05.guess.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>



   
    百万富翁数字竞猜游戏  
  
  
  
  	<%
  		//从request域中取出信息
  		String msg = (String)request.getAttribute("msg");
  		if(msg!=null){
  			out.write(""+msg+"");
  		}
  	 %>
  	 <%
  	 	//获取竞猜次数
  	 	Integer times = (Integer)request.getAttribute("times");
  	 	if(times!=null){
  	 		out.write(",你还有"+(5-times)+"次机会!");
  	 	}
  	  %>
  	  
    
请输入30以下的整数:
<% if(times!=null){ %> <% } %>
GuessServlet.java

public class GuessServlet extends HttpServlet {
	//产生一个幸运数字
	int answer;
	
	/**
	 * 新游戏方法。产生一个新的幸运数字
	 */
	public void newGame(){
		Random random = new Random();
		answer = random.nextInt(30);
	}
	
	public GuessServlet(){
		//第一次访问
		newGame();
	}
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		
		//1.接收输入的数字
		String lucyNoStr = request.getParameter("lucyNo");
		System.out.println("答案:"+answer);
		Integer lucyNo = null;
		//2.判断幸运数字和用户的数字
		//2.1 把用户输入的数字转成整数
		if(lucyNoStr!=null || !lucyNoStr.equals("")){
			lucyNo = Integer.parseInt(lucyNoStr);
		}
		
		
		//标记记录当前竞猜的次数
		Integer times = 1;//初始值
		
		//接收客户当前竞猜次数
		String timesStr = request.getParameter("times");
		if(timesStr!=null && !timesStr.equals("")){
			times = Integer.parseInt(timesStr)+1;
		}
		
		
		if(times<5){
			String msg = "";
			//比较
			if(lucyNo>answer){
				//大了
				msg = "可惜,大了点";
			}else if(lucyNo再来一盘");
			return;
		}
		//转发
		request.getRequestDispatcher("/05.guess.jsp").forward(request, response);
	}

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




你可能感兴趣的:(servlet&jsp)