KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > velocity > demo > ControllerServlet


1 package org.apache.velocity.demo;
2
3 /*
4  * Copyright 1999,2004 The Apache Software Foundation.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 // Java stuff
20
import java.util.*;
21 import java.io.StringWriter JavaDoc;
22 import java.io.PrintWriter JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.FileNotFoundException JavaDoc;
25 import java.io.FileInputStream JavaDoc;
26
27 // Servlet stuff
28
import javax.servlet.*;
29 import javax.servlet.http.HttpServlet JavaDoc;
30 import javax.servlet.http.HttpServletRequest JavaDoc;
31 import javax.servlet.http.HttpServletResponse JavaDoc;
32 import javax.servlet.http.HttpSession JavaDoc;
33
34 // Velocity stuff
35
import org.apache.velocity.context.Context;
36 import org.apache.velocity.Template;
37 import org.apache.velocity.servlet.VelocityServlet;
38
39 import org.apache.velocity.exception.ParseErrorException;
40 import org.apache.velocity.exception.ResourceNotFoundException;
41 import org.apache.velocity.exception.MethodInvocationException;
42
43 // Demo stuff
44
import org.apache.velocity.demo.action.*;
45
46 /**
47  * Main entry point into the forum application.
48  * All requests are made to this servlet.
49  *
50  * @author <a HREF="mailto:daveb@miceda-data.com">Dave Bryson</a>
51  * @version $Revision: 1.4.12.1 $
52  * $Id: ControllerServlet.java,v 1.4.12.1 2004/03/04 00:18:29 geirm Exp $
53  */

54 public class ControllerServlet extends VelocityServlet
55 {
56     private static String JavaDoc ERR_MSG_TAG = "forumdemo_current_error_msg";
57
58     
59     /**
60      * lets override the loadConfiguration() so we can do some
61      * fancier setup of the template path
62      */

63     protected Properties loadConfiguration(ServletConfig config )
64         throws IOException JavaDoc, FileNotFoundException JavaDoc
65     {
66         String JavaDoc propsFile = config.getInitParameter(INIT_PROPS_KEY);
67         
68         /*
69          * now convert to an absolute path relative to the webapp root
70          * This will work in a decently implemented servlet 2.2
71          * container like Tomcat.
72          */

73
74         if ( propsFile != null )
75         {
76             String JavaDoc realPath = getServletContext().getRealPath(propsFile);
77         
78             if ( realPath != null )
79             {
80                 propsFile = realPath;
81             }
82         }
83         
84        Properties p = new Properties();
85        p.load( new FileInputStream JavaDoc(propsFile) );
86       
87
88        /*
89         * now, lets get the two elements we care about, the
90         * template path and the log, and fix those from relative
91         * to the webapp root, to absolute on the filesystem, which is
92         * what velocity needs
93         */

94
95        String JavaDoc path = p.getProperty("file.resource.loader.path");
96
97        if (path != null)
98        {
99            path = getServletContext().getRealPath( path );
100            p.setProperty( "file.resource.loader.path", path );
101        }
102         
103        path = p.getProperty("runtime.log");
104
105        if (path != null)
106        {
107            path = getServletContext().getRealPath( path );
108            p.setProperty("runtime.log", path );
109        }
110
111        return p;
112     }
113
114     /**
115      * VelocityServlet handles most of the Servlet issues.
116      * By extending it, you need to just implement the handleRequest method.
117      * @param the Context created in VelocityServlet.
118      * @return the template
119      */

120     public Template handleRequest( Context ctx )
121     {
122         HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc)ctx.get(VelocityServlet.REQUEST);
123         HttpServletResponse JavaDoc resp = (HttpServletResponse JavaDoc)ctx.get(VelocityServlet.RESPONSE);
124         Template template = null;
125         String JavaDoc templateName = null;
126         
127         HttpSession JavaDoc sess = req.getSession();
128         sess.setAttribute(ERR_MSG_TAG, "all ok" );
129
130         try
131         {
132             // Process the command
133
templateName = processRequest( req, resp, ctx );
134             // Get the template
135
template = getTemplate( templateName );
136         }
137         catch( ResourceNotFoundException rnfe )
138         {
139             String JavaDoc err = "ForumDemo -> ControllerServlet.handleRequest() : Cannot find template " + templateName ;
140             sess.setAttribute( ERR_MSG_TAG, err );
141             System.out.println(err );
142         }
143         catch( ParseErrorException pee )
144         {
145             String JavaDoc err = "ForumDemo -> ControllerServlet.handleRequest() : Syntax error in template " + templateName + ":" + pee ;
146             sess.setAttribute( ERR_MSG_TAG, err );
147             System.out.println(err );
148         }
149         catch( Exception JavaDoc e )
150         {
151             String JavaDoc err = "Error handling the request: " + e ;
152             sess.setAttribute( ERR_MSG_TAG, err );
153             System.out.println(err );
154         }
155
156         return template;
157     }
158     
159     /**
160      * Process the request and execute the command.
161      * Uses a command pattern
162      * @param the request
163      * @param the response
164      * @param the context
165      * @return the name of the template to use
166      */

167     private String JavaDoc processRequest( HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc resp, Context context )
168      throws Exception JavaDoc
169     {
170         Command c = null;
171         String JavaDoc template = null;
172         String JavaDoc name = req.getParameter("action");
173         
174         if ( name == null || name.length() == 0 )
175         {
176             throw new Exception JavaDoc("Unrecognized action request!");
177         }
178                 
179         if ( name.equalsIgnoreCase("list") )
180         {
181             c = new ListCommand( req, resp);
182             template = c.exec( context );
183         }
184         else if ( name.equalsIgnoreCase("post") )
185         {
186             c = new PostCommand( req, resp );
187             template = c.exec( context );
188         }
189         else if ( name.equalsIgnoreCase("reply") )
190         {
191             c = new ReplyCommand( req, resp );
192             template = c.exec( context );
193         }
194         else if ( name.equalsIgnoreCase("postreply") )
195         {
196             c = new PostReplyCommand( req, resp );
197             template = c.exec( context );
198         }
199         else if ( name.equalsIgnoreCase("view") )
200         {
201             c = new ViewCommand( req, resp );
202             template = c.exec( context );
203         }
204         return template;
205     }
206
207     /**
208      * Override the method from VelocityServlet to produce an intelligent
209      * message to the browser
210      */

211     protected void error( HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Exception JavaDoc cause )
212         throws ServletException, IOException JavaDoc
213     {
214         HttpSession JavaDoc sess = request.getSession();
215         String JavaDoc err = (String JavaDoc) sess.getAttribute( ERR_MSG_TAG );
216
217         StringBuffer JavaDoc html = new StringBuffer JavaDoc();
218         html.append("<html>");
219         html.append("<body bgcolor=\"#ffffff\">");
220         html.append("<h2>ForumDemo : Error processing the request</h2>");
221         html.append("<br><br>There was a problem in the request." );
222         html.append("<br><br>The relevant error is :<br>");
223         html.append( err );
224         html.append("<br><br><br>");
225         html.append("The error occurred at :<br><br>");
226
227         StringWriter JavaDoc sw = new StringWriter JavaDoc();
228         cause.printStackTrace( new PrintWriter JavaDoc( sw ) );
229
230         html.append( sw.toString() );
231         html.append("</body>");
232         html.append("</html>");
233         response.getOutputStream().print( html.toString() );
234     }
235 }
236
237
238
239
240
241
Popular Tags