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.leixl.easyframework.web.CookieUtils.java

/**
 * ?cookie?/* ww w .  j  a  v  a2 s  .  c  om*/
 * 
 * @param request
 * @param response
 * @param name
 * @param value
 * @param expiry
 * @param domain
 * @return
 */
public static Cookie addCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, Integer expiry, String domain) {
    Cookie cookie = new Cookie(name, value);
    if (expiry != null) {
        cookie.setMaxAge(expiry);
    }
    if (StringUtils.isNotBlank(domain)) {
        cookie.setDomain(domain);
    }
    String ctx = request.getContextPath();
    cookie.setPath(StringUtils.isBlank(ctx) ? "/" : ctx);
    response.addCookie(cookie);
    return cookie;
}

From source file:org.onebusaway.webapp.impl.WebappServiceServletImpl.java

/**
 * Used by HybridServiceServlet./*from  w  w  w  .  ja va 2  s.  com*/
 */
private static SerializationPolicy customLoadSerializationPolicy(HttpServlet servlet,
        HttpServletRequest request, String moduleBaseURL, String strongName) {

    // The request can tell you the path of the web app relative to the
    // container root.
    String contextPath = request.getContextPath();

    String modulePath = null;
    if (moduleBaseURL != null) {
        try {
            modulePath = new URL(moduleBaseURL).getPath();
        } catch (MalformedURLException ex) {
            // log the information, we will default
            servlet.log("Malformed moduleBaseURL: " + moduleBaseURL, ex);
        }
    }

    SerializationPolicy serializationPolicy = null;

    /*
     * Check that the module path must be in the same web app as the servlet
     * itself. If you need to implement a scheme different than this, override
     * this method.
     */
    if (modulePath == null) {
        String message = "ERROR: The module path requested, " + modulePath
                + ", is not in the same web application as this servlet, " + contextPath
                + ".  Your module may not be properly configured or your client and server code maybe out of date.";
        servlet.log(message, null);
    } else {

        // TODO : Hack for Nokia demo
        // /Users/bdferris/Documents/Aptana%20Studio%20Workspace/nokia-hello-world/
        if (modulePath.endsWith("nokia-hello-world/"))
            modulePath = "/where/mobile/";

        if (!modulePath.startsWith(contextPath))
            modulePath = contextPath + modulePath;

        // Strip off the context path from the module base URL. It should be a
        // strict prefix.
        String contextRelativePath = modulePath.substring(contextPath.length());

        String serializationPolicyFilePath = SerializationPolicyLoader
                .getSerializationPolicyFileName(contextRelativePath + strongName);

        // Open the RPC resource file and read its contents.
        InputStream is = servlet.getServletContext().getResourceAsStream(serializationPolicyFilePath);
        try {
            if (is != null) {
                try {
                    serializationPolicy = SerializationPolicyLoader.loadFromStream(is, null);
                } catch (ParseException e) {
                    servlet.log("ERROR: Failed to parse the policy file '" + serializationPolicyFilePath + "'",
                            e);
                } catch (IOException e) {
                    servlet.log("ERROR: Could not read the policy file '" + serializationPolicyFilePath + "'",
                            e);
                }
            } else {
                String message = "ERROR: The serialization policy file '" + serializationPolicyFilePath
                        + "' was not found; did you forget to include it in this deployment?";
                servlet.log(message, null);
            }
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // Ignore this error
                }
            }
        }
    }

    return serializationPolicy;
}

From source file:org.duracloud.duradmin.spaces.controller.ContentItemController.java

public static String getBaseURL(HttpServletRequest request) throws MalformedURLException {
    URL url = new URL(request.getRequestURL().toString());
    int port = url.getPort();
    String baseURL = url.getProtocol() + "://" + url.getHost() + ":"
            + (port > 0 && port != 80 ? url.getPort() : "") + request.getContextPath();
    return baseURL;
}

From source file:info.magnolia.cms.util.RequestDispatchUtil.java

/**
 * Returns true if processing took place, even if it fails.
 *///from  w w  w.j  av a 2  s.  c o  m
