KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > riotfamily > forms > controller > AbstractFormController


1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1
3  * The contents of this file are subject to the Mozilla Public License Version
4  * 1.1 (the "License"); you may not use this file except in compliance with
5  * the License. You may obtain a copy of the License at
6  * http://www.mozilla.org/MPL/
7  *
8  * Software distributed under the License is distributed on an "AS IS" basis,
9  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10  * for the specific language governing rights and limitations under the
11  * License.
12  *
13  * The Original Code is Riot.
14  *
15  * The Initial Developer of the Original Code is
16  * Neteye GmbH.
17  * Portions created by the Initial Developer are Copyright (C) 2006
18  * the Initial Developer. All Rights Reserved.
19  *
20  * Contributor(s):
21  * Felix Gnass [fgnass at neteye dot de]
22  *
23  * ***** END LICENSE BLOCK ***** */

24 package org.riotfamily.forms.controller;
25
26 import java.io.IOException JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.http.HttpServletResponse JavaDoc;
34 import javax.servlet.http.HttpSession JavaDoc;
35
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.riotfamily.forms.Container;
39 import org.riotfamily.forms.ContentElement;
40 import org.riotfamily.forms.Element;
41 import org.riotfamily.forms.Form;
42 import org.springframework.web.servlet.ModelAndView;
43 import org.springframework.web.servlet.mvc.Controller;
44
45
46 /**
47  * Abstract base class for controllers that display a form.
48  *
49  * @author Felix Gnass [fgnass at neteye dot de]
50  */

