@ExceptionHandler(HttpRequestMethodNotSupportedException.class) public ResponseEntity<OAuth2Exception> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) throws Exception { if (logger.isInfoEnabled()) { logger.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); } return getExceptionTranslator().translate(e); }
/** * Check the given request for supported methods and a required session, if any. * @param request current HTTP request * @throws ServletException if the request cannot be handled because a check failed * @since 4.2 */ protected final void checkRequest(HttpServletRequest request) throws ServletException { // Check whether we should support the request method. String method = request.getMethod(); if (this.supportedMethods != null && !this.supportedMethods.contains(method)) { throw new HttpRequestMethodNotSupportedException(method, this.supportedMethods); } // Check whether a session is required. if (this.requireSession && request.getSession(false) == null) { throw new HttpSessionRequiredException("Pre-existing session required but none found"); } }
/** * Customize the response for HttpRequestMethodNotSupportedException. * <p>This method logs a warning, sets the "Allow" header, and delegates to * {@link #handleExceptionInternal}. * @param ex the exception * @param headers the headers to be written to the response * @param status the selected response status * @param request the current request * @return a {@code ResponseEntity} instance */ protected ResponseEntity<Object> handleHttpRequestMethodNotSupported( HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { pageNotFoundLogger.warn(ex.getMessage()); Set<HttpMethod> supportedMethods = ex.getSupportedHttpMethods(); if (!CollectionUtils.isEmpty(supportedMethods)) { headers.setAllow(supportedMethods); } return handleExceptionInternal(ex, null, headers, status, request); }
/** * Handle the case where no request handler method was found for the particular HTTP request method. * <p>The default implementation logs a warning, sends an HTTP 405 error, sets the "Allow" header, * and returns an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen, * or the HttpRequestMethodNotSupportedException could be rethrown as-is. * @param ex the HttpRequestMethodNotSupportedException to be handled * @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) * @return an empty ModelAndView indicating the exception was handled * @throws IOException potentially thrown from {@link HttpServletResponse#sendError} */ protected ModelAndView handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpServletRequest request, HttpServletResponse response, @Nullable Object handler) throws IOException { String[] supportedMethods = ex.getSupportedMethods(); if (supportedMethods != null) { response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", ")); } response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage()); return new ModelAndView(); }
@ExceptionHandler(HttpRequestMethodNotSupportedException.class) public ResponseEntity<OAuth2Exception> handleMethodNotSupportedException(HttpRequestMethodNotSupportedException e) throws Exception { logger.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); ResponseEntity<OAuth2Exception> result = exceptionTranslator.translate(e); if (HttpMethod.POST.matches(e.getMethod())) { OAuth2Exception cause = new OAuth2Exception("Parameters must be passed in the body of the request", result.getBody().getCause()) { public String getOAuth2ErrorCode() { return "query_string_not_allowed"; } public int getHttpErrorCode() { return NOT_ACCEPTABLE.value(); } }; result = new ResponseEntity<>(cause, result.getHeaders(), NOT_ACCEPTABLE); } return result; }
@Override protected HttpHeaders createHeaders(HttpRequestMethodNotSupportedException ex, HttpServletRequest req) { HttpHeaders headers = super.createHeaders(ex, req); if (!isEmpty(ex.getSupportedMethods())) { headers.setAllow(ex.getSupportedHttpMethods()); } return headers; } }
@Test public void getRequestNotAllowed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("GET"); request.setParameter("foo", "bar"); request.setRequestURI("/postOnly"); try { this.integrationRequestMappingHandlerMapping.getHandler(request); } catch (HttpRequestMethodNotSupportedException e) { assertEquals("GET", e.getMethod()); assertArrayEquals(new String[] {"POST"}, e.getSupportedMethods()); } }
@Override protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(final HttpRequestMethodNotSupportedException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { logger.info(ex.getClass().getName()); // final StringBuilder builder = new StringBuilder(); builder.append(ex.getMethod()); builder.append(" method is not supported for this request. Supported methods are "); ex.getSupportedHttpMethods().forEach(t -> builder.append(t + " ")); final ApiError apiError = new ApiError(HttpStatus.METHOD_NOT_ALLOWED, ex.getLocalizedMessage(), builder.toString()); return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus()); }
/** * 请求方式不支持异常 * 比如:POST方式的API, GET方式请求 */ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ResponseMessage handleException(HttpRequestMethodNotSupportedException exception) { return ResponseMessage .error(HttpStatus.METHOD_NOT_ALLOWED.value(), "不支持的请求方式") .result(exception.getSupportedHttpMethods()); }
return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND); } else if (e instanceof HttpRequestMethodNotSupportedException) { log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods())); return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD); } else if (e instanceof MethodArgumentNotValidException) {
@Test(expected = HttpRequestMethodNotSupportedException.class) public void call_to_get_always_throws_super_method() throws Exception { UaaTokenEndpoint endpoint = new UaaTokenEndpoint(); endpoint.setAllowedRequestMethods(allowedRequestMethods); endpoint.setAllowQueryString(false); try { endpoint.getAccessToken(mock(Principal.class), emptyMap()); } catch (HttpRequestMethodNotSupportedException e) { assertEquals("GET", e.getMethod()); throw e; } }
@Test public void getHandlerRequestMethodNotAllowed() throws Exception { try { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/bar"); this.handlerMapping.getHandler(request); fail("HttpRequestMethodNotSupportedException expected"); } catch (HttpRequestMethodNotSupportedException ex) { assertArrayEquals("Invalid supported methods", new String[]{"GET", "HEAD"}, ex.getSupportedMethods()); } }
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Assert.state(this.target != null, "No HttpRequestHandler available"); LocaleContextHolder.setLocale(request.getLocale()); try { this.target.handleRequest(request, response); } catch (HttpRequestMethodNotSupportedException ex) { String[] supportedMethods = ex.getSupportedMethods(); if (supportedMethods != null) { response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", ")); } response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage()); } finally { LocaleContextHolder.resetLocaleContext(); } }
/** * 请求方式不支持 */ @ExceptionHandler({HttpRequestMethodNotSupportedException.class}) public AjaxResult handleException(HttpRequestMethodNotSupportedException e) { log.error(e.getMessage(), e); return AjaxResult.error("不支持' " + e.getMethod() + "'请求"); }
@Override public Optional<HttpHeaders> createHeaders( // final RequestAttributes requestAttributes, // final HttpRequestMethodNotSupportedException exception // ) { final HttpHeaders headers = super.createHeaders(requestAttributes, exception).orElse(new HttpHeaders()); if (!isEmpty(exception.getSupportedMethods())) { headers.setAllow(exception.getSupportedHttpMethods()); } return !headers.isEmpty() ? Optional.of(headers) : Optional.empty(); } }
/** * Send {@code 405 Method Not Allowed} and include the supported {@link org.springframework.http.HttpMethod}s in the * {@code Allow} header. * * @param o_O the exception to handle. * @return */ @ExceptionHandler ResponseEntity<Void> handle(HttpRequestMethodNotSupportedException o_O) { HttpHeaders headers = new HttpHeaders(); headers.setAllow(o_O.getSupportedHttpMethods()); return response(HttpStatus.METHOD_NOT_ALLOWED, headers); }
@Test(expected = HttpRequestMethodNotSupportedException.class) public void call_to_get_always_throws_override_method() throws Exception { UaaTokenEndpoint endpoint = new UaaTokenEndpoint(); endpoint.setAllowedRequestMethods(allowedRequestMethods); endpoint.setAllowQueryString(false); try { endpoint.doDelegateGet(mock(Principal.class), emptyMap()); } catch (HttpRequestMethodNotSupportedException e) { assertEquals("GET", e.getMethod()); throw e; } } }
/** * Handle the case where no request handler method was found for the particular HTTP request method. * <p>The default implementation logs a warning, sends an HTTP 405 error, sets the "Allow" header, * and returns an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen, * or the HttpRequestMethodNotSupportedException could be rethrown as-is. * @param ex the HttpRequestMethodNotSupportedException to be handled * @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) * @return an empty ModelAndView indicating the exception was handled * @throws IOException potentially thrown from {@link HttpServletResponse#sendError} */ protected ModelAndView handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { String[] supportedMethods = ex.getSupportedMethods(); if (supportedMethods != null) { response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", ")); } response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage()); return new ModelAndView(); }
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; try { super.doFilter(request, response, chain); } catch (RequestRejectedException e) { REQUEST_REJECTED_EXCEPTION_HANDLER.handle(request, response, e.getMessage(), HttpStatus.BAD_REQUEST); } catch (HttpRequestMethodNotSupportedException e) { REQUEST_REJECTED_EXCEPTION_HANDLER.handle(request, response, e.getMessage(), HttpStatus.METHOD_NOT_ALLOWED); } } }
/** * Handle the case where no request handler method was found for the particular HTTP request method. * <p>The default implementation logs a warning, sends an HTTP 405 error, sets the "Allow" header, * and returns an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen, * or the HttpRequestMethodNotSupportedException could be rethrown as-is. * @param ex the HttpRequestMethodNotSupportedException to be handled * @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) * @return an empty ModelAndView indicating the exception was handled * @throws IOException potentially thrown from {@link HttpServletResponse#sendError} */ protected ModelAndView handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpServletRequest request, HttpServletResponse response, @Nullable Object handler) throws IOException { String[] supportedMethods = ex.getSupportedMethods(); if (supportedMethods != null) { response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", ")); } response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage()); return new ModelAndView(); }