Java Code Examples for javax.servlet.http.HttpServletResponse#getStatus()

The following examples show how to use javax.servlet.http.HttpServletResponse#getStatus() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticationFilter.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (securityManager.authenticate(request, response, PRE_REQUEST_CONTAINER)) {
        chain.doFilter(
            securityManager.getAuthenticatedRequest(request, response), 
            securityManager.getAuthenticatedResponse(request, response));
        
        securityManager.postRequestProcess(request, response);
        
        return;
    }
    
    if ((response.getStatus() < 400 || response.getStatus() > 599) && !response.isCommitted()) {
        // Authentication Mechanism did not set an error status. Set the default 403 here.
        response.setStatus(SC_FORBIDDEN);
        response.getWriter().println("Forbidden");
    }
}
 
Example 2
Source File: CustomErrorController.java    From spring-boot-study with MIT License 6 votes vote down vote up
@RequestMapping(
        value = {ERROR_PATH},
        produces = {"text/html"}
)

/**
 * 用户 Controller 带返回的
 * */
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    int code = response.getStatus();
    if (404 == code) {
        return new ModelAndView("error/404");
    } else if (403 == code) {
        return new ModelAndView("error/403");
    } else {
        return new ModelAndView("error/500");
    }

}
 
Example 3
Source File: CustomErrorController.java    From spring-boot-study with MIT License 6 votes vote down vote up
@RequestMapping(value = ERROR_PATH)
public Map handleError(HttpServletRequest request, HttpServletResponse response) {
    Map<String,Object> map=new HashMap<>();
    int code = response.getStatus();
    if (404 == code) {
        map.put("status",404);
        map.put("msg","未找到资源文件");
    } else if (403 == code) {
        map.put("status",403);
        map.put("msg","没有访问权限");
    } else if (401 == code) {
        map.put("status",401);
        map.put("msg","登录过期");
    } else {
        map.put("status",500);
        map.put("msg","服务器错误");
    }
    return  map;
}
 
Example 4
Source File: ServletWebRequest.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean isStatusOK(HttpServletResponse response) {
	if (response == null || !servlet3Present) {
		// Can't check response.getStatus() - let's assume we're good
		return true;
	}
	return response.getStatus() == 200;
}
 
Example 5
Source File: TestErrorReportValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 6
Source File: TomcatServletMetricsFilter.java    From tomcat_exporter with Apache License 2.0 5 votes vote down vote up
private int getStatus(HttpServletResponse response) {
    try {
        return response.getStatus();
    } catch (Exception ex) {
        return UNDEFINED_HTTP_STATUS;
    }
}
 
Example 7
Source File: LoggerHandlerInterceptor.java    From hauth-java with MIT License 5 votes vote down vote up
@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(SqlDefine.sys_rdbms_207, userId, clientIp, statuCd, method, uri, dtvalue, domainId);
}
 
Example 8
Source File: JEEServiceRunGlobalFilterHandler.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * 解决低版本Servlet兼容问题,My God!!!
 * 
 * @param response
 * @return
 */
private int getRespRetStatus(HttpServletResponse response) {

    try {
        return response.getStatus();
    }
    catch (Error e) {

        Object resp = response;
        // 重调用链开启时,获取到原生response         
        if (HttpServletResponseWrapper.class.isAssignableFrom(response.getClass())) {          
                resp = TransformWrapperUtil.moveWrapper("", response);
        }

        if (resp == null) {
            return 0;
        }
        Object result = null;
        // for tomcat 6.0.4x
        if ("org.apache.catalina.connector.ResponseFacade".equals(resp.getClass().getName())) {
            resp = ReflectionHelper.getField(resp.getClass(), resp, "response");
            if (resp != null) {
                result = ReflectionHelper.invoke(resp.getClass().getName(), resp, "getStatus", null, null,
                        response.getClass().getClassLoader());
            }
        }

        if (result == null) {
            return 0;
        }

        return (Integer) result;
    }
}
 
Example 9
Source File: OcHttpServletExtractor.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public int getStatusCode(@Nullable HttpServletResponse response) {
  if (response != null) {
    return response.getStatus();
  }
  return 0;
}
 
Example 10
Source File: AuthenInterceptor.java    From DouBiNovel with Apache License 2.0 5 votes vote down vote up
@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        if (modelAndView == null) {
            super.postHandle(request, response, handler, modelAndView);
            return;
        }
        if (response.getStatus() == 200) {
            modelAndView.addObject("systemInfo", systemSettingService.getSetting());
            User user = (User) SecurityUtils.getSubject().getPrincipal();

            HttpSession session = request.getSession();
            String url = request.getRequestURI();
            if (url != null && url.lastIndexOf("admin") >= 0) {
//                user = (User) session.getAttribute(Const.session.LOGIN_ADMIN);
            } else {
//                user = (User) session.getAttribute(Const.session.LOGIN_USER);
                if (user == null && (url.lastIndexOf("bookshelf")>=0 || url.lastIndexOf("user")>=0)){
                    response.sendRedirect("/index");
                }
            }
            if (user != null) {
                modelAndView.addObject("user", user);
            }
        }
        super.postHandle(request, response, handler, modelAndView);
    }
 
