Example usage for javax.servlet.http HttpServletRequest getQueryString

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

Introduction

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

Prototype

public String getQueryString();

Source Link

Document

Returns the query string that is contained in the request URL after the path.

Usage

From source file:org.jasig.cas.support.pac4j.web.flow.ClientBackChannelAction.java

private void log(HttpServletRequest request) {

    logger.debug("=========================================================");
    logger.debug("ClientBackChannelAction.doExecute: ");
    logger.debug("request.method: " + request.getMethod());
    logger.debug("request.requestURI: " + request.getRequestURI());
    logger.debug("request.queryString: " + request.getQueryString());
    logger.debug("request. host port remoteaddress: " + request.getRemoteHost() + " " + request.getRemotePort()
            + " " + request.getRemoteAddr());
    logger.debug("request. parameter:");
    Enumeration enParams = request.getParameterNames();
    while (enParams.hasMoreElements()) {
        String paramName = (String) enParams.nextElement();
        logger.debug(paramName + ": " + request.getParameter(paramName));
    }//from ww w .  j a v  a  2s  .c om

    logger.debug("request. attribute:");
    Enumeration enParams2 = request.getAttributeNames();
    while (enParams2.hasMoreElements()) {
        String paramName2 = (String) enParams2.nextElement();
        logger.debug(paramName2 + ": " + request.getAttribute(paramName2));
    }
    logger.debug("=========================================================");
}

From source file:com.bluexml.side.Framework.alfresco.shareLanguagePicker.CustomDispatcherServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean errorOccured = false;

    // bind a timer for reporting of dispatches
    if (Timer.isTimerEnabled()) {
        Timer.bindTimer(request);
        Timer.start(request, "service");
    }/*  w w  w .  ja v a 2s. c o  m*/

    if (logger.isDebugEnabled()) {
        String qs = request.getQueryString();
        logger.debug("Processing URL: (" + request.getMethod() + ") " + request.getRequestURI()
                + ((qs != null && qs.length() != 0) ? ("?" + qs) : ""));
    }

    // apply language from browser locale setting
    setLanguageFromLayoutParam(request);

    // no caching for generated page data
    setNoCacheHeaders(response);

    // set response content type and charset
    response.setContentType(MIMETYPE_HTML);

    // initialize the request context
    RequestContext context = null;
    try {
        context = FrameworkHelper.initRequestContext(request);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

    if (logger.isDebugEnabled())
        debug(context, "Context created for request: " + request.getRequestURI());

    // stamp any theme information onto the request
    ThemeUtil.applyTheme(context, request);

    // create the top render context
    RenderContext renderContext = RenderHelper.provideRenderContext(context, request, response);

    // dispatch to render the page
    try {
        if (Timer.isTimerEnabled())
            Timer.start(request, "dispatch");

        // dispatch to page processing code
        dispatch(renderContext);

        if (Timer.isTimerEnabled())
            Timer.stop(request, "dispatch");
    } catch (Throwable t) {
        /**
         * The framework should naturally catch exceptions and handle
         * them gracefully using the system pages defined in the
         * configuration file.  For instance, if a component fails
         * to render, it should resort to displaying itself with
         * a friendly message.
         * 
         * On the other hand, it could be the case that something
         * really nasty came this way - for instance an Error.
         * 
         * Or it may be the case that a system page was unavailable
         * to handle the error.  In that case, the exception will fall
         * back here as a RequestDispatchException.
         * 
         * It may also be the case that the system administrator
         * wishes the errors to trickle back.  This would be the
         * typical setup if the administrator wishes the servlet
         * container to handle the error.
         * 
         * Finally, they may have opted to throw a Runtime Exception
         * back.  We must handle that case as well.
         */

        errorOccured = true;

        logger.error(t);

        // for now, we will throw back to servlet container
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else {
            throw new ServletException("Error during dispatch: " + t.getMessage(), t);
        }
    } finally {
        // clean up - unless an error occured as then we don't want to commit the response yet
        if (!errorOccured) {
            response.getWriter().flush();
            response.getWriter().close();
        }

        // release any resources associated with the request context
        context.release();

        // stop the service timer and print out any timing information (if enabled)
        if (Timer.isTimerEnabled()) {
            Timer.stop(request, "service");
            Timer.reportAll(request);
            Timer.unbindTimer(request);
        }
    }
}

