【问题标题】:Why Request method 'POST' is not supported in Java Spring v.2.2.7?为什么 Java Spring v.2.2.7 不支持请求方法“POST”?
【发布时间】:2020-09-04 16:00:46
【问题描述】:

我正在使用 Spring boot v.2.2.7 来实现 post http 方法的休息服务。从 Postman 可以正常工作,但在使用浏览器时显示下一个错误:

There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'POST' not supported

我的控制器:

@Controller
public class SystemAdministratorController {
    @Autowired
    private StyleRepository styleRepository;

    //Method get, post, put and delete for music styles
    @GetMapping("/musicalstyle")
    public String getStyle(Model model) {
        List<Style> listStyles = styleRepository.findAll();
        model.addAttribute("styles", listStyles);
        return "musicalStyle";
    }

    @PostMapping("/musicalstyle")
    public String addMusicalStyle(@Valid Style style) {
        styleRepository.save(style);
        return "template";
        }

注意:Get 方法工作正常。

我的仓库:

@Repository
public interface StyleRepository extends JpaRepository<Style, Long>{

}

我的模特:

@Entity
@Table(name = "style", schema = "musicnet")
public class Style {

    private String name;
    private String description;

    public Style() {

    }

    public Style(String name, String description) {
        this.name = name;
        this.description = description;
    }

    @Id
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "description", nullable = false)
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "SystemAdministrator [name=" + name + ", description=" + description + "]";
    }

我的网络配置:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();

    }

}

我的申请

@SpringBootApplication() 
@EnableJpaAuditing
public class MusicnetApplication {

    public static void main(String[] args) {
        SpringApplication.run(MusicnetApplication.class, args);


    }

}

addMusicalStyle.html(表单在哪里调用 post 方法):

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>


</head>
<body>

    <form th:action="@{/musicalstyle}" th:object="${style}" method="post">
        <label for="name">Nombre</label>
        <input type="text" th:field="*{name}"  />
        <label for="description">Descripción</label>
        <input type="text" th:field="*{description}" />
        <button type="submit" th:text="Añadir">Añadir</button>
    </form>


</body>
</html>

问题似乎出在百里香叶上。提交表单时 Spring 日志显示:

2020-05-18 20:07:45.793 DEBUG 9752 --- [nio-8182-exec-3] o.s.web.servlet.DispatcherServlet        : POST "/addMusicalStyle.html", parameters={}
2020-05-18 20:07:45.810 DEBUG 9752 --- [nio-8182-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler ["classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/", "/"]
2020-05-18 20:07:45.836  WARN 9752 --- [nio-8182-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
2020-05-18 20:07:45.837 DEBUG 9752 --- [nio-8182-exec-3] o.s.web.servlet.DispatcherServlet        : Completed 405 METHOD_NOT_ALLOWED
2020-05-18 20:07:45.846 DEBUG 9752 --- [nio-8182-exec-3] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for POST "/error", parameters={}
2020-05-18 20:07:45.854 DEBUG 9752 --- [nio-8182-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2020-05-18 20:07:46.408 DEBUG 9752 --- [nio-8182-exec-3] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2020-05-18 20:07:46.432 DEBUG 9752 --- [nio-8182-exec-3] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 405

我们可以看到使用的地方:POST "/addMusicalStyle.html", parameters={} 当它应该是这样的: POST "/musicstyle", parameters={name="Jazz", description="From EEUU"} 所以百里香没有做他的工作。

我的 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.musicnet</groupId>
    <artifactId>musicnet</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>musicnet</name>
    <description>MusicNet is Spring project to develop the TFG</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

就像 th:action、th:object 和 th:field 没有采用正确的参数(来自邮递员客户端的服务正常)。

我试过 Spring 版本 2.3.0、2.2.7 和 2.1.14,结果是一样的。

我该如何解决?

谢谢,

【问题讨论】:

  • 添加enctype='multipart/form-data'&lt;form th:action="@{/musicalstyle}" th:object="${style}" method="post"&gt;看看是否有效
  • 检查了 enctype='multipart/form-data' 还是不行...
  • 能否包含模板生成的 HTML 的 sn-p?
  • 尝试将@ModelAttribute 添加到您的@PostMapping 方法参数中:@ModelAttribute @Valid Style style
  • 您的代码没有加起来。您有一个 Style 类,其 id 类型与您的存储库不同。这一切都让我想知道这是实际代码还是一些看起来像真实代码的愚蠢版本。

标签: java html spring spring-boot thymeleaf


【解决方案1】:

我回复我:

为了让 Thymeleaf 处理这些文件,它们应该位于 /src/main/java/resources/templates 下,所以出现了问题。

【讨论】:

    【解决方案2】:

    你不认为应该将@RequestBody 与@PostMapping 一起使用

    @PostMapping("/musicalstyle")
        public String addMusicalStyle(@Valid @RequestBody Style style) {
            styleRepository.save(style);
            return "template";
            }
    

    【讨论】:

      【解决方案3】:

      我认为问题完全集中在百里香叶上。我像这样修改了 addMusicalStyle.html:

      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
      
      
      </head>
      <body>
      
          <form action="/musicalstyle" method="post">
              <label for="name">Nombre</label>
              <input type="text" name="name" />
              <label for="description">Descripción</label>
              <input type="text" name="description" />
              <button type="submit">Añadir</button>
          </form>
      
      
      </body>
      </html>
      

      并且模板作为正常返回,因此第 th 字段有问题。

      另外,我可以在 Eclipse 菜单 Navigate -> Open type... -> Find Thymeleaf 上看到 thymeleaf 类

      【讨论】:

        猜你喜欢
        • 2016-08-28
        • 2016-09-13
        • 1970-01-01
        • 2018-07-24
        • 2018-06-03
        • 2015-05-28
        • 2014-06-10
        • 2020-03-31
        相关资源
        最近更新 更多