⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 votecounter.java

📁 对于初学者来说..是应该理解下了..我说的是JSP哦
💻 JAVA
字号:
// VoteCounter.java
// This servlet processes the ballot form, returning a 
// page asking for a new vote if no vote was made on the
// ballot. For legitimate ballots, the vote is added to
// the current totals, and those totals are presented to
// the user in a return page.
//  A cookie is returned to the voter, recording the fact
//  that a vote was received. The servlet examines all votes
//  for cookies to ensure that there is no multiple voting.
//  The voting data file, votesdat.dat, is stored on the Web
//  server.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class VoteCounter extends HttpServlet {
    Cookie cookies[] = null;
    int index;
    PrintWriter servletOut;

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException {

        Cookie newCookie;
        int votes[] = null;
        String vote;
        File votesdat = new File("votesdat.dat");
        String candidates[] = {"Daren Dogman", "Timmy Taildragger",
                               "Don Dogpile"};

// Get cookies from the request

        cookies = request.getCookies();
// Check to see if there was a vote on the form

        vote = request.getParameter("vote");
        if (vote == null) {  // There was no vote

// Create the return page

            makeHeader(response);
            servletOut.println(
            "You submitted a ballot with no vote marked <br />");
            servletOut.println(
                "Please mark the ballot and resubmit");
        }       // end of if (vote == null)...

        else {  // There was a vote

// Check to see if this client voted before

            if (!votedBefore()) {  

// No previous vote, so get the contents of the file (if the file
//  already exists)

// Syncronize block for file input/output

                synchronized(this) {

                    if (votesdat.exists()) {
                        ObjectInputStream indat = 
                            new ObjectInputStream(
                            new FileInputStream(votesdat));

// We need the try/catch here because readObject can throw
//  ClassNotFoundException

                        try {
                            votes = (int []) indat.readObject();
                        }
                        catch(ClassNotFoundException problem) {
                           problem.printStackTrace();
                        }
                    }  //** end of if(votesdat.exists() ...

// If the file does not exist (this is the first vote), create the 
//  votes array

                    else 
                        votes = new int[3];
                
// Add the new vote to the votes array

                    if (vote.equals("Dogman")) 
                        votes[0]++;
                    else if (vote.equals("Taildragger"))
                        votes[1]++;
                    else votes[2]++;



// Write updated votes array to disk

                    ObjectOutputStream outdat = 
                        new ObjectOutputStream(
                        new FileOutputStream(votesdat));
                    outdat.writeObject(votes);
                    outdat.flush();
                    outdat.close();

                }  //** end of the synchronized block

// Create a session object and set a value to indicate a vote

                newCookie = new Cookie("iVoted", "true");
                newCookie.setMaxAge(5);
		response.addCookie(newCookie);
                
// Write a response message

                makeHeader(response);
                servletOut.println("Your vote has been received");
                servletOut.println(
                    "<br/> <br/> Current Voting Totals:<br/>");

// Create the total votes return information 
      
                for (index = 0; index < 3; index++) {
                    servletOut.println("<br/>");
		    servletOut.print(candidates[index]);
                    servletOut.print(": ");
                    servletOut.println(votes[index]);
                }
            }  // end of if (!votedBefore( ...

else {  // The client voted before

// Write a response message

                makeHeader(response);
                servletOut.println(
                   "Your vote is illegal - you have already voted!");
                  }  // end of else clause - client voted before

        }  // end of else (there was a vote)

// Finish response document and close the stream

         servletOut.println("</body> </html>"); 
         servletOut.close();

    }  // end of doPost

//----------------------------------------------------------------
// Method votedBefore - return true if the client voted before;
//  false otherwise

    boolean votedBefore() {
        if (cookies == null || cookies.length == 0)
            return false;
        else {

// Check the cookies to see if this user voted before

            for (index = 0; index < cookies.length; index++) {

                 if (cookies[index].getName().equals("iVoted")  
                     && cookies[index].getValue().equals("true"))  
                     return true;

            }  // end of for (index = 0; ...  

            return false;      

        }  // end of if (cookies == null ...
    }  // end of votedBefore

//----------------------------------------------------------------
// Method makeHeader - get the writer and produce 
// the response header
void makeHeader(HttpServletResponse response)
             throws IOException {

// Set content type for response and get a writer

        response.setContentType("text/html"); 
        servletOut = response.getWriter();

// Write the response document head and the message

        servletOut.println("<html><head>");
        servletOut.println(
                 "<title> Return message - </title></head><body>");

    }  // end of makeHeader

}  // end of VoteCounter

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -