1 package example; 2 3 import java.io.IOException ; 4 import java.util.*; 5 6 import javax.servlet.ServletException ; 7 import javax.servlet.http.*; 8 9 public class GuestbookServlet extends ControllerServlet { 10 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 , ServletException { 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 , ServletException { 41 List errors = new ArrayList(); 42 String name = req.getParameter("name"); 43 String email = req.getParameter("email"); 44 String 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 if (errors.isEmpty()) { 54 if (email == null) email = ""; 55 GuestbookEntry e = new GuestbookEntry( 57 name.trim(), email.trim(), message); 58 synchronized (guestbook) { 59 guestbook.add(0, e); 60 } 61 p.put("entry", e); 63 p.setTemplate("add.ftl"); 64 } else { 65 req.setAttribute("errors", errors); 67 p.setForward("form.a"); 68 } 69 } 70 71 public static String noNull(String s) { 72 return s == null ? "" : s; 73 } 74 75 public static boolean isBlank(String s) { 76 return s == null || s.trim().length() == 0; 77 } 78 } 79 | Popular Tags |