Search in sources :

Example 11 with HttpRequestMethodNotSupportedException

use of org.springframework.web.HttpRequestMethodNotSupportedException in project com.revolsys.open by revolsys.

the class AnnotationHandlerMethodResolver method resolveHandlerMethod.

public WebMethodHandler resolveHandlerMethod(final HttpServletRequest request) throws ServletException {
    final String lookupPath = this.adapter.urlPathHelper.getLookupPathForRequest(request);
    final Comparator<String> pathComparator = this.adapter.pathMatcher.getPatternComparator(lookupPath);
    final Map<RequestMappingInfo, WebMethodHandler> targetHandlerMethods = new LinkedHashMap<>();
    final Set<String> allowedMethods = new LinkedHashSet<>(7);
    String resolvedMethodName = null;
    for (final WebMethodHandler webMethodHandler : this.handlerMethods) {
        final Method handlerMethod = webMethodHandler.getMethod();
        final RequestMappingInfo mappingInfo = new RequestMappingInfo();
        final RequestMapping mapping = AnnotationUtils.findAnnotation(handlerMethod, RequestMapping.class);
        mappingInfo.paths = mapping.value();
        if (!hasTypeLevelMapping() || !Arrays.equals(mapping.method(), this.typeLevelMapping.method())) {
            mappingInfo.methods = mapping.method();
        }
        boolean match = false;
        if (mappingInfo.paths.length > 0) {
            final List<String> matchedPaths = new ArrayList<>(mappingInfo.paths.length);
            for (final String methodLevelPattern : mappingInfo.paths) {
                final String matchedPattern = getMatchedPattern(methodLevelPattern, lookupPath, request);
                if (matchedPattern != null) {
                    if (mappingInfo.matches(request)) {
                        match = true;
                        matchedPaths.add(matchedPattern);
                    } else {
                        for (final RequestMethod requestMethod : mappingInfo.methods) {
                            allowedMethods.add(requestMethod.toString());
                        }
                        break;
                    }
                }
            }
            Collections.sort(matchedPaths, pathComparator);
            mappingInfo.matchedPaths = matchedPaths;
        } else {
            // No paths specified: parameter match sufficient.
            match = mappingInfo.matches(request);
            if (match && mappingInfo.methods.length == 0 && resolvedMethodName != null && !resolvedMethodName.equals(handlerMethod.getName())) {
                match = false;
            } else {
                for (final RequestMethod requestMethod : mappingInfo.methods) {
                    allowedMethods.add(requestMethod.toString());
                }
            }
        }
        if (match) {
            WebMethodHandler oldMappedMethod = targetHandlerMethods.put(mappingInfo, webMethodHandler);
            if (oldMappedMethod != null && oldMappedMethod != webMethodHandler) {
                if (this.adapter.methodNameResolver != null && mappingInfo.paths.length == 0) {
                    if (!oldMappedMethod.getMethod().getName().equals(handlerMethod.getName())) {
                        if (resolvedMethodName == null) {
                            resolvedMethodName = this.adapter.methodNameResolver.getHandlerMethodName(request);
                        }
                        if (!resolvedMethodName.equals(oldMappedMethod.getMethod().getName())) {
                            oldMappedMethod = null;
                        }
                        if (!resolvedMethodName.equals(handlerMethod.getName())) {
                            if (oldMappedMethod != null) {
                                targetHandlerMethods.put(mappingInfo, oldMappedMethod);
                                oldMappedMethod = null;
                            } else {
                                targetHandlerMethods.remove(mappingInfo);
                            }
                        }
                    }
                }
                if (oldMappedMethod != null) {
                    throw new IllegalStateException("Ambiguous handler methods mapped for HTTP path '" + lookupPath + "': {" + oldMappedMethod + ", " + handlerMethod + "}. If you intend to handle the same path in multiple methods, then factor " + "them out into a dedicated handler class with that path mapped at the type level!");
                }
            }
        }
    }
    if (!targetHandlerMethods.isEmpty()) {
        final List<RequestMappingInfo> matches = new ArrayList<>(targetHandlerMethods.keySet());
        final RequestMappingInfoComparator requestMappingInfoComparator = new RequestMappingInfoComparator(pathComparator);
        Collections.sort(matches, requestMappingInfoComparator);
        final RequestMappingInfo bestMappingMatch = matches.get(0);
        final String bestMatchedPath = bestMappingMatch.bestMatchedPath();
        if (bestMatchedPath != null) {
            extractHandlerMethodUriTemplates(bestMatchedPath, lookupPath, request);
        }
        return targetHandlerMethods.get(bestMappingMatch);
    } else {
        if (!allowedMethods.isEmpty()) {
            throw new HttpRequestMethodNotSupportedException(request.getMethod(), StringUtils.toStringArray(allowedMethods));
        } else {
            throw new NoSuchRequestHandlingMethodException(lookupPath, request.getMethod(), request.getParameterMap());
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) NoSuchRequestHandlingMethodException(org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) LinkedHashMap(java.util.LinkedHashMap) RequestMapping(com.revolsys.ui.web.annotation.RequestMapping)

Example 12 with HttpRequestMethodNotSupportedException

use of org.springframework.web.HttpRequestMethodNotSupportedException in project spring-framework by spring-projects.

the class ResponseEntityExceptionHandlerTests method httpRequestMethodNotSupported.

@Test
public void httpRequestMethodNotSupported() {
    List<String> supported = Arrays.asList("POST", "DELETE");
    Exception ex = new HttpRequestMethodNotSupportedException("GET", supported);
    ResponseEntity<Object> responseEntity = testException(ex);
    assertThat(responseEntity.getHeaders().getAllow()).isEqualTo(Set.of(HttpMethod.POST, HttpMethod.DELETE));
}
Also used : HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) MissingPathVariableException(org.springframework.web.bind.MissingPathVariableException) ServletException(jakarta.servlet.ServletException) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) NoHandlerFoundException(org.springframework.web.servlet.NoHandlerFoundException) MissingServletRequestPartException(org.springframework.web.multipart.support.MissingServletRequestPartException) BindException(org.springframework.validation.BindException) ConversionNotSupportedException(org.springframework.beans.ConversionNotSupportedException) AsyncRequestTimeoutException(org.springframework.web.context.request.async.AsyncRequestTimeoutException) MissingServletRequestParameterException(org.springframework.web.bind.MissingServletRequestParameterException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ServletRequestBindingException(org.springframework.web.bind.ServletRequestBindingException) TypeMismatchException(org.springframework.beans.TypeMismatchException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) HttpMediaTypeNotSupportedException(org.springframework.web.HttpMediaTypeNotSupportedException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) Test(org.junit.jupiter.api.Test)

Example 13 with HttpRequestMethodNotSupportedException

use of org.springframework.web.HttpRequestMethodNotSupportedException in project spring-framework by spring-projects.

the class DefaultHandlerExceptionResolverTests method handleHttpRequestMethodNotSupported.

@Test
public void handleHttpRequestMethodNotSupported() {
    HttpRequestMethodNotSupportedException ex = new HttpRequestMethodNotSupportedException("GET", new String[] { "POST", "PUT" });
    ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex);
    assertThat(mav).as("No ModelAndView returned").isNotNull();
    assertThat(mav.isEmpty()).as("No Empty ModelAndView returned").isTrue();
    assertThat(response.getStatus()).as("Invalid status code").isEqualTo(405);
    assertThat(response.getHeader("Allow")).as("Invalid Allow header").isEqualTo("POST, PUT");
}
Also used : ModelAndView(org.springframework.web.servlet.ModelAndView) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) Test(org.junit.jupiter.api.Test)