From source file:com.centurylink.mdw.hub.servlet.RestServlet.java

protected String handleRequest(HttpServletRequest request, HttpServletResponse response,
        Map<String, String> metaInfo) throws ServiceException, IOException {

    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug(/*  w w  w .java2 s. com*/
                getClass().getSimpleName() + " " + request.getMethod() + ":\n   " + request.getRequestURI()
                        + (request.getQueryString() == null ? "" : ("?" + request.getQueryString())));
    }

    String requestString = null;
    // DELETE can have a body in some containers
    if (!"GET".equalsIgnoreCase(request.getMethod())) {
        BufferedReader reader = request.getReader();
        StringBuffer requestBuffer = new StringBuffer(
                request.getContentLength() < 0 ? 0 : request.getContentLength());
        String line;
        while ((line = reader.readLine()) != null)
            requestBuffer.append(line).append('\n');

        // log request
        requestString = requestBuffer.toString();
        if (logger.isMdwDebugEnabled()) {
            logger.mdwDebug(
                    getClass().getSimpleName() + " " + request.getMethod() + " Request:\n" + requestString);
        }
    }

    authenticate(request, metaInfo, requestString);
    if (metaInfo.containsKey(Listener.METAINFO_REQUEST_PAYLOAD)) {
        requestString = metaInfo.get(Listener.METAINFO_REQUEST_PAYLOAD);
        metaInfo.remove(Listener.METAINFO_REQUEST_PAYLOAD);
    }

    Set<String> reqHeaderKeys = new HashSet<String>(metaInfo.keySet());
    String responseString = new ListenerHelper().processEvent(requestString, metaInfo);
    populateResponseHeaders(reqHeaderKeys, metaInfo, response);
    if (metaInfo.get(Listener.METAINFO_CONTENT_TYPE) == null)
        response.setContentType("application/json");
    else
        response.setContentType(metaInfo.get(Listener.METAINFO_CONTENT_TYPE));

    if (metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE) != null
            && !metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE).equals("0"))
        response.setStatus(Integer.parseInt(metaInfo.get(Listener.METAINFO_HTTP_STATUS_CODE)));

    if (logger.isMdwDebugEnabled()) {
        logger.mdwDebug(
                getClass().getSimpleName() + " " + request.getMethod() + " Response:\n" + responseString);
    }

    return responseString;
}

From source file:com.stormpath.sdk.servlet.mvc.FormController.java

@SuppressWarnings("unchecked")
protected Map<String, ?> createModel(HttpServletRequest request, HttpServletResponse response) {
    List<ErrorModel> errors = null;
    // We need to look for error in queryString now that we moved SpringSecurity to in in front of us: https://github.com/stormpath/stormpath-sdk-java/issues/915
    String queryString = request.getQueryString();
    boolean requestContainsError = request.getParameter("error") != null
            || (queryString != null && queryString.contains("error"));
    if (requestContainsError) {
        errors = new ArrayList<>();
        ErrorModel error = null;/*from  w  w w.j av  a2  s  .  c  o m*/
        HttpSession session = request.getSession(false);
        // session null check fixes https://github.com/stormpath/stormpath-sdk-java/issues/908
        if (session != null && session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY) != null) {
            //The login page is being re-rendered after an unsuccessful authentication attempt from Spring Security
            //Fix for https://github.com/stormpath/stormpath-sdk-java/issues/648
            //See StormpathAuthenticationFailureHandler
            error = (ErrorModel) session.getAttribute(SPRING_SECURITY_AUTHENTICATION_FAILED_KEY);
        } else {
            //Fix for https://github.com/stormpath/stormpath-sdk-java/issues/1138
            //TODO This breaks i18n. Fix when Stormpath backend returns specific password policy failure codes.
            error = ErrorModel.builder().setStatus(HttpStatus.SC_BAD_REQUEST)
                    .setMessage(request.getParameter("error")).build();
        }
        errors.add(error);
    }
    return createModel(request, response, null, errors);
}