Example 11
Source File: AuthenticationHandler.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void handleError(HttpServletRequest request, HttpServletResponse response, HandlerContext context) {
    Object error = request.getAttribute(HandlerContext.ERROR_ATTRIBUTE);

    if (response.getStatus() == 403 || response.getStatus() == 401) {
        // already handled
        return;
    }

    if (error instanceof AuthenticationException) {
        // force client redirect
        String redirectUri = loginUri + "?" + REDIRECT_PARAM_NAME + "=" + request.getRequestURI();
        response.setHeader("Location", redirectUri);
        try {
            PrintWriter writer = response.getWriter();
            writer.println("<html><head>");
            writer.println("<meta http-equiv=\"refresh\" content=\"0; url=" + redirectUri + "\" />");
            writer.println("</head><body>Redirecting to login page</body></html>");
            writer.flush();
        } catch (IOException e) {
            logger.warn("Couldn't generate or send client response", e);
        }
    } else {
        // let other handler handle error
        context.execute(request, response);
    }
}
 
Example 12
Source File: ServletRequestTagAdapter.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Override
public @Nullable Integer getResponseHttpStatus(@Nullable HttpServletResponse response) {
    if (response == null) {
        return null;
    }

    return response.getStatus();
}
 
Example 13
Source File: FrameworkServlet.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void publishRequestHandledEvent(
		HttpServletRequest request, HttpServletResponse response, long startTime, Throwable failureCause) {

	if (this.publishEvents) {
		// Whether or not we succeeded, publish an event.
		long processingTime = System.currentTimeMillis() - startTime;
		int statusCode = (responseGetStatusAvailable ? response.getStatus() : -1);
		this.webApplicationContext.publishEvent(
				new ServletRequestHandledEvent(this,
						request.getRequestURI(), request.getRemoteAddr(),
						request.getMethod(), getServletConfig().getServletName(),
						WebUtils.getSessionId(request), getUsernameForRequest(request),
						processingTime, failureCause, statusCode));
	}
}
 
Example 14
Source File: ServletWebRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean checkNotModified(@Nullable String etag, long lastModifiedTimestamp) {
	HttpServletResponse response = getResponse();
	if (this.notModified || (response != null && HttpStatus.OK.value() != response.getStatus())) {
		return this.notModified;
	}

	// Evaluate conditions in order of precedence.
	// See https://tools.ietf.org/html/rfc7232#section-6

	if (validateIfUnmodifiedSince(lastModifiedTimestamp)) {
		if (this.notModified && response != null) {
			response.setStatus(HttpStatus.PRECONDITION_FAILED.value());
		}
		return this.notModified;
	}

	boolean validated = validateIfNoneMatch(etag);
	if (!validated) {
		validateIfModifiedSince(lastModifiedTimestamp);
	}

	// Update response
	if (response != null) {
		boolean isHttpGetOrHead = SAFE_METHODS.contains(getRequest().getMethod());
		if (this.notModified) {
			response.setStatus(isHttpGetOrHead ?
					HttpStatus.NOT_MODIFIED.value() : HttpStatus.PRECONDITION_FAILED.value());
		}
		if (isHttpGetOrHead) {
			if (lastModifiedTimestamp > 0 && parseDateValue(response.getHeader(HttpHeaders.LAST_MODIFIED)) == -1) {
				response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedTimestamp);
			}
			if (StringUtils.hasLength(etag) && response.getHeader(HttpHeaders.ETAG) == null) {
				response.setHeader(HttpHeaders.ETAG, padEtagIfNecessary(etag));
			}
		}
	}

	return this.notModified;
}
 
