主题:[讨论]急等
怎么样用jsp和servlet想结合 根据下面的代码做个简单的 投票小系统 要求:能动态添加和删除候选人的名字:
package vote;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Vote extends HttpServlet{
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
PrintWriter out = res.getWriter();
//通过Cookie判断用户是否投过票
Cookie[] cookies = req.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
//投过票的用户不允许再投
if(cookies[i].getName().equals("voted")){
out.println("You have already voted!");
return;
}
}
}
//执行投票逻辑
String candidate = req.getParameter("c");
ServletContext sc = getServletConfig().getServletContext();
doVote(candidate,sc);
//标识用户已投票,重定向到结果页面
Cookie voted = new Cookie("voted","1");
voted.setMaxAge(60*10);
res.addCookie(voted);
res.sendRedirect("/unit11/result.jsp");
}
private void doVote(String c,ServletContext sc){
VoteBox vb = (VoteBox)sc.getAttribute(c);
if(vb==null){
vb = new VoteBox();
vb.insert();
sc.setAttribute(c,vb);
}else{
vb.insert();
}
}
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
doGet(req,res);
}
}
-----------------------------------------------------
package vote;
public class VoteBox{
private int total = 0;
public synchronized void insert(){
total++;
}
public int getTotal(){
return total;
}
}
可否 把代码附上啊 急等!
package vote;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Vote extends HttpServlet{
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
PrintWriter out = res.getWriter();
//通过Cookie判断用户是否投过票
Cookie[] cookies = req.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
//投过票的用户不允许再投
if(cookies[i].getName().equals("voted")){
out.println("You have already voted!");
return;
}
}
}
//执行投票逻辑
String candidate = req.getParameter("c");
ServletContext sc = getServletConfig().getServletContext();
doVote(candidate,sc);
//标识用户已投票,重定向到结果页面
Cookie voted = new Cookie("voted","1");
voted.setMaxAge(60*10);
res.addCookie(voted);
res.sendRedirect("/unit11/result.jsp");
}
private void doVote(String c,ServletContext sc){
VoteBox vb = (VoteBox)sc.getAttribute(c);
if(vb==null){
vb = new VoteBox();
vb.insert();
sc.setAttribute(c,vb);
}else{
vb.insert();
}
}
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
doGet(req,res);
}
}
-----------------------------------------------------
package vote;
public class VoteBox{
private int total = 0;
public synchronized void insert(){
total++;
}
public int getTotal(){
return total;
}
}
可否 把代码附上啊 急等!