javax.servlet.http.HttpServletResponse#sendError()源码实例Demo

下面列出了javax.servlet.http.HttpServletResponse#sendError() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: lams   文件: FindUserLessonsController.java
@ResponseBody
   @RequestMapping("/autocomplete")
   public String autocomplete(HttpServletRequest request, HttpServletResponse response) throws Exception {
Integer courseID = WebUtil.readIntParam(request, "courseID", true);
if (!securityService.isGroupMonitor(courseID, getUserId(), "autocomplete for find user lessons", false)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation");
    return null;
}

String query = WebUtil.readStrParam(request, "term", true);
Organisation rootOrg = (Organisation) userManagementService.findById(Organisation.class, courseID);

List<User> userSet = userManagementService.findUsers(query, rootOrg.getOrganisationId(), true);
ArrayNode jsonArray = JsonNodeFactory.instance.arrayNode();
for (User user : userSet) {
    ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
    jsonObject.put("label", user.getFirstName() + " " + user.getLastName());
    jsonObject.put("value", user.getUserId());
    jsonArray.add(jsonObject);
}

response.setContentType("application/json;charset=utf-8");
response.getWriter().print(jsonArray);
return null;
   }
 
源代码2 项目: lams   文件: MonitoringController.java
/**
    * The purpose of suspending is to hide the lesson from learners temporarily. It doesn't make any sense to suspend a
    * created or a not started (ie scheduled) lesson as they will not be shown on the learner interface anyway! If the
    * teacher tries to suspend a lesson that is not in the STARTED_STATE, then an error should be returned to UI.
    */
   @RequestMapping(path = "/suspendLesson", method = RequestMethod.POST)
   public void suspendLesson(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException, ParseException {
long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID);
String dateStr = WebUtil.readStrParam(request, MonitoringConstants.PARAM_LESSON_END_DATE, true);
try {
    if (dateStr == null || dateStr.length() == 0) {
	monitoringService.suspendLesson(lessonId, getUserId(), true);
    } else {
	monitoringService.finishLessonOnSchedule(lessonId,
		MonitoringController.LESSON_SCHEDULING_DATETIME_FORMAT.parse(dateStr), getUserId());
    }
} catch (SecurityException e) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson");
}
   }
 
源代码3 项目: tomcatsrc   文件: WebdavServlet.java
/**
 * Process a PUT request for the specified resource.
 *
 * @param req The servlet request we are processing
 * @param resp The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    if (isLocked(req)) {
        resp.sendError(WebdavStatus.SC_LOCKED);
        return;
    }

    super.doPut(req, resp);

    String path = getRelativePath(req);

    // Removing any lock-null resource which would be present
    lockNullResources.remove(path);

}
 
源代码4 项目: mycore   文件: MCRQRCodeServlet.java
@Override
public MCRContent getContent(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    String pathInfo = req.getPathInfo();
    Matcher matcher = REQUEST_PATTERN.matcher(pathInfo);
    if (!matcher.matches()) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Path info does not comply to " + REQUEST_PATTERN + ": "
            + pathInfo);
        return null;
    }
    int size = Integer.parseInt(matcher.group(1));
    String relativeURL = matcher.group(2);
    String queryString = req.getQueryString();
    String url = MCRFrontendUtil.getBaseURL() + relativeURL;
    if (queryString != null) {
        url += '?' + queryString;
    }
    LOGGER.info("Generating QR CODE: {}", url);
    MCRContent content = getPNGContent(url, size);
    content.setLastModified(0);
    if (!"HEAD".equals(req.getMethod())) {
        MCRFrontendUtil.writeCacheHeaders(resp, CACHE_TIME, 0, true);
    }
    return content;
}
 
源代码5 项目: openid4java   文件: HttpServletSupport.java
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
    count_++;
    String ndcName = getClass().getName();
    ndcName = ndcName.substring(ndcName.lastIndexOf('.')+1);
    NDC.push(ndcName);
    NDC.push("call-" + count_);
    logger_.info("begin onService");
    try
    {
        onService(req, resp);
    }
    catch (Exception exc)
    {
        lastException = exc;
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    finally
    {
        logger_.info("end onService");
        NDC.pop();
        NDC.pop();
    }
}
 
/**
 * Template method that handles {@link ResponseStatus @ResponseStatus} annotation.
 * <p>The default implementation sends a response error using
 * {@link HttpServletResponse#sendError(int)} or
 * {@link HttpServletResponse#sendError(int, String)} if the annotation has a
 * {@linkplain ResponseStatus#reason() reason} and then returns an empty ModelAndView.
 * @param responseStatus the annotation
 * @param request current HTTP request
 * @param response current HTTP response
 * @param handler the executed handler, or {@code null} if none chosen at the
 * time of the exception (for example, if multipart resolution failed)
 * @param ex the exception that got thrown during handler execution or the
 * exception that has the ResponseStatus annotation if found on the cause.
 * @return a corresponding ModelAndView to forward to, or {@code null}
 * for default processing
 */
