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学习资料的也可以私信我!
祝关注我的人都:身体健康,财源广进,福如东海,寿比南山,早生贵子,从不掉发!
标签:投票系统,Java,项目,request,java,map,import,servlet,javax 来源: https://blog.51cto.com/14623707/2467691