import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GuestBook extends HttpServlet {
String name = "Not provided";
String emailAddress = "Not provided";
String url = "Not provided";
String comment;
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
name = req.getParameter("name");
emailAddress = req.getParameter("email");
url = req.getParameter("url");
comment = req.getParameter("comment");
ServletOutputStream out = res.getOutputStream();
res.setContentType("text/html");
if (comment != null) {
addEntry(name, emailAddress, url, comment);
out.println("
Your entry has been added to the guestbook.");
out.println("
View Entries");
} else {
viewEntries(res);
out.println("
Add a Guestbook Entry
");
out.println("");
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doPost(req, res);
}
void addEntry(String name, String email, String url, String comment) {
try {
ServletContext servletContext = getServletContext();
String filename = servletContext.getRealPath("guestbook.txt");
// Create output stream
FileWriter fw = new FileWriter(filename, true);
BufferedWriter book = new BufferedWriter(fw);
book.write("Name: " + name + "
");
book.newLine();
book.write("E-mail: " + emailAddress + "
");
book.newLine();
book.write("Web Site: " + url + "
");
book.newLine();
book.write("Comment");
book.write("
" + comment);
book.newLine();
book.write("
");
book.newLine();
book.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
} catch (SecurityException se) {
System.out.println("Error -- " + se.toString());
}
}
void viewEntries(HttpServletResponse res) {
try {
ServletContext servletContext = getServletContext();
String filename = servletContext.getRealPath("guestbook.txt");
// Create input stream
ServletOutputStream out = res.getOutputStream();
res.setContentType("text/html");
out.println("Guestbook
");
FileReader fr = new FileReader(filename);
BufferedReader book = new BufferedReader(fr);
try {
String line = "None.";
while (line != null) {
line = book.readLine();
if (line != null)
out.println(line);
}
} catch (IOException ioe) {
// end of file reached
}
book.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
} catch (SecurityException se) {
System.out.println("Error -- " + se.toString());
}
}
}