import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetColor extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String pageColor;
String colorParameter = req.getParameter("color");
if (colorParameter != null) {
Cookie colorCookie = new Cookie("color", colorParameter);
colorCookie.setMaxAge(31536000);
res.addCookie(colorCookie);
pageColor = colorParameter;
} else {
pageColor = retrieveColor(req.getCookies());
}
ServletOutputStream out = res.getOutputStream();
res.setContentType("text/html");
out.println("");
out.println("
");
out.println("The U.S. Constitution");
out.println("The U.S. Constitution
");
displayFile("constitution.html", out);
out.println("Choose a new color
");
out.println("");
out.println("");
out.println("");
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doPost(req, res);
}
String retrieveColor(Cookie[] cookies) {
String inColor = "#FFFFFF";
for (int i = 0; i < cookies.length; i++) {
String cookieName = cookies[i].getName();
if (cookieName.equals("color")) {
inColor = cookies[i].getValue();
}
}
return inColor;
}
void displayFile(String pageName, ServletOutputStream out) {
try {
ServletContext servletContext = getServletContext();
String filename = servletContext.getRealPath(pageName);
FileReader file = new FileReader(filename);
BufferedReader buff = new BufferedReader(file);
boolean eof = false;
while (!eof) {
String line = buff.readLine();
if (line == null)
eof = true;
else
out.println(line);
}
buff.close();
} catch (IOException e) {
log("Error -- " + e.toString());
}
}
}