Java小項目之:投票系統

Java小項目之:投票系統
今天給你們帶來的是java編寫的投票小系統,代碼簡易,適合初學者練手!
代碼展現:
package com.tarena.wgh.servlet;java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;app

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;jsp

public class PollServlet extends HttpServlet {ide

/**
 * 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學習資料的也能夠私信我!
祝關注個人人都:身體健康,財源廣進,福如東海,壽比南山,早生貴子,從不掉髮!post

相關文章
相關標籤/搜索