Example 14 with HttpRequestMethodNotSupportedException

use of org.springframework.web.HttpRequestMethodNotSupportedException in project disconf by knightliao.

the class MyExceptionHandler method resolveException.

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
    LOG.warn(request.getRequestURI() + " ExceptionHandler FOUND. " + e.toString() + "\t" + e.getCause());
    // PathVariable 出错
    if (e instanceof TypeMismatchException) {
        return getParamErrors((TypeMismatchException) e);
    // Bean 参数无法映射错误
    } else if (e instanceof InvalidPropertyException) {
        return getParamErrors((InvalidPropertyException) e);
    // @Valid 出错
    } else if (e instanceof BindException) {
        return ParamValidateUtils.getParamErrors((BindException) e);
    // 业务校验处理
    } else if (e instanceof FieldException) {
        return getParamErrors((FieldException) e);
    } else if (e instanceof DocumentNotFoundException) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        try {
            FileUtils.closeWriter(response.getWriter());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    // 用户没有请求方法的访问权限
    } else if (e instanceof AccessDeniedException) {
        LOG.warn("details: " + ((AccessDeniedException) e).getErrorMessage());
        return buildError("auth.access.denied", ErrorCode.ACCESS_NOAUTH_ERROR);
    } else if (e instanceof HttpRequestMethodNotSupportedException) {
        return buildError("syserror.httpmethod", ErrorCode.HttpRequestMethodNotSupportedException);
    } else if (e instanceof MissingServletRequestParameterException) {
        return buildError("syserror.param.miss", ErrorCode.MissingServletRequestParameterException);
    } else if (e instanceof GlobalExceptionAware) {
        LOG.error("details: ", e);
        GlobalExceptionAware g = (GlobalExceptionAware) e;
        return buildError(g.getErrorMessage(), g.getErrorCode());
    } else {
        LOG.warn("details: ", e);
        return buildError("syserror.inner", ErrorCode.GLOBAL_ERROR);
    }
}
Also used : AccessDeniedException(com.baidu.dsp.common.exception.AccessDeniedException) FieldException(com.baidu.dsp.common.exception.FieldException) DocumentNotFoundException(com.baidu.dsp.common.exception.DocumentNotFoundException) GlobalExceptionAware(com.baidu.dsp.common.exception.base.GlobalExceptionAware) TypeMismatchException(org.springframework.beans.TypeMismatchException) InvalidPropertyException(org.springframework.beans.InvalidPropertyException) BindException(org.springframework.validation.BindException) IOException(java.io.IOException) MissingServletRequestParameterException(org.springframework.web.bind.MissingServletRequestParameterException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException)