From source file:com.web.server.ProxyServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);/*ww  w  .  j  a v  a  2s .com*/
    uri.append(req.getRequestURI());

    // Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    //       if (contentLength == -1)
    //          throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //             System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:com.redhat.rhn.frontend.servlets.DumpFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        // handle request
        HttpServletRequest request = (HttpServletRequest) req;
        log.debug("Entered doFilter() ===================================");
        log.debug("AuthType: " + request.getAuthType());
        log.debug("Method: " + request.getMethod());
        log.debug("PathInfo: " + request.getPathInfo());
        log.debug("Translated path: " + request.getPathTranslated());
        log.debug("ContextPath: " + request.getContextPath());
        log.debug("Query String: " + request.getQueryString());
        log.debug("Remote User: " + request.getRemoteUser());
        log.debug("Remote Host: " + request.getRemoteHost());
        log.debug("Remote Addr: " + request.getRemoteAddr());
        log.debug("SessionId: " + request.getRequestedSessionId());
        log.debug("uri: " + request.getRequestURI());
        log.debug("url: " + request.getRequestURL().toString());
        log.debug("Servlet path: " + request.getServletPath());
        log.debug("Server Name: " + request.getServerName());
        log.debug("Server Port: " + request.getServerPort());
        log.debug("RESPONSE encoding: " + resp.getCharacterEncoding());
        log.debug("REQUEST encoding: " + request.getCharacterEncoding());
        log.debug("JVM encoding: " + System.getProperty("file.encoding"));
        logSession(request.getSession());
        logHeaders(request);/* ww  w  .j av a2s. com*/
        logCookies(request.getCookies());
        logParameters(request);
        logAttributes(request);
        log.debug("Calling chain.doFilter() -----------------------------");
    }

    chain.doFilter(req, resp);

    if (log.isDebugEnabled()) {
        log.debug("Returned from chain.doFilter() -----------------------");
        log.debug("Handle Response, not much to print");
        log.debug("Response: " + resp.toString());
        log.debug("Leaving doFilter() ===================================");
    }
}

From source file:com.logiclander.jaasmine.authentication.http.JaasLoginFilter.java

private void cacheRequestUri(HttpServletRequest req) {

    HttpSession sess = req.getSession();

    sess.setAttribute(AuthenticationService.REQUEST_URI_KEY, req.getRequestURI());

    if (req.getQueryString() != null) {
        sess.setAttribute(AuthenticationService.REQUST_QUERY_KEY, req.getQueryString());
    }// w  w w . j av  a 2s  . c o  m
}

From source file:net.sf.ehcache.constructs.web.filter.Filter.java

/**
 * This method should throw IOExceptions, not wrap them.
 *//*w ww. j  a va  2  s  .c o m*/
private void logThrowable(final Throwable throwable, final HttpServletRequest httpRequest)
        throws ServletException, IOException {
    StringBuffer messageBuffer = new StringBuffer("Throwable thrown during doFilter on request with URI: ")
            .append(httpRequest.getRequestURI()).append(" and Query: ").append(httpRequest.getQueryString());
    String message = messageBuffer.toString();
    boolean matchFound = matches(throwable);
    if (matchFound) {
        try {
            if (suppressStackTraces) {
                Method method = Log.class.getMethod(exceptionsToLogDifferentlyLevel,
                        new Class[] { Object.class });
                method.invoke(LOG, new Object[] { throwable.getMessage() });
            } else {
                Method method = Log.class.getMethod(exceptionsToLogDifferentlyLevel,
                        new Class[] { Object.class, Throwable.class });
                method.invoke(LOG, new Object[] { throwable.getMessage(), throwable });
            }
        } catch (Exception e) {
            LOG.fatal("Could not invoke Log method for " + exceptionsToLogDifferentlyLevel, e);
        }
        if (throwable instanceof IOException) {
            throw (IOException) throwable;
        } else {
            throw new ServletException(message, throwable);
        }
    } else {

        if (suppressStackTraces) {
            LOG.warn(messageBuffer.append(throwable.getMessage()).append("\nTop StackTraceElement: ")
                    .append(throwable.getStackTrace()[0].toString()));
        } else {
            LOG.warn(messageBuffer.append(throwable.getMessage()), throwable);
        }
        if (throwable instanceof IOException) {
            throw (IOException) throwable;
        } else {
            throw new ServletException(throwable);
        }
    }
}

