KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > xtags > util > URLHelper


1 /*
2  * Copyright 1999,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
17 package org.apache.taglibs.xtags.util;
18
19 import java.net.MalformedURLException JavaDoc;
20 import java.net.URL JavaDoc;
21
22 import javax.servlet.ServletContext JavaDoc;
23 import javax.servlet.ServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletRequest JavaDoc;
25 import javax.servlet.jsp.PageContext JavaDoc;
26
27 /** Some helper methods for creating URLs that can handle relative or absolute
28   * URIs or full URLs.
29   *
30   * @author <a HREF="mailto:james.strachan@metastuff.com">James Strachan</a>
31   * @version $Revision: 1.3 $
32   */

33 public class URLHelper {
34
35     /** @return the URL for the given URI. If the uri contains a ':' then
36       * it is assumed to be a URL, otherwise a local URI resource is used.
37       */

38     public static URL JavaDoc createURL(String JavaDoc uri, PageContext JavaDoc pageContext) throws MalformedURLException JavaDoc {
39         if ( uri.indexOf( ":" ) >= 0 ) {
40             return new URL JavaDoc( uri );
41         }
42         else {
43             return getResourceURL( uri, pageContext );
44         }
45     }
46     
47     /** @return the URL object for the given resource URI using the
48       * ServletContext.getResource(String) method.
49       * If the path does not start with a '/' character then a relative
50       * URI is calculated.
51       */

52     public static URL JavaDoc getResourceURL(String JavaDoc uri, PageContext JavaDoc pageContext) throws MalformedURLException JavaDoc {
53         if ( uri.charAt(0) != '/' ) {
54             // calculate a URI relative to the current JSP page
55
HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc) pageContext.getRequest();
56             String JavaDoc path = request.getServletPath();
57             if ( path.length() > 0 ) {
58                 int index = path.lastIndexOf( '/' );
59                 if ( index >= 0 ) {
60                     String JavaDoc prefix = path.substring(0, index + 1);
61                     uri = prefix + uri;
62                 }
63             }
64         }
65         return pageContext.getServletContext().getResource( uri );
66     }
67 }
68
Popular Tags