Java Code Examples for javax.servlet.http.HttpServletRequest.getQueryString()

The following are Jave code examples for showing how to use getQueryString() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: apache-tomcat-7.0.73-with-comment   File: ApplicationHttpRequest.java   View Source Code Vote up 6 votes
/**
 * Set the request that we are wrapping.
 *
 * @param request The new wrapped request
 */
void setRequest(HttpServletRequest request) {

    super.setRequest(request);

    // Initialize the attributes for this request
    dispatcherType = (DispatcherType)request.getAttribute(Globals.DISPATCHER_TYPE_ATTR);
    requestDispatcherPath = 
        request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR);

    // Initialize the path elements for this request
    contextPath = request.getContextPath();
    pathInfo = request.getPathInfo();
    queryString = request.getQueryString();
    requestURI = request.getRequestURI();
    servletPath = request.getServletPath();

}
 
Example 2
Project: hadoop   File: TestJobEndNotifier.java   View Source Code Vote up 6 votes
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  InputStreamReader in = new InputStreamReader(request.getInputStream());
  PrintStream out = new PrintStream(response.getOutputStream());

  calledTimes++;
  try {
    requestUri = new URI(null, null,
        request.getRequestURI(), request.getQueryString(), null);
    foundJobState = request.getParameter("status");
  } catch (URISyntaxException e) {
  }

  in.close();
  out.close();
}
 
Example 3
Project: lambo   File: UpmsAuthenticationFilter.java   View Source Code Vote up 6 votes
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    StringBuffer sso_server_url = new StringBuffer(PropertiesFileUtil.getInstance("lambo-upms-client").get("lambo.upms.sso.server.url"));
    // server需要登录
    String upmsType = PropertiesFileUtil.getInstance("lambo-upms-client").get("lambo.upms.type");
    if ("server".equals(upmsType)) {
        WebUtils.toHttp(response).sendRedirect(sso_server_url.append("/sso/login").toString());
        return false;
    }
    sso_server_url.append("/sso/index").append("?").append("appid").append("=").append(PropertiesFileUtil.getInstance("lambo-upms-client").get("lambo.upms.appID"));
    // 回跳地址
    HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
    StringBuffer backurl = httpServletRequest.getRequestURL();
    String queryString = httpServletRequest.getQueryString();
    if (StringUtils.isNotBlank(queryString)) {
        backurl.append("?").append(queryString);
    }
    sso_server_url.append("&").append("backurl").append("=").append(URLEncoder.encode(backurl.toString(), "utf-8"));
    WebUtils.toHttp(response).sendRedirect(sso_server_url.toString());
    return false;
}
 
Example 4
Project: TARA-Server   File: FlowExecutionExceptionResolver.java   View Source Code Vote up 6 votes
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
    if (exception instanceof FlowExecutionRepositoryException && !(exception instanceof BadlyFormattedFlowExecutionKeyException)) {
        String urlToRedirectTo = request.getRequestURI() + (request.getQueryString() != null ? '?' + request.getQueryString() : "");
        log.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception);
        Map<String, Object> model = new HashMap();
        model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage()));
        return new ModelAndView(new RedirectView(urlToRedirectTo), model);
    } else if (exception instanceof AbstractFlowExecutionException) {
        if (log.isDebugEnabled()) {
            log.error("Flow execution error", exception);
        } else {
            log.error("Flow execution error: {}", exception.getMessage());
        }
        return ((AbstractFlowExecutionException) exception).getModelAndView();
    } else {
        log.debug("Ignoring the received exception due to a type mismatch", exception);
        return null;
    }
}
 
Example 5
Project: hadoop   File: NotificationTestCase.java   View Source Code Vote up 6 votes
protected void doGet(HttpServletRequest req, HttpServletResponse res)
  throws ServletException, IOException {
  String queryString = req.getQueryString();
  switch (counter) {
    case 0:
      verifyQuery(queryString, "SUCCEEDED");
      break;
    case 2:
      verifyQuery(queryString, "KILLED");
      break;
    case 4:
      verifyQuery(queryString, "FAILED");
      break;
  }
  if (counter % 2 == 0) {
    res.sendError(HttpServletResponse.SC_BAD_REQUEST, "forcing error");
  }
  else {
    res.setStatus(HttpServletResponse.SC_OK);
  }
  counter++;
}
 
Example 6
Project: minijax   File: UrlUtils.java   View Source Code Vote up 6 votes
/**
 * Returns the full request URL for a servlet request.
 *
 * 1) Fixes HTTPS protocol if forwarded by load balancer.
 * 2) Handles query strings.
 *
 * See:
 * http://stackoverflow.com/a/2222268/2051724
 * http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html
 *
 * @param request The original HTTP servlet request.
 * @return The full request URL.
 */