Example 15
Source File: PluginHelper.java    From odo with Apache License 2.0 5 votes vote down vote up
public static void writeResponseContent(HttpServletResponse response, String content) throws IOException {
    // check to see if this is chunked
    boolean chunked = false;
    if (response.containsHeader(PluginHelper.STRING_TRANSFER_ENCODING)
            && response.getHeader(PluginHelper.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) {
        response.setHeader(PluginHelper.STRING_CONNECTION, PluginHelper.STRING_CHUNKED);
        chunked = true;
    }

    // check to see if this content is supposed to be compressed
    // if so recompress it
    boolean isEncoded = false;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (response.getHeader("content-encoding") != null &&
            response.getHeader("content-encoding").equals("gzip")) {
        // GZIP the data
        isEncoded = true;
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(content.getBytes());
        gzip.close();
        out.close();
    } else if (response.getHeader("content-encoding") != null &&
            response.getHeader("content-encoding").equals("deflate")) {
        // Deflate the data
        isEncoded = true;
        Deflater compressor = new Deflater();
        compressor.setInput(content.getBytes());
        compressor.finish();

        byte[] buffer = new byte[1024];
        while (!compressor.finished()) {
            int count = compressor.deflate(buffer);
            out.write(buffer, 0, count);
        }
        out.close();
        compressor.end();
    }


    // don't do this if we got a HTTP 304 since there is no data to send back
    if (response.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) {
        if (!chunked) {
            // change the content length header to the new length
            if (content != null && !isEncoded) {
                response.setContentLength(content.getBytes().length);
            } else if (isEncoded) {
                response.setContentLength(out.toByteArray().length);
            }
        }

        OutputStream outputStreamClientResponse = response.getOutputStream();
        response.resetBuffer();

        if (content != null && !isEncoded) {
            outputStreamClientResponse.write(content.getBytes());
        } else if (isEncoded) {
            outputStreamClientResponse.write(out.toByteArray());
        }
    }
}
 
Example 16
Source File: ServletFilterSpanDecorator.java    From java-web-servlet-filter with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 17
Source File: FrameworkServlet.java    From java-technology-stack with MIT License 4 votes vote down vote up
private void logResult(HttpServletRequest request, HttpServletResponse response,
		@Nullable Throwable failureCause, WebAsyncManager asyncManager) {

	if (!logger.isDebugEnabled()) {
		return;
	}

	String dispatchType = request.getDispatcherType().name();
	boolean initialDispatch = request.getDispatcherType().equals(DispatcherType.REQUEST);

	if (failureCause != null) {
		if (!initialDispatch) {
			// FORWARD/ERROR/ASYNC: minimal message (there should be enough context already)
			if (logger.isDebugEnabled()) {
				logger.debug("Unresolved failure from \"" + dispatchType + "\" dispatch: " + failureCause);
			}
		}
		else if (logger.isTraceEnabled()) {
			logger.trace("Failed to complete request", failureCause);
		}
		else {
			logger.debug("Failed to complete request: " + failureCause);
		}
		return;
	}

	if (asyncManager.isConcurrentHandlingStarted()) {
		logger.debug("Exiting but response remains open for further handling");
		return;
	}

	int status = response.getStatus();
	String headers = ""; // nothing below trace

	if (logger.isTraceEnabled()) {
		Collection<String> names = response.getHeaderNames();
		if (this.enableLoggingRequestDetails) {
			headers = names.stream().map(name -> name + ":" + response.getHeaders(name))
					.collect(Collectors.joining(", "));
		}
		else {
			headers = names.isEmpty() ? "" : "masked";
		}
		headers = ", headers={" + headers + "}";
	}

	if (!initialDispatch) {
		logger.debug("Exiting from \"" + dispatchType + "\" dispatch, status " + status + headers);
	}
	else {
		HttpStatus httpStatus = HttpStatus.resolve(status);
		logger.debug("Completed " + (httpStatus != null ? httpStatus : status) + headers);
	}
}
 
Example 18
Source File: Trace.java    From heimdall with Apache License 2.0 4 votes vote down vote up
/**
 * Writes a {@link HttpServletResponse} to the Heimdall Trace
 *
 * @param response	{@link HttpServletResponse}
 */
public void write(HttpServletResponse response) {

    try {

        this.resultStatus = response.getStatus();
        this.durationMillis = System.currentTimeMillis() - getInitialTime();

        if (!this.profile.equals("developer")) {
            this.filters = null;
        }

        writeTrace();

    } catch (Exception e) {

        log.error(e.getMessage(), e);

    } finally {

        TraceContextHolder.getInstance().clearActual();
    }

}
 
Example 19
Source File: AuditingInterceptor.java    From maven-framework-project with MIT License 4 votes vote down vote up
public void afterCompletion(HttpServletRequest request,	HttpServletResponse response, Object handler, Exception arg3) throws Exception {
	if(request.getRequestURI().endsWith("products/add") && response.getStatus()==302){
		logger.info(String.format("A New product[%s] Added by %s on %s", productId, user, getCurrentTime()));
	}
}
 
Example 20
Source File: AuditingInterceptor.java    From maven-framework-project with MIT License 4 votes vote down vote up
public void afterCompletion(HttpServletRequest request,	HttpServletResponse response, Object handler, Exception arg3) throws Exception {
	if(request.getRequestURI().endsWith("products/add") && response.getStatus()==302){
		logger.info(String.format("A New product[%s] Added by %s on %s", productId, user, getCurrentTime()));
	}
}