KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > GuestbookServlet


1 package example;
2
3 import java.io.IOException JavaDoc;
4 import java.util.*;
5
6 import javax.servlet.ServletException JavaDoc;
7 import javax.servlet.http.*;
8
9 public class GuestbookServlet extends ControllerServlet {
10     /**
11      * Stores the list of guestbook entries.
12      *
13      * <p>Note that for the sake of simplicity, this example
14      * does not try to store the guestbook persistenty.
15      */

16     private ArrayList guestbook = new ArrayList();
17     
18     public void indexAction(HttpServletRequest req, Page p) {
19         List snapShot;
20         synchronized (guestbook) {
21             snapShot = (List) guestbook.clone();
22         }
23         p.put("guestbook", snapShot);
24         p.setTemplate("index.ftl");
25     }
26
27     public void formAction (HttpServletRequest req, Page p)
28             throws IOException JavaDoc, ServletException JavaDoc {
29                 
30         p.put("name", noNull(req.getParameter("name")));
31         p.put("email", noNull(req.getParameter("email")));
32         p.put("message", noNull(req.getParameter("message")));
33         List errors = (List) req.getAttribute("errors");
34         p.put("errors", errors == null ? new ArrayList() : errors);
35
36         p.setTemplate("form.ftl");
37     }
38
39     public void addAction (HttpServletRequest req, Page p)
40             throws IOException JavaDoc, ServletException JavaDoc {
41         List errors = new ArrayList();
42         String JavaDoc name = req.getParameter("name");
43         String JavaDoc email = req.getParameter("email");
44         String JavaDoc message = req.getParameter("message");
45         if (isBlank(name)) {
46             errors.add("You must give your name.");
47         }
48         if (isBlank(message)) {
49             errors.add("You must give a message.");
50         }
51
52         // Was the sent data was correct?
53
if (errors.isEmpty()) {
54             if (email == null) email = "";
55             // Create and insert the new guestbook entry.
56
GuestbookEntry e = new GuestbookEntry(
57                     name.trim(), email.trim(), message);
58             synchronized (guestbook) {
59                 guestbook.add(0, e);
60             }
61             // Show "Entry added" page.
62
p.put("entry", e);
63             p.setTemplate("add.ftl");
64         } else {
65             // Go back to the page of the form
66
req.setAttribute("errors", errors);
67             p.setForward("form.a");
68         }
69     }
70
71     public static String JavaDoc noNull(String JavaDoc s) {
72         return s == null ? "" : s;
73     }
74     
75     public static boolean isBlank(String JavaDoc s) {
76         return s == null || s.trim().length() == 0;
77     }
78 }
79
Popular Tags