protected ModelAndView resolveResponseStatus(ResponseStatus responseStatus, HttpServletRequest request,
		HttpServletResponse response, Object handler, Exception ex) throws Exception {

	int statusCode = responseStatus.code().value();
	String reason = responseStatus.reason();
	if (this.messageSource != null) {
		reason = this.messageSource.getMessage(reason, null, reason, LocaleContextHolder.getLocale());
	}
	if (!StringUtils.hasLength(reason)) {
		response.sendError(statusCode);
	}
	else {
		response.sendError(statusCode, reason);
	}
	return new ModelAndView();
}
 
源代码7 项目: HongsCORE   文件: RestAction.java
@Override
protected void service(HttpServletRequest req, HttpServletResponse rsp)
        throws ServletException, IOException {
    switch(req.getMethod()) {
        case METHOD_GET   :
            reset(req, ACTION_GET   );
            super.service( req, rsp );
            break;
        case METHOD_ADD   :
        case METHOD_POST  :
            req.setAttribute(Cnst.UPDATE_MODE, false);
            reset(req, ACTION_POST  );
            super.service( req, rsp );
            break;
        case METHOD_PUT   :
        case METHOD_PATCH :
            req.setAttribute(Cnst.UPDATE_MODE, true );
            reset(req, ACTION_PATCH );
            super.service( req, rsp );
            break;
        case METHOD_DELETE:
            reset(req, ACTION_DELETE);
            super.service( req, rsp );
            break;
        default:
            rsp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
            req.getMethod() + " is not allowed for this resource!");
    }
}
 
源代码8 项目: fenixedu-academic   文件: FindSpacesDA.java
public ActionForward viewSpaceBlueprint(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
//        return new ManageSpaceBlueprintsDA().view(mapping, actionForm, request, response);

        Boolean isToViewOriginalSpaceBlueprint = isToViewOriginalSpaceBlueprint(request);

        Boolean viewBlueprintNumbers = isToViewBlueprintNumbers(request);
        Boolean isToViewIdentifications = isToViewSpaceIdentifications(request);
        Boolean isToViewDoorNumbers = isToViewDoorNumbers(request);

        BigDecimal scalePercentage = getScalePercentage(request);

        DateTime now = new DateTime();

        Space space = getDomainObject(request, "spaceId");

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

        response.setContentType("text/plain");
        response.setHeader("Content-disposition", "attachment; filename=blueprint.jpeg");
        final ServletOutputStream writer = response.getOutputStream();

        SpaceBlueprintsDWGProcessor.writeBlueprint(space, now, isToViewOriginalSpaceBlueprint, viewBlueprintNumbers,
                isToViewIdentifications, isToViewDoorNumbers, scalePercentage, writer);

        return null;
    }
 
源代码9 项目: Tomcat7.0.67   文件: DefaultServlet.java
/**
 * Check if the if-match condition is satisfied.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param resourceAttributes File object
 * @return boolean true if the resource meets the specified condition,
 * and false if the condition is not satisfied, in which case request
 * processing is stopped
 */
protected boolean checkIfMatch(HttpServletRequest request,
                             HttpServletResponse response,
                             ResourceAttributes resourceAttributes)
    throws IOException {

    String eTag = resourceAttributes.getETag();
    String headerValue = request.getHeader("If-Match");
    if (headerValue != null) {
        if (headerValue.indexOf('*') == -1) {

            StringTokenizer commaTokenizer = new StringTokenizer
                (headerValue, ",");
            boolean conditionSatisfied = false;

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(eTag))
                    conditionSatisfied = true;
            }

            // If none of the given ETags match, 412 Precodition failed is
            // sent back
            if (!conditionSatisfied) {
                response.sendError
                    (HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }

        }
    }
    return true;

}
 
