當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpServletResponse.getStatus方法代碼示例

本文整理匯總了Java中javax.servlet.http.HttpServletResponse.getStatus方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpServletResponse.getStatus方法的具體用法?Java HttpServletResponse.getStatus怎麽用?Java HttpServletResponse.getStatus使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.servlet.http.HttpServletResponse的用法示例。


在下文中一共展示了HttpServletResponse.getStatus方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: doGet

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // Only set the status on the first call (the dispatch will trigger
    // another call to this Servlet)
    if (resp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        AsyncContext ac = req.startAsync();
        ac.dispatch();
    }
}
 
開發者ID:liaokailin,項目名稱:tomcat7,代碼行數:12,代碼來源:TestErrorReportValve.java

示例2: doFilter

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
    throws IOException, ServletException {

  final HttpServletRequest req = (HttpServletRequest) request;
  final HttpServletResponse resp = (HttpServletResponse) response;

  SpanBuilder sb = tracer.importSpan(name -> req.getHeader(name));
  try {
    sb.resource(normalize(req.getServerName()) + ':' + req.getServerPort())
      .operation(req.getMethod() + ' ' + URLDecoder.decode(req.getRequestURI(), "UTF-8"))
      .type(TraceOperation.WEB);
    filterChain.doFilter(request, response);
  } finally {
    int status = resp.getStatus();
    sb.error(status<200 || status>=400);
    tracer.closeSpan(sb);
  }
}
 
開發者ID:chonton,項目名稱:apm-client,代碼行數:20,代碼來源:TraceServletFilter.java

示例3: handleError

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@RequestMapping(value=ERROR_PATH)
public String handleError(HttpServletRequest request, HttpServletResponse response, Model model){
    String errorInfo[];
    switch (response.getStatus()){
        case 404:
            errorInfo = ERROR_404;
            break;
        case 500:
            errorInfo = ERROR_500;
            break;
        default:
            errorInfo = ERROR_DEFAULT;
    }
    model.addAttribute("status",response.getStatus());
    model.addAttribute("errorInfo",errorInfo);
    return "index/error";
}
 
開發者ID:BetaSummer,項目名稱:sztw,代碼行數:18,代碼來源:Error.java

示例4: getStatus

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
private int getStatus(HttpServletResponse response) {
    try {
        return response.getStatus();
    } catch (Exception ex) {
        return UNDEFINED_HTTP_STATUS;
    }
}
 
開發者ID:nlighten,項目名稱:wildfly_exporter,代碼行數:8,代碼來源:ServletMetricsFilter.java

示例5: postHandle

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response,
                             final Object o, final ModelAndView modelAndView) throws Exception {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        return;
    }

    final boolean recordEvent = response.getStatus() != HttpStatus.SC_CREATED
                             && response.getStatus() != HttpStatus.SC_OK;

    if (recordEvent) {
        LOGGER.debug("Recording submission failure for [{}]", request.getRequestURI());
        recordSubmissionFailure(request);
    }
}
 
開發者ID:mrluo735,項目名稱:cas-5.1.0,代碼行數:16,代碼來源:AbstractThrottledSubmissionHandlerInterceptorAdapter.java

示例6: handleError

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@RequestMapping("/error")
public String handleError(HttpServletRequest request, HttpServletResponse response, Model model) {
    int code = response.getStatus();
    String message = HttpStatus.valueOf(code).getReasonPhrase();
    model.addAttribute("code", code);
    model.addAttribute("message", message);

    LOG.info(String.format("HTTP error: %s, %s on request %s '%s' caused by %s",
            code, message,
            request.getMethod(), request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI),
            LogUtil.getUserInfo(request)));

    return "error";
}
 
開發者ID:kalsowerus,項目名稱:Guestbook9001,代碼行數:15,代碼來源:ExceptionController.java

示例7: postFilter

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
public void postFilter(ServletRequest request, ServletResponse response) {
    Segment segment = recorder.getCurrentSegment();
    if (null != segment) {
        HttpServletResponse httpServletResponse = castServletResponse(response);

        if (null != httpServletResponse) {
            Map<String, Object> responseAttributes = new HashMap<String, Object>();

            int responseCode = httpServletResponse.getStatus();
            switch (responseCode/100) {
                case 4:
                    segment.setError(true);
                    if (responseCode == 429) {
                        segment.setThrottle(true);
                    }
                    break;
                case 5:
                    segment.setFault(true);
                    break;
                default:
                    break;
            }
            responseAttributes.put("status", responseCode);


            Optional<Integer> contentLength = getContentLength(httpServletResponse);
            if (contentLength.isPresent()) {
                responseAttributes.put("content_length", contentLength.get());
            }

            segment.putHttp("response", responseAttributes);
        }

        recorder.endSegment();
    }
}
 
開發者ID:aws,項目名稱:aws-xray-sdk-java,代碼行數:37,代碼來源:AWSXRayServletFilter.java

示例8: onError

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
public void onError(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                    Throwable exception, Span span) {
    Tags.ERROR.set(span, Boolean.TRUE);
    span.log(logsForException(exception));

    if (httpServletResponse.getStatus() == HttpServletResponse.SC_OK) {
        // exception is thrown in filter chain, but status code is incorrect
        Tags.HTTP_STATUS.set(span, 500);
    }
}
 
