Example usage for javax.servlet.http HttpServletRequest getContextPath

List of usage examples for javax.servlet.http HttpServletRequest getContextPath

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getContextPath.

Prototype

public String getContextPath();

Source Link

Document

Returns the portion of the request URI that indicates the context of the request.

Usage

From source file:com.eryansky.common.web.utils.RequestUtil.java

public static String getAppURL(HttpServletRequest request) {
    StringBuffer url = new StringBuffer();
    int port = request.getServerPort();
    if (port < 0) {
        port = 80;/*w w w  .j av a2  s . co  m*/
    }
    String scheme = request.getScheme();
    url.append(scheme);
    url.append("://");
    url.append(request.getServerName());
    if (((scheme.equals("http")) && (port != 80)) || ((scheme.equals("https")) && (port != 443))) {
        url.append(':');
        url.append(port);
    }
    url.append(request.getContextPath());
    return url.toString();
}

From source file:eu.webtoolkit.jwt.servlet.WebRequest.java

public static String computeScriptName(HttpServletRequest request, Configuration configuration) {
    String scriptName = request.getServletPath();

    if (request.getContextPath() != null)
        scriptName = request.getContextPath() + scriptName;

    if (!scriptName.startsWith("/"))
        scriptName = "/" + scriptName;

    // Jetty will auto-redirect in this case to .../
    // I am not sure if this is according to the servlet spec ?
    if (request.getServletPath().length() == 0 && !scriptName.endsWith("/"))
        scriptName += "/";

    if (configuration.internalDeploymentSize() != 0) {
        String pathInfo = getPathInfo(request, scriptName);
        // Move part of the internal path to the script name
        if (pathInfo != null) {
            for (int i = 0; i < configuration.internalDeploymentSize(); ++i) {
                if (pathInfo.length() > 1) {
                    int slashPos = pathInfo.indexOf('/', 1);
                    if (slashPos == -1)
                        slashPos = pathInfo.length();
                    if (slashPos != -1) {
                        scriptName += pathInfo.substring(0, slashPos);
                        pathInfo = pathInfo.substring(slashPos);
                    }//from  w w w . j  av a2  s. c o  m
                }
            }
        }
        if (!scriptName.endsWith("/"))
            scriptName += "/";
    }

    return scriptName;
}

From source file:ca.uhn.fhir.rest.server.IncomingRequestAddressStrategy.java

/**
 * Determines the servlet's context path.
 * /*from w  w w. j  a  v a  2s.c om*/
 * This is here to try and deal with the wide variation in servers and what they return.
 * 
 * getServletContext().getContextPath() is supposed to return the path to the specific servlet we are deployed as but it's not available everywhere. On some servers getServletContext() can return
 * null (old Jetty seems to suffer from this, see hapi-fhir-base-test-mindeps-server) and on other old servers (Servlet 2.4) getServletContext().getContextPath() doesn't even exist.
 * 
 * theRequest.getContextPath() returns the context for the specific incoming request. It should be available everywhere, but it's likely to be less predicable if there are multiple servlet mappings
 * pointing to the same servlet, so we don't favour it. This is possibly not the best strategy (maybe we should just always use theRequest.getContextPath()?) but so far people seem happy with this
 * behavour across a wide variety of platforms.
 * 
 * If you are having troubles on a given platform/configuration and want to suggest a change or even report incompatibility here, we'd love to hear about it.
 */
public static String determineServletContextPath(HttpServletRequest theRequest, RestfulServer server) {
    String retVal;
    if (server.getServletContext() != null) {
        if (server.getServletContext().getMajorVersion() >= 3
                || (server.getServletContext().getMajorVersion() > 2
                        && server.getServletContext().getMinorVersion() >= 5)) {
            retVal = server.getServletContext().getContextPath();
        } else {
            retVal = theRequest.getContextPath();
        }
    } else {
        retVal = theRequest.getContextPath();
    }
    retVal = StringUtils.defaultString(retVal);
    return retVal;
}

From source file:edu.ucmerced.cas.web.support.CasShibUtil.java

/**
 * This parses out the application name from the request URI.
 * //from   www .j  av a  2s .com
 * <p/>
 * 
 * Convention is as follows: /<contextPath>/shib/<appName>/...<br/>
 * Registrations are typically in casshib-service-registrations.xml.
 * 
 * @see AbstractShibEnabledArgumentExtractor
 * 
 * @throws UnauthorizedServiceException
 *             Thrown if the application name is not registered.
 * @param request
 *            <code>HttpServletRequest</code> object
 * @param registrar
 *            The CASShib service registrar
 * @return The application name from the request URI.
 */
public static String getAppNameFromRequestURI(HttpServletRequest request, CasShibServiceRegistrar registrar) {
    // If the request URI follows the form of
    // <contextPath>/shib/<appName>/<service> then we can determine
    // appName from the requestURI. This is needed for cookie paths (so
    // we have a cookie-per-app) and also redirecting to Shibboleth
    // logout URLs.

    if (request == null || request.getRequestURI() == null)
        return null;

    String appName = null;
    String prefix = (request.getContextPath() != null ? request.getContextPath() : "") + "/shib/";
    if (request.getRequestURI().startsWith(prefix)) {
        appName = request.getRequestURI().substring(prefix.length(), request.getRequestURI().lastIndexOf('/'));
    }

    // Verify the app is a valid registered app. Note if CAS login URLs
    // are protected by the Shibboleth SP web server module then
    // Shibboleth may pre-emptively error out before we ever get here
    // (it might not error out either if you map to a valid default
    // service in shibboleth2.xml).
    try {
        CasShibRegisteredService service = registrar.findServiceByAppName(appName);
        if (service == null) {
            log.warn("Application with name of " + appName + " is not registered.");
            throw new UnauthorizedServiceException("Application name is not registered.");
        }
    } catch (CasShibServiceRegistrar.CasShibServiceRegistrarException e) {
        log.warn("Exception trying to look up application with name of " + appName + ": " + e.getMessage());
        throw new UnauthorizedServiceException("Application name is not registered.", e);
    }

    return (appName);
}