From source file:your.microservice.core.util.YourServletUriComponentsBuilder.java

/**
 * Prepare a builder by copying the scheme, host, port, path, and
 * query string of an HttpServletRequest.
 * @param request to build path from//w w w . j a v  a2s  . co  m
 * @return a URI component builder
 */
public static YourServletUriComponentsBuilder fromRequest(HttpServletRequest request) {
    String scheme = request.getScheme();
    String host = request.getServerName();
    int port = request.getServerPort();

    String hostHeader = request.getHeader("X-Forwarded-Host");
    if (StringUtils.hasText(hostHeader)) {
        String[] hosts = StringUtils.commaDelimitedListToStringArray(hostHeader);
        String hostToUse = hosts[0];
        if (hostToUse.contains(":")) {
            String[] hostAndPort = StringUtils.split(hostToUse, ":");
            host = hostAndPort[0];
            port = Integer.parseInt(hostAndPort[1]);
        } else {
            host = hostToUse;
            port = -1;
        }
    }

    String portHeader = request.getHeader("X-Forwarded-Port");
    if (StringUtils.hasText(portHeader)) {
        port = Integer.parseInt(portHeader);
    }

    String protocolHeader = request.getHeader("X-Forwarded-Proto");
    if (StringUtils.hasText(protocolHeader)) {
        scheme = protocolHeader;
    }

    YourServletUriComponentsBuilder builder = new YourServletUriComponentsBuilder();
    builder.scheme(scheme);
    builder.host(host);
    if (scheme.equals("http") && port != 80 || scheme.equals("https") && port != 443) {
        builder.port(port);
    }
    builder.pathFromRequest(request);
    builder.query(request.getQueryString());
    return builder;
}

From source file:com.idega.core.cache.filter.Filter.java

private void logThrowable(final Throwable throwable, final HttpServletRequest httpRequest)
        throws ServletException {
    StringBuffer messageBuffer = new StringBuffer("Throwable thrown during doFilter on request with URI: ")
            .append(httpRequest.getRequestURI()).append(" and Query: ").append(httpRequest.getQueryString());
    String message = messageBuffer.toString();
    boolean matchFound = matches(throwable);
    if (matchFound) {
        try {//  w  w  w. j  a va2  s. co m
            if (this.suppressStackTraces) {
                Method method = Log.class.getMethod(this.exceptionsToLogDifferentlyLevel,
                        new Class[] { Object.class });
                method.invoke(LOG, new Object[] { throwable.getMessage() });
            } else {
                Method method = Log.class.getMethod(this.exceptionsToLogDifferentlyLevel,
                        new Class[] { Object.class, Throwable.class });
                method.invoke(LOG, new Object[] { throwable.getMessage(), throwable });
            }
        } catch (Exception e) {
            LOG.fatal("Could not invoke Log method for " + this.exceptionsToLogDifferentlyLevel, e);
        }
        throw new ServletException(message, throwable);
    } else {

        if (this.suppressStackTraces) {
            LOG.warn(messageBuffer.append(throwable.getMessage()).append("\nTop StackTraceElement: ")
                    .append(throwable.getStackTrace()[0].toString()));
        } else {
            LOG.warn(messageBuffer.append(throwable.getMessage()), throwable);
        }
        throw new ServletException(throwable);
    }
}