View Javadoc
1   /* 
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   *
14   */
15  package org.esigate.servlet.impl;
16  
17  import javax.servlet.http.HttpServletRequest;
18  
19  import org.slf4j.Logger;
20  import org.slf4j.LoggerFactory;
21  
22  /**
23   * Utility class to work with Servlet request urls.
24   * 
25   * @author Nicolas Richeton
26   * 
27   */
28  public final class RequestUrl {
29      public static final Logger LOG = LoggerFactory.getLogger(RequestUrl.class);
30  
31      private RequestUrl() {
32  
33      }
34  
35      /**
36       * Get the relative url to the current servlet.
37       * <p>
38       * Uses the request URI and removes : the context path, the servlet path if used.
39       * 
40       * @param request
41       *            The current HTTP request
42       * @param servlet
43       *            true to remove the servlet path
44       * @return the url, relative to the servlet mapping.
45       */
46      public static String getRelativeUrl(HttpServletRequest request, boolean servlet) {
47          // Raw request url
48          String requestURI = request.getRequestURI();
49          // Application (war) context path
50          String contextPath = request.getContextPath();
51          // Servlet mapping
52          String servletPath = request.getServletPath();
53  
54          String relativeUrl = requestURI;
55  
56          // Remove application context path
57          if (contextPath != null && relativeUrl.startsWith(contextPath)) {
58              relativeUrl = relativeUrl.substring(contextPath.length());
59          }
60  
61          // Remove servlet mapping path
62          if (servlet && servletPath != null && relativeUrl.startsWith(servletPath)) {
63              relativeUrl = relativeUrl.substring(servletPath.length());
64          }
65  
66          if (LOG.isDebugEnabled()) {
67              LOG.debug("requestURI: {}, contextPath: {}, servletPath: {}, relativeUrl: {}, ", requestURI, contextPath,
68                      servletPath, relativeUrl);
69          }
70  
71          return relativeUrl;
72      }
73  }