package voteCounter2webapp;
// VoteCounter2.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.
// This servlet uses session tracking rather than cookies.
// The voting data file, votesdat.dat, is stored on the Web server.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class VoteCounter2 extends HttpServlet {
PrintWriter servletOut;
int index;
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
HttpSession mySession = null;
int votes[] = null;
String vote;
File votesdat = new File("votesdat.dat");
String candidates[] = {"Daren Dogman", "Timmy Taildragger",
"Don Dogpile"};
// If the file already exists, read in its data
if (votesdat.exists()) {
ObjectInputStream indat = new ObjectInputStream(
new FileInputStream(votesdat));
// We need try/catch here because readObject may throw the
// ClassNotFoundException
try {
votes = (int []) indat.readObject();
}
catch(ClassNotFoundException problem) {
problem.printStackTrace();
}
indat.close();
} // end of if (votesdat...
// If the file does not exist (this is the first vote), create the
// votes array
else
votes = new int[3];
// 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");
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(mySession, request)) {
// No previous vote, so add the new vote of the response 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();
// Create a session object and set a value to indicate a vote
mySession = request.getSession(true);
mySession.putValue("iVoted", "true");
// Write a response message
makeHeader(response);
servletOut.println("Your vote has been received");
servletOut.println(
"
Current Voting Totals:
");
// Create the total votes return information
for (index = 0; index < 3; index++) {
servletOut.println("
");
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
} // end of else (there was a vote)
servletOut.println("