開發者ID:opentracing-contrib,項目名稱:java-web-servlet-filter,代碼行數:12,代碼來源:ServletFilterSpanDecorator.java

示例9: doFilterInternal

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
protected void doFilterInternal (final HttpServletRequest request, final HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
  final long startTime = System.nanoTime ();
  int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
  try {
    filterChain.doFilter(request, response);
    status = response.getStatus();
  } finally {
    try {
      apmSpringService.traceTransaction (request, response, Integer.toString (status), System.nanoTime () - startTime);
    } catch (final InterruptedException e) {
      logger.warn (String.format ("Failed to trace transaction for request %s", request.getRequestURI ()), e);
    }
  }
}
 
開發者ID:davidecavestro,項目名稱:elastic-apm-java-agent-poc,代碼行數:16,代碼來源:RequestTraceFilter.java

示例10: afterCompletion

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    RequestUserDto httpConn = JwtService.getConnUser(httpServletRequest);
    String userId = httpConn.getUserId();
    String domainId = httpConn.getDomainID();
    String clientIp = httpServletRequest.getRemoteAddr();
    Integer statuCd = httpServletResponse.getStatus();
    String method = httpServletRequest.getMethod();
    String uri = httpServletRequest.getRequestURI();
    Map<String, String[]> map = httpServletRequest.getParameterMap();
    Map<String, String> dt = parseJSON(map);
    String dtvalue = new GsonBuilder().create().toJson(dt);
    jdbcTemplate.update(sqlText.getSql("sys207"), userId, clientIp, statuCd, method, uri, dtvalue, domainId);
}
 
開發者ID:hzwy23,項目名稱:batch-scheduler,代碼行數:15,代碼來源:LoggerHandlerInterceptor.java

示例11: postHandle

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
       //獲取響應狀態碼
       int status = response.getStatus();
       
       //當前時間
       long currentTime = System.currentTimeMillis();
       
       //請求開始時間
       long time = Long.valueOf(request.getAttribute(LOGGER_SEND_TIME).toString());
       
       //獲取本次請求日誌實體
       LoggerEntity loggerEntity = (LoggerEntity) request.getAttribute(LOGGER_ENTITY);
       
       //設置請求時間差
       loggerEntity.setTimeConsuming(String.valueOf(currentTime - time));
       
       //設置返回時間
       loggerEntity.setReturnTime(currentTime + "");
       
       //設置返回錯誤碼
       loggerEntity.setHttpStatusCode(status + "");
       
       //設置返回值,返回值需要配置AOP攔截,待完善
       String returnData = null;
       
       LoggerRepository loggerDAO = getDAO(LoggerRepository.class, request);
       loggerDAO.save(loggerEntity);
}
 
開發者ID:SnailFastGo,項目名稱:ontology_setting,代碼行數:31,代碼來源:LoggerInterceptor.java

示例12: statusCode

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Nullable
@Override
public Integer statusCode(@Nonnull HttpServletResponse response) {
  return response.getStatus() == 0 ? 500 : response.getStatus();
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:6,代碼來源:SpringTracingConfiguration.java

示例13: doExecute

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);

    // get client
    final String clientName = request.getParameter(this.clients.getClientNameParameter());
    LOGGER.debug("clientName: [{}]", clientName);

    if (hasDelegationRequestFailed(request, response.getStatus()).isPresent()) {
        return stopWebflow();
    }
    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
        LOGGER.debug("Client: [{}]", client);

        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            LOGGER.debug("Retrieved credentials: [{}]", credentials);
        } catch (final Exception e) {
            LOGGER.debug("The request requires http action", e);
            return stopWebflow();
        }

        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(CasProtocolConstants.PARAMETER_SERVICE);
        context.getFlowScope().put(CasProtocolConstants.PARAMETER_SERVICE, service);
        LOGGER.debug("Retrieve service: [{}]", service);
        if (service != null) {
            request.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
        }

        restoreRequestAttribute(request, session, this.themeParamName);
        restoreRequestAttribute(request, session, this.localParamName);
        restoreRequestAttribute(request, session, CasProtocolConstants.PARAMETER_METHOD);

        // credentials not null -> try to authenticate
        if (credentials != null) {
            final AuthenticationResult authenticationResult =
                    this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, new ClientCredential(credentials));

            final TicketGrantingTicket tgt = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
            WebUtils.putTicketGrantingTicketInScopes(context, tgt);
            return success();
        }
    }

    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    if (response.getStatus() == HttpStatus.UNAUTHORIZED.value()) {
        return stopWebflow();
    }

    if (this.autoRedirect) {
        final Set<ProviderLoginPageConfiguration> urls = context.getFlowScope().get(PAC4J_URLS, Set.class);
        if (urls != null && urls.size() == 1) {
            final ProviderLoginPageConfiguration cfg = urls.stream().findFirst().get();
            LOGGER.debug("Auto-redirecting to client url [{}]", cfg.getRedirectUrl());
            response.sendRedirect(cfg.getRedirectUrl());
            final ExternalContext externalContext = context.getExternalContext();
            externalContext.recordResponseComplete();
            return stopWebflow();
        }
    }
    return error();
}
 