51 public abstract class AbstractFormController implements Controller {
52
53     public static final String JavaDoc FORM_SUBMISSION_HANDLER = "formSubmissionHandler";
54     
55     protected static final String JavaDoc BUTTON_CONTAINER_ID = "buttons";
56     
57     private static final String JavaDoc CONTENT_PARAM = "_content";
58     
59     private static final String JavaDoc EXCLUSIVE_PARAM = "_exclusive";
60     
61     protected Log log = LogFactory.getLog(getClass());
62     
63     private FormContextFactory formContextFactory;
64     
65     private boolean processNewForms;
66     
67     private List JavaDoc buttonFactories;
68     
69
70     public void setFormContextFactory(FormContextFactory contextFactory) {
71         this.formContextFactory = contextFactory;
72     }
73
74     public final void setProcessNewForms(boolean processNewForms) {
75         this.processNewForms = processNewForms;
76     }
77     
78     public void setButtonFactories(List JavaDoc buttonFactories) {
79         this.buttonFactories = buttonFactories;
80     }
81     
82     protected void addButton(ButtonFactory buttonFactory) {
83         if (buttonFactories == null) {
84             buttonFactories = new ArrayList JavaDoc();
85         }
86         buttonFactories.add(buttonFactory);
87     }
88
89     protected final void initController() {
90     }
91     
92     /**
93      * Handles a HTTP request. The workflow is:
94      * <ol>
95      * <li>
96      * Check if a new Form needs to be created by calling
97      * {@link #isInitialRequest}.
98      * </li>
99      * <li>
100      * Call to {@link #createAndInitForm} in case of an initial request
101      * or {@link #getForm} otherwise.
102      * </li>
103      * <li>
104      * Check if the request is request for additional content (an
105      * image or iframe for example) and call {@link #handleContentRequest}
106      * or {@link #handleFormRequest}.
107      * </li>
108      * </ol>
109      */

110     public ModelAndView handleRequest(HttpServletRequest JavaDoc request,
111             HttpServletResponse JavaDoc response) throws Exception JavaDoc {
112
113         Form form = null;
114         if (!isInitialRequest(request)) {
115             form = getForm(request);
116         }
117         if (form == null) {
118             form = createAndInitForm(request, response);
119         }
120
121         if (isContentRequest(request)) {
122             return handleContentRequest(form, request, response);
123         }
124         else {
125             return handleFormRequest(form, request, response);
126         }
127     }
128     
129     protected ModelAndView handleFormRequest(Form form,
130             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
131             throws Exception JavaDoc {
132         
133         if (!isInitialRequest(request) || processNewForms) {
134             processForm(form, request);
135         }
136         return createModelAndView(form, request, response);
137     }
138     
139     /**
140      * Returns the {@link Form Form} for the given request. By
141      * default this method looks for an existing instance in the HTTP session
142      * under the key returned by {@link #getSessionAttribute} and
143      * returns it.
144      */

145     protected Form getForm(HttpServletRequest JavaDoc request) {
146         log.debug("Retrieving Form from session");
147         HttpSession JavaDoc session = request.getSession();
148         String JavaDoc attrName = getSessionAttribute(request);
149         Form form = (Form) session.getAttribute(attrName);
150         return form;
151     }
152         
153     protected ModelAndView showForm(Form form,
154             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
155             throws Exception JavaDoc {
156         
157         PrintWriter JavaDoc writer = getWriter(request,response);
158         renderForm(form, writer);
159         return null;
160     }
161     
162     protected PrintWriter JavaDoc getWriter(HttpServletRequest JavaDoc request,
163             HttpServletResponse JavaDoc response) throws IOException JavaDoc {
164         
165         return response.getWriter();
166     }
167     
168     protected void renderForm(Form form, PrintWriter JavaDoc writer) {
169         form.render(writer);
170     }
171     
172     /**
173      * Returns whether the given request is an initial form request. By
174      * default it is checked whether the request method is <tt>GET</tt> and
175      * {@link #isContentRequest} returns <code>false</code>.
176      */

177     protected boolean isInitialRequest(HttpServletRequest JavaDoc request) {
178         return "GET".equals(request.getMethod()) && !isContentRequest(request);
179     }
180     
181     /**
182      * Returns whether the request is to be handled by a {@link ContentElement}.
183      */

184     protected boolean isContentRequest(HttpServletRequest JavaDoc request) {
185         return request.getParameter(CONTENT_PARAM) != null;
186     }
187     
188     protected boolean isExclusiveRequest(HttpServletRequest JavaDoc request) {
189         return request.getParameter(EXCLUSIVE_PARAM) != null;
190     }
191     
192     protected ModelAndView handleContentRequest(Form form,
193             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
194             throws IOException JavaDoc {
195         
196         if (form != null) {
197             String JavaDoc id = request.getParameter(CONTENT_PARAM);
198             Element element = form.getElementById(id);
199             if (element instanceof ContentElement) {
200                 ContentElement ce = (ContentElement) element;
201                 ce.handleContentRequest(request, response);
202                 return null;
203             }
204         }
205         response.sendError(HttpServletResponse.SC_NOT_FOUND);
206         return null;
207     }
208     
209     /**
210      * Creates and initializes a form.
211      */

212     protected Form createAndInitForm(HttpServletRequest JavaDoc request,
213             HttpServletResponse JavaDoc response) throws Exception JavaDoc {
214                 
215         Form form = createForm(request);
216         form.setFormContext(formContextFactory.createFormContext(request, response));
217         
218         if (buttonFactories != null && !buttonFactories.isEmpty()) {
219             Container container = form.createContainer(BUTTON_CONTAINER_ID);
220             Iterator JavaDoc it = buttonFactories.iterator();
221             while (it.hasNext()) {
222                 ButtonFactory buttonFactory = (ButtonFactory) it.next();
223                 container.addElement(buttonFactory.createButton());
224             }
225         }
226         
227         populateForm(form, request);
228         form.init();
229         initForm(form, request);
230         
231         String JavaDoc attrName = getSessionAttribute(request);
232         request.getSession().setAttribute(attrName, form);
233         
234         return form;
235     }
236     
237     protected void processForm(Form form, HttpServletRequest JavaDoc request) {
238         if (isExclusiveRequest(request)) {
239             String JavaDoc id = request.getParameter(EXCLUSIVE_PARAM);
240             form.processExclusiveRequest(id, request);
241         }
242         else {
243             form.processRequest(request);
244         }
245     }
246     
247     /**
248      * Populates newly created forms. The default implementation invokes
249      * {@link Form#setValue(Object)} with the object returned by
250      * {@link #getFormBackingObject(HttpServletRequest)}.
251      */

252     protected void populateForm(Form form, HttpServletRequest JavaDoc request)
253             throws Exception JavaDoc {
254         
255         form.setValue(getFormBackingObject(request));
256     }
257     
258     /**
259      * Returns the object backing the form. Subclasses may overwrite this method
260      * to retrieve a persistent object. The default implementation returns
261      * <code>null</code>.
262      */

263     protected Object JavaDoc getFormBackingObject(HttpServletRequest JavaDoc request)
264             throws Exception JavaDoc {
265         
266         return null;
267     }
268
269     /**
270      * Subclasses must implement this method and return a fresh
271      * {@link Form} instance.
272      */

273     protected abstract Form createForm(HttpServletRequest JavaDoc request);
274     
275     /**
276      * Subclasses may overwite this method to inialize forms after they have
277      * been populated. The default implementation does nothing.
278      */

279     protected void initForm(Form form, HttpServletRequest JavaDoc request) {
280     }
281     
282     protected final ModelAndView createModelAndView(Form form,
283             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
284             throws Exception JavaDoc {
285         
286         FormSubmissionHandler handler = (FormSubmissionHandler)
287                 form.getAttribute(FORM_SUBMISSION_HANDLER);
288         
289         form.setAttribute(FORM_SUBMISSION_HANDLER, null);
290         
291         if (handler != null && !form.hasErrors()) {
292             return handler.handleFormSubmission(form, request, response);
293         }
294         return showForm(form, request, response);
295     }
296     
297     protected String JavaDoc getSessionAttribute(HttpServletRequest JavaDoc request) {
298         return AbstractFormController.class.getName() + ".form";
299     }
300     
301 }
302
Popular Tags