Example usage for javax.servlet.http HttpServletRequest getServletPath

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

Introduction

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

Prototype

public String getServletPath();

Source Link

Document

Returns the part of this request's URL that calls the servlet.

Usage

From source file:com.alfaariss.oa.sso.web.profile.user.UserProfile.java

private void processLogout(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        ISession session) throws OAException {
    try {//from ww  w  . j a  v  a2s.c  om
        String sTGTCookie = _cookieTool.getCookieValue(WebSSOServlet.TGT_COOKIE_NAME, servletRequest);
        if (sTGTCookie == null) {
            _logger.debug("No TGT cookie found, user already loggedout");

            if (session != null) {
                session.expire();
                session.persist();
            }

            processDefault(servletRequest, servletResponse, null);
            return;
        }

        String sServletPath = servletRequest.getServletPath();

        if (session == null) {
            String sRequestURL = _sRedirectURL;
            if (sRequestURL == null) {
                sRequestURL = servletRequest.getRequestURL().toString();
                if (sRequestURL.endsWith("/"))
                    sRequestURL = sRequestURL.substring(0, sRequestURL.length() - 1);

                if (sRequestURL.endsWith(PROFILE_ID + "/" + TARGET_LOGOUT))
                    sRequestURL = sRequestURL.substring(0, sRequestURL.length() - TARGET_LOGOUT.length());
            }

            session = _sessionFactory.createSession(_sUserPageRequestorId);
            session.persist();//resist for creating the session id

            StringBuilder sbProfileURL = new StringBuilder(sRequestURL);
            if (!sRequestURL.endsWith("/"))
                sbProfileURL.append("/");
            sbProfileURL.append("?");
            sbProfileURL.append(ISession.ID_NAME);
            sbProfileURL.append("=");
            sbProfileURL.append(session.getId());
            session.setProfileURL(sbProfileURL.toString());
        }

        _logger.debug("Starting logout");

        session.persist();//update session; also to increase lifetime

        servletRequest.setAttribute(ISession.ID_NAME, session);

        StringBuilder sbForward = new StringBuilder(sServletPath);
        if (!sServletPath.endsWith("/"))
            sbForward.append("/");
        sbForward.append(LogoutProfile.PROFILE_ID);

        RequestDispatcher oDispatcher = servletRequest.getRequestDispatcher(sbForward.toString());
        if (oDispatcher == null) {
            _logger.warn("There is no requestor dispatcher supported with name: " + sbForward.toString());
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        oDispatcher.forward(servletRequest, servletResponse);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Internal error during logout", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:com.tecapro.inventory.common.action.BaseAction.java

/**
 * check request//from  w w w. j  a v  a  2  s  .co  m
 *
 * @param request
 * @return
 * @throws IOException
 */
private Boolean isNotAcceptAction(HttpServletRequest request) throws IOException {
    Map<?, ?> actList = requestUtil.loadActList(getServlet().getServletContext().getRealPath(""));
    return (!actList.containsKey(request.getServletPath()) && GET_METHOD.equals(request.getMethod()));
}

From source file:com.sinosoft.one.mvc.web.RequestPath.java

public RequestPath(HttpServletRequest request) {
    // method/* w  w  w .j a  v  a 2 s. co m*/
    setMethod(parseMethod(request));

    // ctxpath
    setCtxpath(request.getContextPath());
    String invocationCtxpath = null; // includeinvocationCtxPathincludectxpath
    // dispather, uri, ctxpath
    String uri;
    if (WebUtils.isIncludeRequest(request)) {
        setDispatcher(Dispatcher.INCLUDE);
        uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
        invocationCtxpath = ((String) request.getAttribute(WebUtils.INCLUDE_CONTEXT_PATH_ATTRIBUTE));
        setMvcPath((String) request.getAttribute(WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE));
    } else {
        if (request.getAttribute(MvcConstants.WINDOW_REQUEST_URI) != null) {
            uri = (String) request.getAttribute(MvcConstants.WINDOW_REQUEST_URI);
            request.removeAttribute(MvcConstants.WINDOW_REQUEST_URI);
            request.setAttribute(MvcConstants.IS_WINDOW_REQUEST, "1");
        } else {
            uri = request.getRequestURI();
            request.removeAttribute(MvcConstants.IS_WINDOW_REQUEST);
        }

        this.setMvcPath(request.getServletPath());
        if (request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) == null) {
            this.setDispatcher(Dispatcher.REQUEST);
        } else {
            this.setDispatcher(Dispatcher.FORWARD);
        }
    }
    if (uri.startsWith("http://") || uri.startsWith("https://")) {
        int start = uri.indexOf('/', 9);
        if (start == -1) {
            uri = "";
        } else {
            uri = uri.substring(start);
        }
    }
    if (uri.indexOf('%') != -1) {
        try {
            String encoding = request.getCharacterEncoding();
            if (encoding == null || encoding.length() == 0) {
                encoding = "UTF-8";
            }
            uri = URLDecoder.decode(uri, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    this.setUri(uri);
    // requestPathctxpathincludeinvocationCtxpath

    if (getCtxpath().length() <= 1) {
        setMvcPath(getUri());
    } else {
        setMvcPath(getUri().substring((invocationCtxpath == null ? getCtxpath() : invocationCtxpath).length()));
    }
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionsUtilityToolServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    M_log.debug("doGet: Called");
    M_log.info("request.getPathInfo(): " + request.getPathInfo());
    if (request.getPathInfo().equals(SectionUtilityToolFilter.LTI_PAGE)) {
        response.sendError(403);//  ww w.  j ava 2s  .  c  o  m
        return;
    } else {
        try {
            if (request.getServletPath().equals(MANAGER_SERVLET_NAME)) {
                M_log.debug("Manager Servlet invoked");
                canvasRestApiCall(request, response);
            } else {
                M_log.debug("NOT MANAGER");
                doRequest(request, response); //doRequest will always call fillContext()
            }
        } catch (Exception e) {
            M_log.error("GET request has some exceptions", e);
        }
    }
}

From source file:com.devnexus.ting.web.filter.LoggingFilter4Logback.java

public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final HttpServletResponse response;
    final HttpServletRequest request;

    if (res instanceof HttpServletResponse) {
        response = (HttpServletResponse) res;
    } else {/*from  w ww . jav  a  2s . co m*/
        throw new IllegalStateException("Cannot cast ServletResponse to HttpServletResponse.");
    }

    if (req instanceof HttpServletRequest) {
        request = (HttpServletRequest) req;
    } else {
        throw new IllegalStateException("Cannot cast ServletRequest to HttpServletRequest.");
    }

    final ErrorAwareHttpServletResponseWrapper errorAwareResponse = new ErrorAwareHttpServletResponseWrapper(
            response);

    final String username;

    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null) {
        username = SecurityContextHolder.getContext().getAuthentication().getName();
    } else {
        username = null;
    }

    final String sessionId = request.getSession().getId();
    final String requestUrl = request.getRequestURL().toString();

    MDC.put("username", username);
    MDC.put("sessionId", sessionId);
    MDC.put("requestUrl", requestUrl);

    try {

        chain.doFilter(request, errorAwareResponse);

        if (HttpServletResponse.SC_NOT_FOUND == errorAwareResponse.getErrorCode()) {
            LOGGER.error("Page '" + request.getServletPath() + "' was not found.");
        }

    } finally {
        MDC.remove("username");
        MDC.remove("sessionId");
        MDC.remove("requestUrl");

    }
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

public static String getServerURL(HttpServletRequest req, String relativeServletPath, boolean preserveQS) {
    // for now, only store the servlet context and the serverUrl
    String path = req.getContextPath();

    Integer identifiedPort = req.getServerPort();
    String identifiedHostname = req.getServerName();

    if (identifiedHostname == null || identifiedHostname.length() == 0
            || identifiedHostname.equals("0.0.0.0")) {
        try {//from w  ww  .j  a  va 2s  .c o m
            identifiedHostname = InetAddress.getLocalHost().getCanonicalHostName();
        } catch (UnknownHostException e) {
            identifiedHostname = "127.0.0.1";
        }
    }

    String identifiedScheme = "http";

    if (identifiedPort == null || identifiedPort == 0) {
        if (req.getScheme().equals(identifiedScheme)) {
            identifiedPort = req.getServerPort();
        } else {
            identifiedPort = HtmlConsts.WEB_PORT;
        }
    }

    boolean expectedPort = (identifiedScheme.equalsIgnoreCase("http") && identifiedPort == HtmlConsts.WEB_PORT)
            || (identifiedScheme.equalsIgnoreCase("https") && identifiedPort == HtmlConsts.SECURE_WEB_PORT);

    String serverUrl;
    if (!expectedPort) {
        serverUrl = identifiedScheme + "://" + identifiedHostname + BasicConsts.COLON
                + Integer.toString(identifiedPort) + path;
    } else {
        serverUrl = identifiedScheme + "://" + identifiedHostname + path;
    }

    String query = req.getQueryString();
    if (query == null) {
        if (req.getServletPath().equals("/demowebclient/greet")) {
            if (CLIENT_WEBSITE_CODESVR_PORT.length() != 0) {
                query = "gwt.codesvr=127.0.0.1:" + CLIENT_WEBSITE_CODESVR_PORT;
            } else {
                query = "";
            }
        } else {
            query = "";
        }
    }

    if (query.length() != 0) {
        query = "?" + query;
    }
    return serverUrl + BasicConsts.FORWARDSLASH + relativeServletPath + (preserveQS ? query : "");
}

From source file:org.georchestra.security.Proxy.java

/**
 * Main entry point for methods where the request path is encoded in the
 * path of the URL/* ww  w .j a va  2 s.co m*/
 */
private void handlePathEncodedRequests(HttpServletRequest request, HttpServletResponse response,
        RequestType requestType) {
    try {
        String contextPath = request.getServletPath() + request.getContextPath();
        String forwardRequestURI = buildForwardRequestURL(request);

        logger.debug("handlePathEncodedRequests: -- Handling Request: " + requestType + ":" + forwardRequestURI
                + " from: " + request.getRemoteAddr());

        String sURL = findTarget(forwardRequestURI);

        if (sURL == null) {
            response.sendError(404);
            return;
        }

        URL url;
        try {
            url = new URL(sURL);
        } catch (MalformedURLException e) {
            throw new MalformedURLException(sURL + " is not a valid URL");
        }

        boolean sameHostAndPort = false;

        try {
            sameHostAndPort = isSameHostAndPort(request, url);
        } catch (UnknownHostException e) {
            logger.error("Unknown host in requested URL", e);
            response.sendError(503);
            return;
        }

        if (sameHostAndPort && (isRecursiveCallToProxy(forwardRequestURI, contextPath)
                || isRecursiveCallToProxy(url.getPath(), contextPath))) {
            response.sendError(403,
                    forwardRequestURI + " is a recursive call to this service.  That is not a legal request");
        }

        if (request.getQueryString() != null && !isFormContentType(request)) {
            StringBuilder query = new StringBuilder("?");
            Enumeration paramNames = request.getParameterNames();
            boolean needCasValidation = false;
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                String[] values = request.getParameterValues(name);
                for (String string : values) {
                    if (query.length() > 1) {
                        query.append('&');
                    }
                    // special case: if we have a ticket parameter and no
                    // authentication principal, we need to validate/open
                    // the session against CAS server
                    if ((request.getUserPrincipal() == null)
                            && (name.equals(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER))) {
                        needCasValidation = true;
                    } else {
                        query.append(name);
                        query.append('=');
                        query.append(URLEncoder.encode(string, "UTF-8"));
                    }
                }
            }
            sURL += query;
            if ((needCasValidation) && (urlIsProtected(request, new URL(sURL)))) {
                // loginUrl: sends a redirect to the client with a ?login (or &login if other arguments)
                // since .*login patterns are protected by the SP, this would trigger an authentication
                // onto CAS (which should succeed if the user is already connected onto the platform).
                String loginUrl = String.format("%s%s%s", request.getPathInfo(), query, "login");
                redirectStrategy.sendRedirect(request, response, loginUrl);
                return;
            }
        }

        handleRequest(request, response, requestType, sURL, true);
    } catch (IOException e) {
        logger.error("Error connecting to client", e);
    }
}

From source file:com.fota.fota3g.deviceSetupMgt.controller.FrimwareMgtCTR.java

/**
 *  firmware // ww w .j av a 2 s.  com
 * @param request
 * @param model / maker
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/deviceSetup/FirmwareMgt")
public String getView(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
    if (!request.getServletPath().equals("/commonDevice/deviceSetup/FirmwareMgt")) {
        response.setStatus(403);
        return "redirect:/lresources/errorPage.jsp";
    }

    return "fota3g/deviceSetupMgt/FirmwareMgtView";
}

From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (this.config == null) {
        return;/*from   ww  w.j  a v a 2  s  .  co m*/
    }

    // Just pass through to next filter if we're not at TRACE level
    if (!logger.isTraceEnabled()) {
        chain.doFilter(request, response);
        return;
    }

    // Create a variable to hold the (possibly different) request
    // passed to downstream filters
    ServletRequest downstreamRequest = request;

    // Render the generic servlet request properties
    final StringWriter sw = new StringWriter();
    final PrintWriter writer = new PrintWriter(sw);
    writer.println("Dumping request...");
    writer.println("-----------------------------------------------------");
    writer.println("REQUEST received " + Calendar.getInstance().getTime());
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");

    final Enumeration<Locale> locales = request.getLocales();
    for (int i = 0; locales.hasMoreElements(); i++) {
        if (i > 0) {
            writer.print(", ");
        }
        writer.print(locales.nextElement());
    }
    writer.println();

    final Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        final String name = paramNames.nextElement();
        writer.print("         parameter=" + name + "=");

        final String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                writer.print(", ");
            }
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());

        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }

        final Enumeration<String> headerNames = hrequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String name = headerNames.nextElement();
            final String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());

        // Create a wrapped request that contains the request body
        // and that we will pass to downstream filters
        final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest);
        downstreamRequest = wrappedRequest;
        writer.println(wrappedRequest.getRequestBodyAsString());
    }
    writer.println("-----------------------------------------------------");

    // Log the resulting string
    writer.flush();
    logger.trace(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(downstreamRequest, response);
}