開發者ID:mrluo735,項目名稱:cas-5.1.0,代碼行數:75,代碼來源:DelegatedClientAuthenticationAction.java

示例14: doFilterInternal

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
/**
 * Forwards the request to the next filter in the chain and delegates down to the subclasses to perform the actual
 * request logging both before and after the request is processed.
 *
 * @see #beforeRequest
 * @see #afterRequest
 */
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
	if (resourceUrlStart==null) {
		resourceUrlStart = request.getContextPath() + YadaWebConfig.getResourceFolder() + "-"; // /site/res-
	}
	boolean isFirstRequest = !isAsyncDispatch(request);
	long startTime = -1;
	String sessionId = "";
	String username = "";
	// Questo codice per il calcolo dell'IP è stato messo in YadaWebUtil ma accedere quello da qui non viene facile, per cui duplico qui
	String remoteAddr = request.getRemoteAddr();
	String forwardedFor = request.getHeader("X-Forwarded-For");
	String remoteIp = "?";
	if (!StringUtils.isBlank(remoteAddr)) {
		remoteIp = remoteAddr;
	}
	if (!StringUtils.isBlank(forwardedFor)) {
		remoteIp = "[for " + forwardedFor + "]";
	}
	//
	String requestUri = request.getRequestURI();
	HttpSession session = request.getSession(false);
	SecurityContext securityContext = null;
	if (session!=null) {
		sessionId = StringUtils.trimToEmpty(session.getId());
		securityContext = ((SecurityContext)session.getAttribute("SPRING_SECURITY_CONTEXT"));
	}
	if (sessionId.length()==0) {
		sessionId = "req-"+Integer.toString(request.hashCode());
	}
	if (securityContext!=null) {
		try {
			username = securityContext.getAuthentication().getName();
		} catch (Exception e) {
			log.debug("No username in securityContext");
		}
	}
	MDC.put(MDC_SESSION, sessionId); // Session viene messo sull'MDC. Usarlo con %X{session} nel pattern
	MDC.put(MDC_USERNAME, username); // username viene messo sull'MDC. Usarlo con %X{username} nel pattern		
	MDC.put(MDC_REMOTEIP, remoteIp); // remoteIp viene messo sull'MDC. Usarlo con %X{remoteIp} nel pattern		

	if (isFirstRequest) {
		beforeRequest(request);
		startTime = System.currentTimeMillis();
	}
	try {
		filterChain.doFilter(request, response);
		int status = response.getStatus();
		if (!skipDuration(requestUri) && !isAsyncStarted(request)) {
			if (startTime>-1) {
				long timetaken = System.currentTimeMillis()-startTime;
				log.info("{}: {} ms (HTTP {})", requestUri, timetaken, status);
			}
		} else if (status>399) {
			log.error("{} HTTP {}", requestUri, status);
		}
	} finally {
		MDC.remove(MDC_USERNAME);
		MDC.remove(MDC_SESSION);
		MDC.remove(MDC_REMOTEIP);
	}
}
 
開發者ID:xtianus,項目名稱:yadaframework,代碼行數:70,代碼來源:AuditFilter.java

示例15: doFilter

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {

    StopWatch stopWatch = StopWatch.createStarted();

    String domain = request.getServerName();
    String remoteAddr = request.getRemoteAddr();
    Long contentLength = request.getContentLengthLong();

    String tenant = tenantMappingService != null ? tenantMappingService.getTenants().get(domain) : null;

    String method = null;
    String userLogin = null;
    String requestUri = null;

    try {

        if (request instanceof HttpServletRequest) {
            HttpServletRequest req = HttpServletRequest.class.cast(request);
            method = req.getMethod();
            userLogin = req.getRemoteUser();
            requestUri = req.getRequestURI();
        }

        MDCUtil.putRid(MDCUtil.generateRid() + ":" + userLogin + ":" + tenant);

        log.info("START {}/{} --> {} {}, contentLength = {} ", remoteAddr, domain, method, requestUri,
                 contentLength);

        chain.doFilter(request, response);

        Integer status = null;

        if (response instanceof HttpServletResponse) {
            HttpServletResponse res = HttpServletResponse.class.cast(response);
            status = res.getStatus();
        }

        log.info("STOP  {}/{} --> {} {}, status = {}, time = {} ms", remoteAddr, domain, method, requestUri,
                 status, stopWatch.getTime());

    } catch (Exception e) {
        log.error("STOP  {}/{} --> {} {}, error = {}, time = {} ms", remoteAddr, domain, method, requestUri,
                  LogObjectPrinter.printException(e), stopWatch.getTime());
        throw e;
    } finally {
        MDCUtil.clear();
    }

}
 
開發者ID:xm-online,項目名稱:xm-gate,代碼行數:52,代碼來源:LoggingFilter.java


注:本文中的javax.servlet.http.HttpServletResponse.getStatus方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。