Java小項目之:投票系統


Java小項目之:投票系統

今天給大家帶來的是java編寫的投票小系統,代碼簡易,適合初學者練手!

代碼展示:

package com.tarena.wgh.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.*;

 

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class PollServlet extends HttpServlet {

 

/**

 * The doPost method of the servlet. <br>

 *

 * This method is called when a form has its tag value method equals to post.

 *

 * @param request the request send by the client to the server

 * @param response the response send by the server to the client

 * @throws ServletException if an error occurred

 * @throws IOException if an error occurred

 */

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setCharacterEncoding("GBK"); //設置請求的編碼方式

String item=request.getParameter("item"); //獲取投票項

ServletContext servletContext=request.getSession().getServletContext(); //獲取ServletContext對象該對象在application范圍內有效

Map map=null;

if(servletContext.getAttribute("pollResult")!=null){

map=(Map)servletContext.getAttribute("pollResult"); //獲取投票結果

map.put(item,Integer.parseInt(map.get(item).toString())+1); //將當前的投票項加1

}else{ //初始化一個保存投票信息的Map集合,並將選定投票項的投票數設置為1,其他為0

String[] arr={"基礎教程類","實例集錦類","經驗技巧類","速查手冊類","案例剖析類"};

map=new HashMap();

for(int i=0;i<arr.length;i++){

if(item.equals(arr[i])){ //判斷是否為選定的投票項

map.put(arr[i], 1);

}else{

map.put(arr[i], 0);

}

}

}

servletContext.setAttribute("pollResult", map); //保存投票結果到ServletContext對象中

response.setCharacterEncoding("GBK"); //設置響應的編碼方式,如果不設置彈出的對話框中的文字將亂碼

PrintWriter out=response.getWriter();

out.println("<script>alert('投票成功!');window.location.href='showResult.jsp';</script>");

 

}

 

}

喜歡這樣文章的可以關注我,我會持續更新,你們的關注是我更新的動力!需要更多java學習資料的也可以私信我!

祝關注我的人都:身體健康,財源廣進,福如東海,壽比南山,早生貴子,從不掉發!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM