用JSP做一个简单的抽奖页面

    科技2022-09-12  111

    首先写两个jsp文件

    info.jsp
    <body> <% HashMap<String, Integer> scoreMap = (HashMap<String, Integer>)application.getAttribute("scoreMap"); if(scoreMap == null){ scoreMap = new HashMap<String, Integer>(); } String ip = request.getRemoteAddr(); Integer score = scoreMap.get(ip); if (score == null) { score = new Random().nextInt(7) - 1; scoreMap.put(ip, score); } System.out.println(ip + ":" + score); application.setAttribute("scoreMap",scoreMap); request.setAttribute("score", score); request.getRequestDispatcher("draw.jsp").forward(request, response); %> </body> </html>
    draw.jsp
    <body> <% HashMap<String, Integer> scoreMap = (HashMap<String, Integer>) application .getAttribute("scoreMap"); Integer score = (Integer) request.getAttribute("score"); String ip = (String) request.getAttribute("ip"); String msg = ""; if (score != null) { switch (score) { case -1: msg = "祝您下次好运"; break; case 0: msg = "真可惜,差一点就中奖了"; break; case 1: msg = "恭喜您中了五等奖"; break; case 2: msg = "恭喜您中了四等奖"; break; case 3: msg = "恭喜您中了三等奖"; break; case 4: msg = "恭喜您中了二等奖"; break; case 5: msg = "恭喜您中了一等奖"; break; } } %> <form action="info.jsp" method="post"> <input type="submit" value="点击抽奖吧" /> </form> <%=msg%> </body> </html>
    在两个jsp中,draw.jsp中为页面效果,在点击抽奖之后,draw.jsp会向info.jsp发送请求info.jsp会生成一个随机数传给draw.jsp,draw.jsp会根据传回的随机数决定输出内容

    下面为代码效果

    draw.jsp页面的效果

    draw.jsp页面点击之后的效果

    Processed: 0.009, SQL: 10