KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > io > 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.io;
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     public static URL JavaDoc createURL(String JavaDoc uri, PageContext JavaDoc pageContext) throws MalformedURLException JavaDoc {
36         ServletContext JavaDoc context = pageContext.getServletContext();
37         ServletRequest JavaDoc request = pageContext.getRequest();
38         if ( request instanceof HttpServletRequest JavaDoc ) {
39             return createURL( uri, (HttpServletRequest JavaDoc) request, context );
40         }
41         else if ( uri.startsWith( "/" ) ) {
42             int port = request.getServerPort();
43             String JavaDoc host = request.getServerName();
44             String JavaDoc protocol = "http";
45             return new URL JavaDoc( protocol, host, port, uri );
46         }
47         else {
48             return new URL JavaDoc(uri);
49         }
50     }
51     
52     public static URL JavaDoc createURL(String JavaDoc uri, HttpServletRequest JavaDoc request, ServletContext JavaDoc context) throws MalformedURLException JavaDoc {
53         if ( uri.startsWith( "/" ) ) {
54             int port = request.getServerPort();
55             String JavaDoc host = request.getServerName();
56             String JavaDoc protocol = "http";
57             String JavaDoc path = request.getContextPath() + uri;
58             return new URL JavaDoc( protocol, host, port, path );
59         }
60         else {
61             return new URL JavaDoc( uri );
62         }
63     }
64 }
65
Popular Tags