public static URI getFullRequestUrl(final HttpServletRequest request) {
    if (request == null) {
        return null;
    }

    String url = request.getRequestURL().toString();

    // Fix HTTPS->HTTP rewriting from HTTP proxy.
    // For example, "https://www.ajibot.com" will appear as "http://www.ajibot.com"
    final String forwarded = request.getHeader("X-Forwarded-Proto");
    if (forwarded != null && forwarded.equals("https")) {
        url = url.replaceFirst("http://", "https://");
    }

    final String queryString = request.getQueryString();
    if (queryString != null) {
        url += "?" + queryString;
    }

    return URI.create(url);
}
 
Example 7
Project: springboot-shiro-cas-mybatis   File: FlowExecutionExceptionResolver.java   View Source Code Vote up 5 votes
@Override
public ModelAndView resolveException(final HttpServletRequest request,
    final HttpServletResponse response, final Object handler,
    final Exception exception) {

    /*
     * Since FlowExecutionRepositoryException is a common ancestor to these exceptions and other
     * error cases we would likely want to hide from the user, it seems reasonable to check for
     * FlowExecutionRepositoryException.
     *
     * BadlyFormattedFlowExecutionKeyException is specifically ignored by this handler
     * because redirecting to the requested URI with this exception may cause an infinite
     * redirect loop (i.e. when invalid "execution" parameter exists as part of the query string
     */
    if (!(exception instanceof FlowExecutionRepositoryException)
          || exception instanceof BadlyFormattedFlowExecutionKeyException) {
        logger.debug("Ignoring the received exception due to a type mismatch", exception);
        return null;
    }

    final String urlToRedirectTo = request.getRequestURI()
            + (request.getQueryString() != null ? '?'
            + request.getQueryString() : "");

    logger.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception);
    final Map<String, Object> model = new HashMap<>();
    model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage()));

    return new ModelAndView(new RedirectView(urlToRedirectTo), model);
}
 
Example 8
Project: lams   File: OAuthServlet.java   View Source Code Vote up 5 votes
/** Reconstruct the requested URL, complete with query string (if any). */
public static String getRequestURL(HttpServletRequest request) {
    StringBuffer url = request.getRequestURL();
    String queryString = request.getQueryString();
    if (queryString != null) {
        url.append("?").append(queryString);
    }
    return url.toString();
}
 
Example 9
Project: springboot-shiro-cas-mybatis   File: FlowExecutionExceptionResolver.java   View Source Code Vote up 5 votes
@Override
public ModelAndView resolveException(final HttpServletRequest request,
    final HttpServletResponse response, final Object handler,
    final Exception exception) {

    /*
     * Since FlowExecutionRepositoryException is a common ancestor to these exceptions and other
     * error cases we would likely want to hide from the user, it seems reasonable to check for
     * FlowExecutionRepositoryException.
     *
     * BadlyFormattedFlowExecutionKeyException is specifically ignored by this handler
     * because redirecting to the requested URI with this exception may cause an infinite
     * redirect loop (i.e. when invalid "execution" parameter exists as part of the query string
     */
    if (!(exception instanceof FlowExecutionRepositoryException)
          || exception instanceof BadlyFormattedFlowExecutionKeyException) {
        logger.debug("Ignoring the received exception due to a type mismatch", exception);
        return null;
    }

    final String urlToRedirectTo = request.getRequestURI()
            + (request.getQueryString() != null ? '?'
            + request.getQueryString() : "");

    logger.debug("Error getting flow information for URL [{}]", urlToRedirectTo, exception);
    final Map<String, Object> model = new HashMap<>();
    model.put(this.modelKey, StringEscapeUtils.escapeHtml4(exception.getMessage()));

    return new ModelAndView(new RedirectView(urlToRedirectTo), model);
}
 
Example 10
Project: lams   File: UrlPathHelper.java   View Source Code Vote up 5 votes
/**
 * Return the query string part of the given request's URL. If this is a forwarded request,
 * correctly resolves to the query string of the original request.
 * @param request current HTTP request
 * @return the query string
 */
public String getOriginatingQueryString(HttpServletRequest request) {
	if ((request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) != null) ||
		(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null)) {
		return (String) request.getAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE);
	}
	else {
		return request.getQueryString();
	}
}
 
Example 11
Project: ServiceServer   File: LogUtil.java   View Source Code Vote up 5 votes
/**
 * Print logs of http request.
 */
