这个抽奖逻辑是根据成绩而得到的响应的奖励,这里的成绩是随机生成的,不是提前存入数据库的。五道题总分五分,错一道题奖励5遍代码,两道题10遍代码,一次类推,全错25遍代码。
在.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>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
// 接收成绩
Integer score = (Integer) request.getAttribute("score");
int jiSuan = 0;
String present = "";
if (score != null) {
jiSuan = (5 - score) * 5;
present = jiSuan + "";
}
%>
恭喜你,喜提 <%=present%> 遍
<form action="drow" method="post">
<input type="submit" value="抽奖" />
</form>
</body>
</html>
在.jsp文件中,点击抽奖,进入servlet类中,通过全局变量实现一个IP只能得到第一次抽奖的结果,在抽结果根第一次一样的需求。
至于全局变量可以使用application隐式对象完成,这个我忘了咋弄了,等以后想到了在拐回来补吧。
package top.hehongfei.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DrowServlet extends HttpServlet {
// 设置一个全局变量
private static HashMap<String, Integer> scoreMap = new HashMap<String, Integer>();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取客户端(请求中的IP地址)
String ip = request.getRemoteAddr();
// 根据获取的ip查找对应的成绩
Integer score = scoreMap.get(ip);
// 如果查不到,则随机生成
if (score == null) {
Random random = new Random(); // 随机方法
int i = random.nextInt(7);
score = i - 1;
scoreMap.put(ip, score); // 并将ip和对应的成绩存储到全局变量当中去
}
request.setAttribute("score", score);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
运行,点击抽奖,然后会随机获得遍数,这样一个抽奖的逻辑就出来了