源代码10 项目: dhis2-core   文件: AppController.java
@RequestMapping( method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_JSON )
public void getApps( @RequestParam( required = false ) String key,
    HttpServletRequest request, HttpServletResponse response )
    throws IOException
{
    List<String> filters = Lists.newArrayList( contextService.getParameterValues( "filter" ) );
    String contextPath = ContextUtils.getContextPath( request );

    List<App> apps = new ArrayList<>();

    if ( key != null )
    {
        App app = appManager.getApp( key, contextPath );

        if ( app == null )
        {
            response.sendError( HttpServletResponse.SC_NOT_FOUND );
            return;
        }

        apps.add( app );
    }
    else if ( !filters.isEmpty() )
    {
        apps = appManager.filterApps( filters, contextPath );
    }
    else
    {
        apps = appManager.getApps( contextPath );
    }

    response.setContentType( MediaType.APPLICATION_JSON_VALUE );
    renderService.toJson( response.getOutputStream(), apps );
}
 
源代码11 项目: drivemarks   文件: BaseServlet.java
/**
 * Returns true if one of the required query parameters is missing.
 * @param req
 * @param resp
 * @param paramNames
 * @return
 * @throws IOException
 */
protected boolean requireQueryParams(HttpServletRequest req,
    HttpServletResponse resp, String... paramNames) throws IOException {
  for (String paramName: paramNames) {
    if (req.getParameter(paramName) == null) {
      resp.sendError(400, "Missing parameter: " + paramName);
      return true;
    }
  }
  return false;
}
 
@Override
public void commence(HttpServletRequest request,
                     HttpServletResponse response,
                     AuthenticationException authException) throws IOException {
    // This is invoked when user tries to access a secured REST resource without supplying any credentials
    // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
 
@RequestMapping(value = Routes.ROOT_AUTHORIZATION_COLLECTION, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody
public void index(HttpServletRequest request, HttpServletResponse response,
		@RequestParam Map<String, String> params) throws IOException,
		FeedException {

	// Verify request contains valid query parameters
	if(!VerifyURLParams.verifyEntries(Routes.ROOT_AUTHORIZATION_COLLECTION, params)) {

		response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request contains invalid query parameter values!");
		return;
	}

	response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
	String accessToken = request.getHeader("authorization").replace(
			"Bearer ", "");
	Authorization authorization = authorizationService
			.findByAccessToken(accessToken);

	// we know this is a client-access-token or a datacustodian-access-token
	// if it is a datacustodian-access-token, it can get everything

	if (authorization.getApplicationInformation().getClientId()
			.equals("data_custodian_admin")) {
		exportService.exportAuthorizations(response.getOutputStream(),
				new ExportFilter(params));
	} else {
		// anything else that gets here is a third party
		// (client-access-token) and needs to be
		// restricted in access scope
		exportService.exportAuthorizations(authorization,
				response.getOutputStream(), new ExportFilter(params));
	}
}
 
源代码14 项目: uyuni   文件: TinyUrlAction.java
/**
 * {@inheritDoc}
 */
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
    throws Exception {
    String token = request.getParameter(TY_TOKEN);
    if (log.isDebugEnabled()) {
        log.debug("token: " + token);
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            log.debug("param.name: " + name + " val: " +
                    request.getParameter(name));
        }
    }

    TinyUrl turl = CommonFactory.lookupTinyUrl(token);
    if (turl != null) {
        if (log.isDebugEnabled()) {
            log.debug("turl: " + turl.getUrl());
        }
        request.setAttribute("ksurl", turl.getUrl());
        if (log.isDebugEnabled()) {
            log.debug("ksurl in request attribute before we call include: " +
                    request.getAttribute("ksurl"));
        }
        request.getRequestDispatcher("/kickstart/DownloadFile.do").
            forward(request, response);
        if (log.isDebugEnabled()) {
            log.debug("include() called ...");
        }
    }
    else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    return null;
}
 
源代码15 项目: mycore   文件: MCRServletContentHelper.java
/**
 * Check if the If-Match condition is satisfied.
 */
private static boolean checkIfMatch(final HttpServletRequest request, final HttpServletResponse response,
    final MCRContent content) throws IOException {

    final String eTag = content.getETag();
    final String headerValue = request.getHeader("If-Match");
    if (headerValue != null) {
        if (headerValue.indexOf('*') == -1) {

            final StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
            boolean conditionSatisfied = false;

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                final String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(eTag)) {
                    conditionSatisfied = true;
                }
            }

            // none of the given ETags match
            if (!conditionSatisfied) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }

        }
    }
    return true;
}
 
