您好,登錄后才能下訂單哦!
這篇文章主要為大家詳細(xì)介紹了Java制作投票系統(tǒng),文中示例代碼介紹的非常詳細(xì),零基礎(chǔ)也能參考此文章,感興趣的小伙伴們可以參考一下。
代碼展示:
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"); //設(shè)置請求的編碼方式 String item=request.getParameter("item"); //獲取投票項(xiàng) ServletContext servletContext=request.getSession().getServletContext(); //獲取ServletContext對象該對象在application范圍內(nèi)有效 Map map=null; if(servletContext.getAttribute("pollResult")!=null){ map=(Map)servletContext.getAttribute("pollResult"); //獲取投票結(jié)果 map.put(item,Integer.parseInt(map.get(item).toString())+1); //將當(dāng)前的投票項(xiàng)加1 }else{ //初始化一個(gè)保存投票信息的Map集合,并將選定投票項(xiàng)的投票數(shù)設(shè)置為1,其他為0 String[] arr={"基礎(chǔ)教程類","實(shí)例集錦類","經(jīng)驗(yàn)技巧類","速查手冊類","案例剖析類"}; map=new HashMap(); for(int i=0;i<arr.length;i++){ if(item.equals(arr[i])){ //判斷是否為選定的投票項(xiàng) map.put(arr[i], 1); }else{ map.put(arr[i], 0); } } } servletContext.setAttribute("pollResult", map); //保存投票結(jié)果到ServletContext對象中 response.setCharacterEncoding("GBK"); //設(shè)置響應(yīng)的編碼方式,如果不設(shè)置彈出的對話框中的文字將亂碼 PrintWriter out=response.getWriter(); out.println("<script>alert('投票成功!');window.location.href='showResult.jsp';</script>"); }
}
關(guān)于Java制作投票系統(tǒng)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果喜歡這篇文章,不如把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。