public static boolean dispatch(String targetUri, HttpServletRequest request, HttpServletResponse response) {

    if (targetUri == null) {
        return false;
    }

    if (targetUri.startsWith(REDIRECT_PREFIX)) {
        String redirectUrl = StringUtils.substringAfter(targetUri, REDIRECT_PREFIX);
        try {

            if (isInternal(redirectUrl)) {
                redirectUrl = request.getContextPath() + redirectUrl;
            }

            response.sendRedirect(response.encodeRedirectURL(redirectUrl));

        } catch (IOException e) {
            log.error("Failed to redirect to {}:{}", targetUri, e.getMessage());
        }
        return true;
    }

    if (targetUri.startsWith(PERMANENT_PREFIX)) {
        String permanentUrl = StringUtils.substringAfter(targetUri, PERMANENT_PREFIX);
        try {

            if (isInternal(permanentUrl)) {
                if (isUsingStandardPort(request)) {
                    permanentUrl = new URL(request.getScheme(), request.getServerName(),
                            request.getContextPath() + permanentUrl).toExternalForm();
                } else {
                    permanentUrl = new URL(request.getScheme(), request.getServerName(),
                            request.getServerPort(), request.getContextPath() + permanentUrl).toExternalForm();
                }
            }

            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", permanentUrl);

        } catch (MalformedURLException e) {
            log.error("Failed to create permanent url to redirect to {}:{}", targetUri, e.getMessage());
        }
        return true;
    }

    if (targetUri.startsWith(FORWARD_PREFIX)) {
        String forwardUrl = StringUtils.substringAfter(targetUri, FORWARD_PREFIX);
        try {
            request.getRequestDispatcher(forwardUrl).forward(request, response);
        } catch (Exception e) {
            log.error("Failed to forward to {} - {}:{}",
                    new Object[] { forwardUrl, ClassUtils.getShortClassName(e.getClass()), e.getMessage() });
        }
        return true;
    }

    return false;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.authenticate.LogoutRedirector.java

/**
 * If the page they were on was not restricted, send them back to it.
 * Otherwise, send them to the home page.
 *//*from www  .j ava2s  . c  om*/
public static String getRedirectUrl(HttpServletRequest request, HttpServletResponse response, String referrer)
        throws IOException {
    String referringUri = figureUriFromUrl(request, referrer);

    log.debug("referringUri: '" + referringUri + "', restrictedUris=" + getRestrictedPageUris(request));

    if ((referringUri == null) || (getRestrictedPageUris(request).contains(referringUri))) {
        log.debug("Sending to home page.");
        return request.getContextPath();
    } else {
        log.debug("Sending back to referring page.");
        return referrer;
    }
}

From source file:org.impalaframework.extension.mvc.util.RequestModelHelper.java

/**
 * //from   www .j  a va  2  s  .com
 * @param logger
 * @param request
 */
public static void maybeDebugRequest(Log logger, HttpServletRequest request) {

    if (logger.isDebugEnabled()) {

        logger.debug("#####################################################################################");
        logger.debug("---------------------------- Request details ---------------------------------------");
        logger.debug("Request context path: " + request.getContextPath());
        logger.debug("Request path info: " + request.getPathInfo());
        logger.debug("Request path translated: " + request.getPathTranslated());
        logger.debug("Request query string: " + request.getQueryString());
        logger.debug("Request servlet path: " + request.getServletPath());
        logger.debug("Request request URI: " + request.getRequestURI());
        logger.debug("Request request URL: " + request.getRequestURL());
        logger.debug("Request session ID: " + request.getRequestedSessionId());

        logger.debug("------------------------------------------------ ");
        logger.debug("Parameters ------------------------------------- ");
        final Enumeration<String> parameterNames = request.getParameterNames();

        Map<String, String> parameters = new TreeMap<String, String>();

        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String value = request.getParameter(name);
            final String lowerCase = name.toLowerCase();
            if (lowerCase.contains("password") || lowerCase.contains("cardnumber")) {
                value = "HIDDEN";
            }
            parameters.put(name, value);
        }

        //now output            
        final Set<String> parameterKeys = parameters.keySet();
        for (String key : parameterKeys) {
            logger.debug(key + ": " + parameters.get(key));
        }

        logger.debug("------------------------------------------------ ");

        Map<String, Object> attributes = new TreeMap<String, Object>();

        logger.debug("Attributes ------------------------------------- ");
        final Enumeration<String> attributeNames = request.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String name = attributeNames.nextElement();
            Object value = request.getAttribute(name);
            final String lowerCase = name.toLowerCase();
            if (lowerCase.contains("password") || lowerCase.contains("cardnumber")) {
                value = "HIDDEN";
            }
            attributes.put(name, value);
        }

        //now output
        final Set<String> keys = attributes.keySet();
        for (String name : keys) {
            Object value = attributes.get(name);
            logger.debug(name + ": " + (value != null ? value.toString() : value));
        }

        logger.debug("------------------------------------------------ ");
        logger.debug("#####################################################################################");
    } else {
        if (logger.isInfoEnabled()) {
            logger.info(
                    "#####################################################################################");
            logger.info("Request query string: " + request.getQueryString());
            logger.info("Request request URI: " + request.getRequestURI());
            logger.info(
                    "#####################################################################################");
        }
    }
}

From source file:com.soolr.core.web.Servlets.java

public static String getBasePath(HttpServletRequest request) {
    String requestURL = request.getRequestURL().toString();
    String requestURI = request.getRequestURI();
    String host = StringUtils.substringBeforeLast(requestURL, requestURI);
    String contextPath = request.getContextPath();
    return StringUtils.removeEnd(host + contextPath, "/");
}

From source file:com.manydesigns.elements.util.Util.java

public static String getAbsoluteUrl(HttpServletRequest req, String url) {
    StringBuilder sb = new StringBuilder();

    Matcher matcher = pattern.matcher(url);
    if (matcher.lookingAt()) {
        return url;
    }/*from   w  w  w . jav  a2 s.c  o m*/

    if (!"/".equals(req.getContextPath())) {
        sb.append(req.getContextPath());
    }

    if (!url.startsWith("/")) {
        sb.append("/");
    }

    sb.append(url);

    return sb.toString();
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.VitroHttpServlet.java

private static String assembleLoginUrlWithReturn(HttpServletRequest request, String afterLoginUrl) {
    String encodedAfterLoginUrl = afterLoginUrl;
    try {/*w ww. j a  v  a2s . co  m*/
        encodedAfterLoginUrl = URLEncoder.encode(afterLoginUrl, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.error("Really? No UTF-8 encoding?", e);
    }
    return request.getContextPath() + Controllers.AUTHENTICATE + "?afterLogin=" + encodedAfterLoginUrl;
}

From source file:com.liusoft.dlog4j.util.RequestUtils.java

/**
 * ?URL/*from   www . ja va2 s .  c  o m*/
 * @param req
 * @return
 */
public static String getRequestURL(HttpServletRequest req) {
    StringBuffer url = new StringBuffer(req.getRequestURI());
    String param = req.getQueryString();
    if (param != null) {
        url.append('?');
        url.append(param);
    }
    String path = url.toString();
    return path.substring(req.getContextPath().length());
}