java投票系統源碼
㈠ java語言中用於投票器的代碼如何寫
把投票的信息放在 ServletContext對象 中。也就是 JSP 內置對象中的application對象。因為投票信息是所有用戶都要看的信息,所以要把他放在 ServletContext對象 中。這樣只要是 應用一載入就會創建 ServletContext對象 直到應用銷毀,也就是伺服器關閉時,ServletContext對象 才銷毀。這樣就使得所有用戶公用一個對象存儲信息。具體的實現那要根據你自己的需求,具體設計。
public class CServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {int n = 0;ServletContext application = getServletContext();Integer num = (Integer) application.getAttribute("num");if (num != null) {n = num;}application.setAttribute("num", ++n);response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();out.println("你是第" + n + "個訪問者");}}
上面是個類似的例子。你可以參考一下。package servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;這是需要導入的包
