KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > ControllerServlet


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 /**
11  * <p>This is very very primitive MVC Controller servlet base class, based
12  * on example 1. The application specific controller servlet should extend
13  * this class.
14  */

15 public class ControllerServlet extends HttpServlet {
16     private Configuration cfg;
17     
18     public void init() {
19         // Initialize the FreeMarker configuration;
20
// - Create a configuration instance
21
cfg = new Configuration();
22         // - Templates are stoted in the WEB-INF/templates directory of the Web app.
23
cfg.setServletContextForTemplateLoading(
24                 getServletContext(), "WEB-INF/templates");
25         // - Set update dealy to 0 for now, to ease debugging and testing.
26
// Higher value should be used in production environment.
27
cfg.setTemplateUpdateDelay(0);
28         // - Set an error handler that prints errors so they are readable with
29
// a HTML browser.
30
cfg.setTemplateExceptionHandler(
31                 TemplateExceptionHandler.HTML_DEBUG_HANDLER);
32         // - Use beans wrapper (recommmended for most applications)
33
cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
34         // - Set the default charset of the template files
35
cfg.setDefaultEncoding("ISO-8859-1");
36         // - Set the charset of the output. This is actually just a hint, that
37
// templates may require for URL encoding and for generating META element
38
// that uses http-equiv="Content-type".
39
cfg.setOutputEncoding("UTF-8");
40         // - Set the default locale
41
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         // Choose action method
53
String JavaDoc 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 JavaDoc[]{HttpServletRequest.class, Page.class});
64         } catch (NoSuchMethodException JavaDoc e) {
65             throw new ServletException("Unknown action: " + action);
66         }
67         
68         // Set the request charset to the same as the output charset,
69
// because HTML forms normally send parameters encoded with that.
70
req.setCharacterEncoding(cfg.getOutputEncoding());
71         
72         // Call the action method
73
Page page = new Page();
74         try {
75             actionMethod.invoke(this, new Object JavaDoc[]{req, page});
76         } catch (IllegalAccessException JavaDoc e) {
77             throw new ServletException(e);
78         } catch (InvocationTargetException e) {
79             throw new ServletException(e.getTargetException());
80         }
81         
82         if (page.getTemplate() != null) { // show a page with a template
83
// Get the template object
84
Template t = cfg.getTemplate(page.getTemplate());
85             
86             // Prepare the HTTP response:
87
// - Set the MIME-type and the charset of the output.
88
// Note that the charset should be in sync with the output_encoding setting.
89
resp.setContentType("text/html; charset=" + cfg.getOutputEncoding());
90             // - Prevent browser or proxy caching the page.
91
// Note that you should use it only for development and for interactive
92
// pages, as it significantly slows down the Web site.
93
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             // Merge the data-model and the template
100
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) { // forward request
107
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