Spring Boot-请求方法'POST'不支持尝试了一切

如何解决Spring Boot-请求方法'POST'不支持尝试了一切

遵循可能会有所帮助。

  1. 在部署应用程序时,spring boot在控制台上显示所有可用服务。检查创建的POST方法是否显示。检查与其他服务不应有任何矛盾。GET / PUT / POST
  2. 如果没有部署服务,请尝试在其他服务(GET,PUT和POST)之前添加“ /”。
  3. 添加异常处理程序以检查客户端输入请求以检查POJO结构。
  4. 检查URL-如果在配置中添加了应用程序/名称的全局路径
  5. 尝试删除标题-请求标题中的Content-Type并再次发布请求

以下是可能发生的不同事情。无需按顺序进行。

编辑:

运行以下命令检查spring应用程序是否启用并考虑了控制器。

import java.util.Arrays;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }

    }

解决方法

我正在使用Spring Boot和MongoDB构建一个Web应用程序,它将仅对员工文档执行CRUD操作。

"Request method 'POST' not supported"当我尝试使用json命中create employee端点时出现此错误。

我的控制器类是:

@RestController
@RequestMapping("/employeeapp/employees")
public class EmployeeController {

    private final EmployeeService service;

    @Autowired
    public EmployeeController(EmployeeService service) {
        this.service = service;
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public
    @ResponseBody
    Employee create(@RequestBody @Valid Employee employeeEntry) {
        return service.create(employeeEntry);
    }

    @RequestMapping(value = "{id}",method = RequestMethod.DELETE)
    public Employee delete(@PathVariable("id") long id) {
        return service.delete(id);
    }

    @RequestMapping(method = RequestMethod.GET)
    public List<Employee> findAll() {
        return service.findAll();
    }

    @RequestMapping(value = "{id}",method = RequestMethod.GET)
    public Employee findById(@PathVariable("id") long id) {
        return service.findById(id);
    }

    @RequestMapping(value = "{id}",method = RequestMethod.PUT)
    public Employee update(@RequestBody @Valid Employee employeeEntry) {
        return service.update(employeeEntry);
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public void handleEmployeeNotFound(EmployeeNotFoundException exception) {
    }

}

应用类别:

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class,args);
    }
}

我尝试禁用csrf,添加@ResponseBody了方法,但似乎没有任何效果。

编辑

我遇到http://localhost:8080/employeeapp/employees了POST请求。标题包含Content-Type : application/json,并在正文中包含以下json:

{
    "id" : 1,"name" : "nikhil","dept" : "DCX"
}

另外,这是我通过POST请求点击上述URL时在日志中看到的内容。

2016-02-19 12:21:36.549  INFO 5148 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       :
Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-02-19 12:21:36.549  INFO 5148 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        :
FrameworkServlet 'dispatcherServlet': initialization started
2016-02-19 12:21:36.562  INFO 5148 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        :
FrameworkServlet 'dispatcherServlet': initialization completed in 13 ms
2016-02-19 12:21:36.595  WARN 5148 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound             :
Request method 'POST' not supported

编辑2:

我检查了Spring引导日志,结果是未生成映射,而是spring映射到默认服务。知道为什么会发生吗?

    [INFO] --- spring-boot-maven-plugin:1.3.2.RELEASE:run (default-cli) @ EmployeeApp ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__,| / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.2.RELEASE)

