package moreservlets;

import javax.servlet.http.*;

/** A small set of utilities to simplify the use of URLs in
 *  Web applications.
 *  <P>
 *  Taken from More Servlets and JavaServer Pages
 *  from Prentice Hall and Sun Microsystems Press,
 *  http://www.moreservlets.com/.
 *  &copy; 2002 Marty Hall; may be freely used or adapted.
 */

public class AppUtils {
  
  /** For use in URLs referenced by JSP pages or servlets, where
   *  you want to avoid hardcoding the Web app name. Replace
   *         <PRE><XMP>
   *  <IMG SRC="/images/foo.gif" ...>
   *  with the following two lines:
   *  <% String imageURL = webAppURL("/images/foo.gif",
   *                                 request); %>
   *  <IMG SRC="<%= imageURL %>"...>
   *
   *         </XMP></PRE>
   */
   
  public static String webAppURL(String origURL,
                                 HttpServletRequest request) {
    return(request.getContextPath() + origURL);
  }

  /** For use when you want to support session tracking with
   *  URL encoding and you are putting a URL
   *  beginning with a slash into a page from a Web app.
   */

  public static String encodeURL(String origURL,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
    return(response.encodeURL(webAppURL(origURL, request)));
  }

  /** For use when you want to support session tracking with
   *  URL encoding and you are using sendRedirect to send a URL
   *  beginning with a slash to the client.
   */
  
  public static String encodeRedirectURL
                                (String origURL,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
    return(response.encodeRedirectURL
                         (webAppURL(origURL, request)));
  }
}
    
