KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > myfaces > webapp > filter > WelcomeFileFilter


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

16 package org.apache.myfaces.webapp.filter;
17
18 import javax.servlet.*;
19 import javax.servlet.http.HttpServletRequest JavaDoc;
20 import javax.xml.parsers.SAXParser JavaDoc;
21 import javax.xml.parsers.SAXParserFactory JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25
26
27 /**
28  *
29  * Due to the manner in which the JSP / servlet lifecycle
30  * functions, it is not currently possible to specify default
31  * welcome files for a web application and map them to the
32  * MyFacesServlet. Normally they will be mapped to the
33  * default servlet for the JSP container. To offset this
34  * shortcoming, we utilize a servlet Filter which examines
35  * the URI of all incoming requests.
36  *
37  * @author Robert J. Lebowitz (latest modification by $Author: matze $)
38  * @author Anton Koinov
39  * @since February 18th, 2003
40  * @version $Revision: 1.7 $ $Date: 2004/10/13 11:51:01 $
41  */

42 public class WelcomeFileFilter
43 implements Filter
44 {
45     //~ Instance fields --------------------------------------------------------
46

47     private FilterConfig _config;
48     private ServletContext _context;
49     private String JavaDoc[] _welcomeFiles = new String JavaDoc[0];
50
51     //~ Methods ----------------------------------------------------------------
52

53     /**
54      * @see javax.servlet.Filter#destroy()
55      */

56     public void destroy()
57     {
58         _config = null;
59         _context = null;
60         _welcomeFiles = null;
61     }
62
63     /**
64      *
65      * If the URI indicates a context, or a subdirectory within a particular
66      * context, but does not specify a filename, the request is redirected to
67      * one of the default welcome files, assuming they are provided in the web.xml file.
68      * If no welcome files are specified, or if none of the welcome files
69      * actually exists, then the request is redirected to a file named "index.jsp" for
70      * that context or subdirectory with the current context. If the index.jsp file
71      * does not exist, the servlet will return a File Not Found Error 404 message.
72      *
73      * A well configured servlet should provide a means of handling this type of
74      * error, along with a link to an appropriate help page.
75      *
76      * A URI is thought to represent a context and/or subdirectory(s) if
77      * it lacks a suffix following the pattern <b>.suffix</b>.
78      *
79      */

80     public void doFilter(
81         ServletRequest JavaDoc request, ServletResponse response, FilterChain chain)
82     throws IOException JavaDoc, ServletException
83     {
84         if (_config == null)
85         {
86             return;
87         }
88
89         HttpServletRequest JavaDoc httpRequest = (HttpServletRequest JavaDoc) request;
90         String JavaDoc uri = httpRequest.getRequestURI();
91
92         // if the uri does not contain a suffix, we consider
93
// it to represent a directory / context, not a file.
94
// file has suffix. No need to search for welcome file
95
if (uri.lastIndexOf('.') > uri.lastIndexOf('/'))
96         {
97             chain.doFilter(request, response);
98
99             return;
100         }
101
102         String JavaDoc contextPath = httpRequest.getContextPath();
103         String JavaDoc welcomeFile = null;
104         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(uri);
105
106         if (!uri.endsWith("/"))
107         {
108             sb.append('/');
109         }
110
111         String JavaDoc baseURI = sb.delete(
112                 0,
113                 contextPath.length()).toString();
114
115         // REVISIT: we probably can check for existence once at startup
116
// and know the exact welcome file by now. Of course, that
117
// would not work if the files change at runtime, but does it matter?
118
for (int i = 0; i < _welcomeFiles.length; i++)
119         {
120             sb.setLength(0);
121             sb.append(baseURI).append(_welcomeFiles[i]);
122
123             File JavaDoc file = new File JavaDoc(_context.getRealPath(sb.toString()));
124
125             // context.log("Welcome File: " + file.getAbsolutePath());
126
if (file.exists())
127             {
128                 // REVISIT: This will force all "welcome" JSPs through MyFaces.
129
// Shouldn't we allow the user to enter *.jsf and check for *.jsp for existence, instead?
130
if (_welcomeFiles[i].endsWith(".jsp"))
131                 {
132                     // alter the name of the file we are requesting to
133
// force it through the MyFacesServlet
134
sb.replace(
135                         sb.lastIndexOf(".jsp"),
136                         sb.length(),
137                         ".jsf");
138                     welcomeFile = sb.toString();
139                 }
140
141                 // we have discovered a filename;
142
// stop the loop
143
break;
144             }
145         }
146
147         if (welcomeFile == null)
148         {
149             sb.setLength(0);
150             sb.append(baseURI);
151             sb.append("index.jsf");
152             welcomeFile = sb.toString();
153         }
154
155         RequestDispatcher rd = httpRequest.getRequestDispatcher(welcomeFile);
156         rd.forward(request, response);
157
158         return;
159     }
160
161     /**
162      * During the init method, we have to get any predefined welcome files
163      * for the current ServletContext.
164      * @param config The filter configuration data
165      * @throws ServletException
166      */

167     public void init(FilterConfig config)
168     throws ServletException
169     {
170         if (config == null)
171         {
172             return;
173         }
174
175         this._config = config;
176         this._context = config.getServletContext();
177
178         try
179         {
180             SAXParserFactory JavaDoc factory = SAXParserFactory.newInstance();
181             factory.setValidating(true);
182             factory.setNamespaceAware(false);
183
184             SAXParser JavaDoc parser = factory.newSAXParser();
185             WelcomeFileHandler handler = new WelcomeFileHandler();
186             InputStream JavaDoc is =
187                 _context.getResourceAsStream("WEB-INF/web.xml");
188
189             if (is == null)
190             {
191                 _context.log("Unable to get inputstream for web.xml");
192             }
193
194             parser.parse(is, handler);
195             _welcomeFiles = handler.getWelcomeFiles();
196             _context.log("Number of welcome files: " + _welcomeFiles.length);
197         }
198         catch (Exception JavaDoc ex)
199         {
200             throw new ServletException(ex);
201         }
202     }
203 }
204
Popular Tags