1 package example; 2 3 import java.io.*; 4 import java.util.*; 5 import java.lang.reflect.*; 6 import javax.servlet.*; 7 import javax.servlet.http.*; 8 import freemarker.template.*; 9 10 15 public class ControllerServlet extends HttpServlet { 16 private Configuration cfg; 17 18 public void init() { 19 cfg = new Configuration(); 22 cfg.setServletContextForTemplateLoading( 24 getServletContext(), "WEB-INF/templates"); 25 cfg.setTemplateUpdateDelay(0); 28 cfg.setTemplateExceptionHandler( 31 TemplateExceptionHandler.HTML_DEBUG_HANDLER); 32 cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER); 34 cfg.setDefaultEncoding("ISO-8859-1"); 36 cfg.setOutputEncoding("UTF-8"); 40 cfg.setLocale(Locale.US); 42 } 43 44 protected void doPost(HttpServletRequest req, HttpServletResponse resp) 45 throws ServletException, IOException { 46 doGet(req, resp); 47 } 48 49 protected void doGet(HttpServletRequest req, HttpServletResponse resp) 50 throws ServletException, IOException { 51 52 String action = req.getServletPath(); 54 if (action == null) action = "index"; 55 if (action.startsWith("/")) action = action.substring(1); 56 if (action.lastIndexOf(".") != -1) { 57 action = action.substring(0, action.lastIndexOf(".")); 58 } 59 Method actionMethod; 60 try { 61 actionMethod = 62 getClass().getMethod(action + "Action", 63 new Class []{HttpServletRequest.class, Page.class}); 64 } catch (NoSuchMethodException e) { 65 throw new ServletException("Unknown action: " + action); 66 } 67 68 req.setCharacterEncoding(cfg.getOutputEncoding()); 71 72 Page page = new Page(); 74 try { 75 actionMethod.invoke(this, new Object []{req, page}); 76 } catch (IllegalAccessException e) { 77 throw new ServletException(e); 78 } catch (InvocationTargetException e) { 79 throw new ServletException(e.getTargetException()); 80 } 81 82 if (page.getTemplate() != null) { Template t = cfg.getTemplate(page.getTemplate()); 85 86 resp.setContentType("text/html; charset=" + cfg.getOutputEncoding()); 90 resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, " 94 + "post-check=0, pre-check=0"); 95 resp.setHeader("Pragma", "no-cache"); 96 resp.setHeader("Expires", "Thu, 01 Dec 1994 00:00:00 GMT"); 97 Writer out = resp.getWriter(); 98 99 try { 101 t.process(page.getRoot(), out); 102 } catch (TemplateException e) { 103 throw new ServletException( 104 "Error while processing FreeMarker template", e); 105 } 106 } else if (page.getForward() != null) { RequestDispatcher rd = req.getRequestDispatcher(page.getForward()); 108 rd.forward(req, resp); 109 } else { 110 throw new ServletException("The action didn't specified a command."); 111 } 112 } 113 } | Popular Tags |