public static void logReq(Logger logger, HttpServletRequest req) {
    String queryStr = req.getQueryString();
    if (queryStr == null || queryStr.length() == 0) {
        logger.info(req.getMethod() + " " + req.getRequestURI());
    } else {
        try {
            queryStr = URLDecoder.decode(queryStr, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.warn(e.getMessage());
        }
        logger.info(req.getMethod() + " " + req.getRequestURI() + "?" + queryStr);
    }
}
 
Example 12
Project: OpenDiabetes   File: Servlet.java   View Source Code Vote up 5 votes
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
                  throws IOException, ServletException {

    String query = request.getQueryString();

    if ((query == null) || (query.length() == 0)) {
        response.setContentType("text/html");

        // [email protected] 20020130 - patch 1.7.0 by fredt
        // to avoid caching on the browser
        response.setHeader("Pragma", "no-cache");

        PrintWriter out = response.getWriter();

        out.println(
            "<html><head><title>HSQL Database Engine Servlet</title>");
        out.println("</head><body><h1>HSQL Database Engine Servlet</h1>");
        out.println("The servlet is running.<p>");

        if (initError == null) {
            out.println("Connected to the database.<p>");
            out.println("Database name: " + dbType + dbPath + "<p>");
        } else {
            out.println("<h2>The database is not available.</h2>");
            out.println("The error message is:<p>");
            out.println(initError);
        }

        out.println("</body></html>");
    }
}
 
Example 13
Project: redirector   File: AccessLoggingFilter.java   View Source Code Vote up 5 votes
private void log(HttpServletRequest request, HttpServletResponse response) {
    long duration = 0;
    try {
        final Long requestStartTime = (Long) request.getAttribute(START_TIME);
        if (requestStartTime!=null && requestStartTime > 0) {
            duration = System.currentTimeMillis() - requestStartTime;
        }
    } catch (Exception x) {
        log.warn("Could not get request start time {}", x);
    }

    final StringBuilder httpHeaders = new StringBuilder('[');
    for (final Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements(); ) {
        final String headerName = headerNames.nextElement();
        httpHeaders.append('[').append(headerName).append(": ").append(request.getHeader(headerName)).append("], ");
    }
    httpHeaders.append(']');

    final StringBuffer requestStringBuffer = request.getRequestURL();

    if (request.getQueryString() != null && !request.getQueryString().isEmpty()) {
        requestStringBuffer.append("?").append(request.getQueryString());
    }

    Metrics.reportGatewayRedirectDurationStats(duration);

    log.info("Request: {} {} agent={} status={} duration={} HTTP Headers={}",
            request.getMethod(), requestStringBuffer,
            request.getHeader("User-Agent"),
            response.getStatus(),
            duration != 0 ? duration : "unknown",
            httpHeaders.toString());
}
 
Example 14
Project: TARA-Server   File: CasWebAppConfiguration.java   View Source Code Vote up 5 votes
@Bean
protected Controller rootController() {
    return new ParameterizableViewController() {
        protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
            String queryString = request.getQueryString();
            String url = request.getContextPath() + "/login" + (queryString != null ? '?' + queryString : "");
            return new ModelAndView(new RedirectView(response.encodeURL(url)));
        }
    };
}
 
Example 15
Project: private-WeChat   File: RequestUtils.java   View Source Code Vote up 5 votes
/***
 * 获取请求的完整url路径 比如http://car.chexiang.com/detail.htm?spuId=2222
 * @param request
 * @param needQueryString 是否包含get请求的参数
 * @return
 */
public static String getFullRequestUrl(HttpServletRequest request, boolean needQueryString){
	StringBuilder urlBuilder = new StringBuilder();
	urlBuilder.append(request.getRequestURL().toString());
	if(needQueryString){
		if(request.getQueryString() != null && request.getQueryString().length() > 0){
			urlBuilder.append("?").append(request.getQueryString());
		}
	}
	return urlBuilder.toString();
}
 
