Java project: voting system
Today, I bring you a small voting system written in java. The code is simple and suitable for beginners to practice!
Code display:
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"); //Set the encoding of the request String item=request.getParameter("item"); //Get votes ServletContext servletContext=request.getSession().getServletContext(); //Get the ServletContext object, which is valid in the application scope Map map=null; if(servletContext.getAttribute("pollResult")!=null){ map=(Map)servletContext.getAttribute("pollResult"); //Get voting results map.put(item,Integer.parseInt(map.get(item).toString())+1); //Add 1 to the current vote }else{ //Initialize a Map collection to save voting information, and set the number of votes for the selected voting items to 1, and the others to 0 String[] arr={"Basic tutorial class","Instance collection class","Experience and skill","Quick reference manual","Case analysis"}; map=new HashMap(); for(int i=0;i<arr.length;i++){ if(item.equals(arr[i])){ //Determine if it is a selected vote map.put(arr[i], 1); }else{ map.put(arr[i], 0); } } } servletContext.setAttribute("pollResult", map); //Save voting results to ServletContext object response.setCharacterEncoding("GBK"); //Set the encoding method of the response. If you do not set the text in the pop-up dialog box, it will be garbled PrintWriter out=response.getWriter(); out.println("<script>alert('Vote successfully!');window.location.href='showResult.jsp';</script>"); }
}
Like this article can pay attention to me, I will continue to update, your attention is my update power! If you need more java learning materials, you can also private me!
I wish all the people who pay attention to me: good health, rich financial resources, good fortune like the East China Sea, long life than Nanshan Mountain, having a baby early and never losing their hair!