源代码16 项目: kork   文件: GenericExceptionHandlers.java
@ExceptionHandler(RetrofitError.class)
public void handleRetrofitError(
    RetrofitError e, HttpServletResponse response, HttpServletRequest request)
    throws IOException {
  if (e.getResponse() != null) {
    Map<String, Object> additionalContext = new HashMap<>();
    additionalContext.put("url", e.getResponse().getUrl());

    Header contentTypeHeader =
        e.getResponse().getHeaders().stream()
            .filter(h -> h.getName().equalsIgnoreCase("content-type"))
            .findFirst()
            .orElse(null);

    if (contentTypeHeader != null
        && contentTypeHeader.getValue().toLowerCase().contains("application/json")) {
      // include any json responses
      additionalContext.put(
          "body",
          CharStreams.toString(
              new InputStreamReader(e.getResponse().getBody().in(), Charsets.UTF_8)));
    }

    storeException(
        request, response, new RetrofitErrorWrapper(e.getMessage(), additionalContext));
    response.sendError(e.getResponse().getStatus(), e.getMessage());
  } else {
    // no retrofit response (likely) indicates a NETWORK error
    handleException(e, response, request);
  }
}
 
@ExceptionHandler(Exception.class)
public void handleGenericException(HttpServletResponse response, Exception e) throws IOException {
    response.sendError(HttpStatus.BAD_REQUEST.value(), "There was an error processing your request: " + e.getMessage());
}
 
源代码18 项目: sk-admin   文件: JwtAccessDeniedHandler.java
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
   //当用户在没有授权的情况下访问受保护的REST资源时,将调用此方法发送403 Forbidden响应
   response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
}
 
源代码19 项目: Tomcat7.0.67   文件: WebSocketServlet.java
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    // Information required to send the server handshake message
    String key;
    String subProtocol = null;
    List<String> extensions = Collections.emptyList();

    if (!headerContainsToken(req, "upgrade", "websocket")) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (!headerContainsToken(req, "connection", "upgrade")) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    if (!headerContainsToken(req, "sec-websocket-version", "13")) {
        resp.setStatus(426);
        resp.setHeader("Sec-WebSocket-Version", "13");
        return;
    }

    key = req.getHeader("Sec-WebSocket-Key");
    if (key == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    String origin = req.getHeader("Origin");
    if (!verifyOrigin(origin)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    List<String> subProtocols = getTokensFromHeader(req,
            "Sec-WebSocket-Protocol");
    if (!subProtocols.isEmpty()) {
        subProtocol = selectSubProtocol(subProtocols);

    }

    // TODO Read client handshake - Sec-WebSocket-Extensions

    // TODO Extensions require the ability to specify something (API TBD)
    //      that can be passed to the Tomcat internals and process extension
    //      data present when the frame is fragmented.

    // If we got this far, all is good. Accept the connection.
    resp.setHeader("Upgrade", "websocket");
    resp.setHeader("Connection", "upgrade");
    resp.setHeader("Sec-WebSocket-Accept", getWebSocketAccept(key));
    if (subProtocol != null) {
        resp.setHeader("Sec-WebSocket-Protocol", subProtocol);
    }
    if (!extensions.isEmpty()) {
        // TODO
    }

    WsHttpServletRequestWrapper wrapper = new WsHttpServletRequestWrapper(req);
    StreamInbound inbound = createWebSocketInbound(subProtocol, wrapper);
    wrapper.invalidate();

    // Small hack until the Servlet API provides a way to do this.
    ServletRequest inner = req;
    // Unwrap the request
    while (inner instanceof ServletRequestWrapper) {
        inner = ((ServletRequestWrapper) inner).getRequest();
    }
    if (inner instanceof RequestFacade) {
        ((RequestFacade) inner).doUpgrade(inbound);
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                sm.getString("servlet.reqUpgradeFail"));
    }
}
 
private void sendErrorInvalidConfiguration(HttpServletResponse response) throws IOException {
  response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, invalidConfigurationMessage);
}