Example 16
Project: admin-template   File: AdminFilter.java   View Source Code Vote up 4 votes
private void redirectToLogon(HttpServletRequest request, HttpServletResponse response) {
    try {
        String referer = request.getHeader("Referer");
        String recoveryUrlParams = "";
        //get request parameters
        if (has(referer) && referer.contains("?")) {
            recoveryUrlParams = referer.substring(referer.lastIndexOf("?") + 1);
        } else {
            recoveryUrlParams = request.getQueryString();
        }
        //saves page where user were
        String requestedPage = request.getRequestURI();
        StringBuilder recoveryUrl = null;
        if (!loginPage.equals(requestedPage) && requestedPage.contains(".")) {
            if (requestedPage.startsWith(request.getContextPath())) {
                requestedPage = requestedPage.replaceFirst(request.getContextPath(), "");
            }
            recoveryUrl = new StringBuilder(requestedPage);
            if (has(recoveryUrlParams)) {
                recoveryUrl.append("?").append(recoveryUrlParams);
            }
        }
        /*
         if saved page is not null and is not index page then send user to logon page and save
        / previous page in url param named 'page'
        */
        String redirectUrl = request.getContextPath() + "/" + loginPage + (has(recoveryUrl) &&
                isValidRecoveryUrl(recoveryUrl) ? "?page=" + URLEncoder.encode(recoveryUrl.toString(), "UTF-8") : "");
        if ("partial/ajax".equals(request.getHeader("Faces-Request"))) {
            //redirect on ajax request: //http://stackoverflow.com/questions/13366936/jsf-filter-not-redirecting-after-initial-redirect
            response.setContentType("text/xml");
            response.getWriter()
                    .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
                    .printf("<partial-response><redirect url=\"%s\"></redirect></partial-response>", redirectUrl);
        } else {//normal redirect
            response.sendRedirect(redirectUrl);
        }

    } catch (Exception e) {
        log.log(Level.SEVERE,"Could not redirect to " + loginPage, e);
    }

}
 
Example 17
Project: cas-5.1.0   File: CasDefaultFlowUrlHandler.java   View Source Code Vote up 4 votes
@Override
public String createFlowDefinitionUrl(final String flowId, final AttributeMap input, final HttpServletRequest request) {
    return request.getRequestURI()
        + (request.getQueryString() != null ? '?'
        + request.getQueryString() : StringUtils.EMPTY);
}
 
Example 18
Project: jambo2   File: LastRequest.java   View Source Code Vote up 4 votes
public void recordRequest(HttpServletRequest request, long reqTime){
    url = request.getRequestURI() + "?" + request.getQueryString();
    time = reqTime;
}
 
Example 19
Project: Webstore   File: PerformanceMonitorInterceptor.java   View Source Code Vote up 4 votes
private String getURLPath(HttpServletRequest request) {
    String currentPath = request.getRequestURI();
    String queryString = request.getQueryString();
    queryString = queryString == null ? "" : "?" + queryString;
    return currentPath+queryString;
}
 
Example 20
Project: myfaces-trinidad   File: TrinidadFilterImpl.java   View Source Code Vote up 4 votes
private void _handleDialogReturn(ExternalContext ec)
  throws IOException
{
  Map<String, Object> reqMap = ec.getRequestMap();
  
  if(Boolean.TRUE.equals(reqMap.get(DialogServiceImpl.DIALOG_RETURN)))
  {
    /**
     * We use pageflow scope so that if something fails on the redirect, we
     * have a chance of getting cleaned up early.  This will not always happen
     * so the object may stick around for a while.
     */
    Map<String, Object> sessionMap = ec.getSessionMap();
    String uid = UUID.randomUUID().toString();
    LaunchData data = new LaunchData((UIViewRoot)reqMap.get(RequestContextImpl.LAUNCH_VIEW), (Map<String, String[]>) reqMap.get(RequestContextImpl.LAUNCH_PARAMETERS));
    sessionMap.put(_getKey(uid), data);
    
    //Construct URL
    //TODO: sobryan I believe some of this can be added to the RequestContextUtils to allow
    //      this url to be constructed for both portlet and servlet environments.  We'll want to research.
    HttpServletRequest req = (HttpServletRequest) ec.getRequest();
    StringBuffer url = req.getRequestURL().append("?");
    String queryStr = req.getQueryString();
    if((queryStr != null) && (queryStr.trim().length() >0))
    {
      url.append(queryStr)
         .append("&");
    }
    
    url.append(_LAUNCH_KEY)
       .append("=")
       .append(uid);

    //Extensions to Trinidad may have alternatve means of handling PPR.  This
    //flag allows those extensions to for the <redirect> AJAX message to be returned.
    if (RequestContext.getCurrentInstance().isPartialRequest(_PSEUDO_FACES_CONTEXT.get()) || 
        Boolean.TRUE.equals(RequestStateMap.getInstance(ec).get(_FORCE_PPR_DIALOG_RETURN)))
    {
      //Special handling for XmlHttpRequest.  Would be cool to handle this much cleaner.
      HttpServletResponse resp = (HttpServletResponse) ec.getResponse();
      XmlHttpConfigurator.sendXmlRedirect(resp.getWriter(), url.toString());
    }
    else
    {
      ec.redirect(url.toString());
    }
  }
}