用Java结合Jsp写了一个抽奖小程序 , 分享给大家

    科技2025-09-26  56

    网上抽奖我们都经常用,回顾servlet, 顺手写了一个抽奖的小程序 ,稍加改动 来个亲朋好友抽奖大比拼还是不错滴 我把源码放出来大家参考一下

    //创建私有的集合 用于存储随机数 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地址判定是否已经抽过; //获取客户端IP地址 String ip = request.getRemoteAddr(); Integer score = scoreMap.get(ip); if(score!=null){ //你已经抽过了 }else{ //你是第一次进来,我会给你生成一个随机数; Random random = new Random(); //new一个随机数 int i = random.nextInt(6); //我们设定随机数的长度自定义 score = i; scoreMap.put(ip, score); //把IP和对应IP生成的随机数存到键值对里 } request.setAttribute("score", score); request.getRequestDispatcher("index.jsp").forward(request, response);

    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"); String msg = ""; if(score != null){ switch(score){ case 0 : msg = "恭喜你,中笔记本电脑一台!"; break; case 1 : msg = "恭喜你,中IPhone11一台!"; break; case 2 : msg = "恭喜你,中天猫500¥代金券"; break; case 3 : msg = "恭喜你 ,中腾讯视频VIP一个月"; break; case 4 : msg = "感谢您的参与!"; break; } } out.println(msg); %> <form action="gameServlet" method="post"> <input type="submit" value="抽奖"/> </form> </body> </html>

    另外说明哈 , 网上的抽奖活动仅供娱乐 , 谁要是当真谁就输了 , 因为赢家永远都是程序猿哥哥们… 简单娱乐 稍加美化效果更好, 如有错误请各位大神指教 .

    Processed: 0.013, SQL: 8