From source file:eionet.util.SecurityUtil.java

/**
 *
 * @return/*from  w w w  . j a  v  a 2s  .  co m*/
 */
private static String getUrlWithContextPath(HttpServletRequest request) {

    StringBuffer url = new StringBuffer(request.getScheme());
    url.append("://").append(request.getServerName());
    if (request.getServerPort() > 0) {
        url.append(":").append(request.getServerPort());
    }
    url.append(request.getContextPath());
    return url.toString();
}

From source file:eionet.util.SecurityUtil.java

/**
 *
 * @param request//ww w  . java  2  s  . c  o m
 * @return
 */
public static String getLoginURL(HttpServletRequest request) {

    // Legacy login mechanism. Used if the application is configured to not use Central Authentication Service (CAS).
    //String result = "javascript:login('" + request.getContextPath() + "')";
    String result = request.getContextPath() + "/" + LoginServlet.LOGIN_JSP;

    boolean rememberAfterLoginUrl = false;
    if (Props.isUseCentralAuthenticationService()) {

        CASFilterConfig casFilterConfig = CASFilterConfig.getInstance();
        if (casFilterConfig != null) {

            String casLoginUrl = casFilterConfig.getInitParameter(CASFilter.LOGIN_INIT_PARAM);
            if (casLoginUrl != null) {

                String casServerName = casFilterConfig.getInitParameter(CASFilter.SERVERNAME_INIT_PARAM);
                if (casServerName == null) {
                    throw new DDRuntimeException("If " + CASFilter.LOGIN_INIT_PARAM
                            + " context parameter has been specified, so must be "
                            + CASFilter.SERVERNAME_INIT_PARAM);
                }

                rememberAfterLoginUrl = true;
                try {
                    result = casLoginUrl + "?service=" + URLEncoder.encode(
                            request.getScheme() + "://" + casServerName + request.getContextPath() + "/login",
                            "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new DDRuntimeException(e.toString(), e);
                }
            }
        }
    } else {
        String servletPath = request.getServletPath();
        if (servletPath == null || !servletPath.endsWith(LoginServlet.LOGIN_JSP)) {
            rememberAfterLoginUrl = true;
        }
    }

    if (rememberAfterLoginUrl) {

        String requestURL = request.getRequestURL().toString();
        if (requestURL != null && !AfterCASLoginServlet.isSkipUrl(requestURL)) {

            request.getSession().setAttribute(AfterCASLoginServlet.AFTER_LOGIN_ATTR_NAME,
                    buildAfterLoginURL(request));
        }
    }

    return result;
}

From source file:net.siegmar.japtproxy.JaptProxy.java

public static String getURL(HttpServletRequest req, boolean serverOnly, Configuration configuration) {

    String scheme = req.getScheme(); // http
    String serverName = req.getServerName(); // hostname.com

    // do we have a remap for this serverName??
    String remap = configuration.getRemap(serverName);
    if (remap != null) {
        serverName = remap;/* ww  w. java  2s  .  c o  m*/
    }

    int serverPort = req.getServerPort(); // 80
    String contextPath = req.getContextPath(); // /mywebapp
    String servletPath = req.getServletPath(); // /servlet/MyServlet
    String pathInfo = req.getPathInfo(); // /a/b;c=123
    String queryString = req.getQueryString(); // d=789

    // Reconstruct original requesting URL
    StringBuilder url = new StringBuilder();
    url.append(scheme).append("://").append(serverName);

    if (serverPort != 80 && serverPort != 443) {
        url.append(":").append(serverPort);
    }

    if (serverOnly)
        return url.toString();

    url.append(contextPath).append(servletPath);

    if (pathInfo != null) {
        url.append(pathInfo);
    }
    if (queryString != null) {
        url.append("?").append(queryString);
    }
    return url.toString();
}

From source file:de.betterform.agent.web.WebUtil.java

/**
*
* @return String for use as root of URLs
*///  ww w  . ja v a  2  s  . c  o m
public static String getContextRoot(HttpServletRequest request) {
    if (request.getAttribute(WebProcessor.ALTERNATIVE_ROOT) != null) {
        return (String) request.getAttribute(WebProcessor.ALTERNATIVE_ROOT);
    } else {
        return request.getContextPath();
    }
}

From source file:info.magnolia.cms.core.Path.java

/**
 * Returns the decoded URI of the current request, without the context path.
 * @param req request//from  ww w .  j  av a  2  s  .  co  m
 * @return request URI without servlet context
 */
private static String getDecodedURI(HttpServletRequest req) {
    String encoding = StringUtils.defaultString(req.getCharacterEncoding(), ENCODING_DEFAULT);
    String decodedURL = null;
    try {
        decodedURL = URLDecoder.decode(req.getRequestURI(), encoding);
    } catch (UnsupportedEncodingException e) {
        decodedURL = req.getRequestURI();
    }
    return StringUtils.substringAfter(decodedURL, req.getContextPath());
}

From source file:com.lm.lic.manager.util.GenUtil.java

/**
 * Extract the requestded uri/ resource in raw form befor the context path was appended to it.
 * //ww  w  . j  av a 2  s. c  o m
 * @param req
 * @return
 */
public static String extractRawUri(HttpServletRequest req) {
    String uri = req.getRequestURI();
    String contextPath = req.getContextPath();
    if (contextPath == null || contextPath.length() <= 0)
        return uri;
    int length = contextPath.length();
    uri = uri.substring(length);
    return uri;
}