Example 15 with HttpRequestMethodNotSupportedException

use of org.springframework.web.HttpRequestMethodNotSupportedException in project spring-boot by spring-projects.

the class CompositeHandlerExceptionResolverTests method resolverShouldAddDefaultResolverIfNonePresent.

@Test
void resolverShouldAddDefaultResolverIfNonePresent() {
    load(BaseConfiguration.class);
    CompositeHandlerExceptionResolver resolver = (CompositeHandlerExceptionResolver) this.context.getBean(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME);
    HttpRequestMethodNotSupportedException exception = new HttpRequestMethodNotSupportedException("POST");
    ModelAndView resolved = resolver.resolveException(this.request, this.response, null, exception);
    assertThat(resolved).isNotNull();
    assertThat(resolved.isEmpty()).isTrue();
}
Also used : ModelAndView(org.springframework.web.servlet.ModelAndView) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) Test(org.junit.jupiter.api.Test)

Aggregations

HttpRequestMethodNotSupportedException (org.springframework.web.HttpRequestMethodNotSupportedException)15 Test (org.junit.jupiter.api.Test)5 ModelAndView (org.springframework.web.servlet.ModelAndView)4 IOException (java.io.IOException)3 Test (org.junit.Test)2 TypeMismatchException (org.springframework.beans.TypeMismatchException)2 BindException (org.springframework.validation.BindException)2 HttpMediaTypeNotAcceptableException (org.springframework.web.HttpMediaTypeNotAcceptableException)2 HttpMediaTypeNotSupportedException (org.springframework.web.HttpMediaTypeNotSupportedException)2 MissingServletRequestParameterException (org.springframework.web.bind.MissingServletRequestParameterException)2 ServletRequestBindingException (org.springframework.web.bind.ServletRequestBindingException)2 RestfulResult (cn.opencil.vo.RestfulResult)1 AccessDeniedException (com.baidu.dsp.common.exception.AccessDeniedException)1 DocumentNotFoundException (com.baidu.dsp.common.exception.DocumentNotFoundException)1 FieldException (com.baidu.dsp.common.exception.FieldException)1 GlobalExceptionAware (com.baidu.dsp.common.exception.base.GlobalExceptionAware)1 RequestMapping (com.revolsys.ui.web.annotation.RequestMapping)1 ValidationException (com.shaoqunliu.validation.ValidationException)1 ServletException (jakarta.servlet.ServletException)1 Method (java.lang.reflect.Method)1