2016-02-19 14:51:00.690  INFO 5080 --- [           main] app.Application                          : Starting Application on DIN16003277 with PID 5080 (D:\!Nikhil\Documents\Code\EmployeeApp\target\classes started by nvibhav in D:\!Nikhil\Documents\Code\EmployeeApp)
2016-02-19 14:51:00.693  INFO 5080 --- [           main] app.Application                          : No active profile set,falling back to default profiles: default
2016-02-19 14:51:00.770  INFO 5080 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@46117566: startup date [Fri Feb 19 14:51:00 IST 2016]; root of context hierarchy
2016-02-19 14:51:01.987  INFO 5080 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-02-19 14:51:02.567  INFO 5080 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-02-19 14:51:03.026  INFO 5080 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-02-19 14:51:03.037  INFO 5080 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-02-19 14:51:03.039  INFO 5080 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.30
2016-02-19 14:51:03.172  INFO 5080 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-02-19 14:51:03.173  INFO 5080 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2409 ms
2016-02-19 14:51:03.689  INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'metricFilter' to: [/*]
2016-02-19 14:51:03.689  INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-02-19 14:51:03.690  INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-02-19 14:51:03.690  INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-02-19 14:51:03.690  INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2016-02-19 14:51:03.691  INFO 5080 --- [ost-startStop-1] .e.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2016-02-19 14:51:03.691  INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2016-02-19 14:51:03.691  INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'applicationContextIdFilter' to: [/*]
2016-02-19 14:51:03.692  INFO 5080 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2016-02-19 14:51:04.011  INFO 5080 --- [ost-startStop-1] b.a.s.AuthenticationManagerConfiguration :

Using default security password: c652ec29-f926-40eb-bb5b-2bd9185bf6a5

2016-02-19 14:51:04.075  INFO 5080 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'],Ant [pattern='/js/**'],Ant [pattern='/images/**'],Ant [pattern='/**/favicon.ico'],Ant [pattern='/error']]],[]
2016-02-19 14:51:04.141  INFO 5080 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1,[org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@71d64e0f,org.springframework.security.web.context.SecurityContextPersistenceFilter@68e32d1f,org.springframework.security.web.header.HeaderWriterFilter@30bd43e4,org.springframework.security.web.authentication.logout.LogoutFilter@6a766ce6,org.springframework.security.web.savedrequest.RequestCacheAwareFilter@3111b148,org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@75e89f1f,org.springframework.security.web.authentication.AnonymousAuthenticationFilter@289e0d8f,org.springframework.security.web.session.SessionManagementFilter@4ec4999b,org.springframework.security.web.access.ExceptionTranslationFilter@3f4e33f9]
2016-02-19 14:51:04.181  INFO 5080 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration$LazyEndpointPathRequestMatcher@7f2a96e1,[org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@3ae13235,org.springframework.security.web.context.SecurityContextPersistenceFilter@5f36bdc8,org.springframework.security.web.header.HeaderWriterFilter@658ee520,org.springframework.security.web.authentication.logout.LogoutFilter@1ce1dc64,org.springframework.security.web.authentication.www.BasicAuthenticationFilter@51a29584,org.springframework.security.web.savedrequest.RequestCacheAwareFilter@120723a8,org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@b2632d,org.springframework.security.web.authentication.AnonymousAuthenticationFilter@49cabfed,org.springframework.security.web.session.SessionManagementFilter@6c8e082f,org.springframework.security.web.access.ExceptionTranslationFilter@51f381ff,org.springframework.security.web.access.intercept.FilterSecurityInterceptor@3b3223fd]
2016-02-19 14:51:04.399  INFO 5080 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@46117566: startup date [Fri Feb 19 14:51:00 IST 2016]; root of context hierarchy
2016-02-19 14:51:04.471  INFO 5080 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String,java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-02-19 14:51:04.472  INFO 5080 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-02-19 14:51:04.506  INFO 5080 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-02-19 14:51:04.506  INFO 5080 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-02-19 14:51:04.549  INFO 5080 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-02-19 14:51:04.720  INFO 5080 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017],mode=SINGLE,requiredClusterType=UNKNOWN,serverSelectionTimeout='30000 ms',maxWaitQueueSize=500}
2016-02-19 14:51:04.844  INFO 5080 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1,serverValue:5}] to localhost:27017
2016-02-19 14:51:04.845  INFO 5080 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017,type=STANDALONE,state=CONNECTED,ok=true,version=ServerVersion{versionList=[3,2,1]},minWireVersion=0,maxWireVersion=4,maxDocumentSize=16777216,roundTripTimeNanos=565904}
2016-02-19 14:51:05.243  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/autoconfig || /autoconfig.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.244  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env/{name:.*}],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)
2016-02-19 14:51:05.244  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/env || /env.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.245  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/configprops || /configprops.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.247  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/metrics/{name:.*}],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2016-02-19 14:51:05.247  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/metrics || /metrics.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.250  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/mappings || /mappings.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.251  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/health || /health.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(java.security.Principal)
2016-02-19 14:51:05.251  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/trace || /trace.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.252  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/beans || /beans.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.252  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/info || /info.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.253  INFO 5080 --- [           main] o.s.b.a.e.mvc.EndpointHandlerMapping     : Mapped "{[/dump || /dump.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.377  INFO 5080 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-02-19 14:51:05.391  INFO 5080 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2016-02-19 14:51:05.561  INFO 5080 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-02-19 14:51:05.567  INFO 5080 --- [           main] app.Application                          : Started Application in 5.207 seconds (JVM running for 11.036)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-