当前位置: 首页 > 知识库问答 >
问题:

从TomcatServerConf切换到springboot后,请求方法“POST”不受支持

盖雪峰
2023-03-14

最初,我用IntelliJ Idea Tomcat本地服务器配置(一切都起作用了)启动了项目,但决定使用spring boot应用程序。我添加了main类,更改了pom.xml(删除spring-context并添加spring-boot-starter-parent、spring-boot、spring-boot-starter-tomcat、spring-boot-starter-web、spring-boot-autocigure)。帮帮我吧!!!谢谢!

main.class

@SpringBootApplication(scanBasePackageClasses = {SpringConfig.class})
    public class Main extends SpringBootServletInitializer {
        public static void main(String[] args) {
            SpringApplication.run(Main.class, args);
        }
    }

pom.xml到springboot

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.3</version>
    <relativePath/>
  </parent>

  <dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot</artifactId>
      <version>2.4.3</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>2.4.3</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <version>2.4.3</version>
    </dependency>

    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
  </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
      <version>3.0.11.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
      <version>4.4</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

主配置类

@Configuration
@ComponentScan("ru")
@PropertySource("classpath:application.properties")
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    private final ApplicationContext applicationContext;

    @Autowired
    public SpringConfig(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }


    /*
     *  Dispatcher configuration for serving static resources
     */
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        WebMvcConfigurer.super.addResourceHandlers(registry);
        registry.addResourceHandler("/images/**").addResourceLocations("/images/");
        registry.addResourceHandler("/webjars/bootstrap/4.6.0/css/**").addResourceLocations("/webjars/bootstrap/4.6.0/css/bootstrap.min.css");
        registry.addResourceHandler("assets/select2-develop/**").addResourceLocations("/assets/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
    }

    /*
     *  Message externalization/internationalization
     */
    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("Messages");
        return messageSource;
    }

    @Bean
    public SpringResourceTemplateResolver templateResolver(){
        // SpringResourceTemplateResolver automatically integrates with Spring's own
        // resource resolution infrastructure, which is highly recommended.
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(this.applicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        // HTML is the default value, added here for the sake of clarity.
        templateResolver.setTemplateMode(TemplateMode.HTML);
        // Template cache is true by default. Set to false if you want
        // templates to be automatically updated when modified.
        templateResolver.setCacheable(true);
        return templateResolver;
    }


    @Bean
    public SpringTemplateEngine templateEngine(){
        // SpringTemplateEngine automatically applies SpringStandardDialect and
        // enables Spring's own MessageSource message resolution mechanisms.
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        // Enabling the SpringEL compiler with Spring 4.2.4 or newer can
        // speed up execution in most scenarios, but might be incompatible
        // with specific cases when expressions in one template are reused
        // across different data types, so this flag is "false" by default
        // for safer backwards compatibility.
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        registry.viewResolver(resolver);
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();

        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres");
        dataSource.setUsername("over");
//      dataSource.setPassword("postgres");     Можно установить пароль для базы данных.
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }

}

DispatcherSerlvet配置

public class MySpringMvcDispatcherSerlvetIntitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }


    /* Класс знает теперь где находится spring конфигурация */

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    /* Все http запросы от пользователя посылаем на dispatcher servlet  */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    public void onStartup(ServletContext aServletContext) throws ServletException {
        super.onStartup(aServletContext);
        registerCharacterEncodingFilter(aServletContext);
        registerHiddenFieldFilter(aServletContext);
    }

    private void registerHiddenFieldFilter(ServletContext aContext) {
        aContext.addFilter("hiddenHttpMethodFilter",
                new HiddenHttpMethodFilter()).addMappingForUrlPatterns(null ,true, "/*");
    }

    private void registerCharacterEncodingFilter(ServletContext aContext) {
        EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);

        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        FilterRegistration.Dynamic characterEncoding = aContext.addFilter("characterEncoding", characterEncodingFilter);
        characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
    }
}

这是我的感受:

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.logException - Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]

控制器

@RequestMapping("/categories")
@Controller
public class CategoriesController {
    private CategoriesDao categoriesDAO;

    @Autowired
    public void setCategoriesDAO(CategoriesDao categoriesDAO)
    {
        this.categoriesDAO = categoriesDAO;
    }

    @GetMapping
    public  String index(Model model) {
        model.addAttribute("category", new Category());
        model.addAttribute("categories", categoriesDAO.index());
        return "categories/index";
    }

    @PostMapping
    public String addCategory(@ModelAttribute("category") @Valid Category category,
                              BindingResult bindingResult, Model model) {
        if(bindingResult.hasErrors()) {
            model.addAttribute("categories", categoriesDAO.index());
            return "categories/index";
        }
        categoriesDAO.addCategory(category);
        return "redirect:categories";
    }

    @DeleteMapping("/{id}")
    public String deleteCategory(@PathVariable("id") int id) {
        categoriesDAO.deleteCategory(id);
        return "redirect:/categories";
    }

    @GetMapping("/{id}/edit")
    public String editCategory(Model model, @PathVariable("id") int id) {
        model.addAttribute("editCategory", categoriesDAO.editCategory(id));
        return "categories/edit";
    }

    @PatchMapping("/{id}")
    public String updateCategory(@ModelAttribute("editCategory") Category updateCategory,
                                 @PathVariable("id") int id) {
        categoriesDAO.updateCategory(id, updateCategory);
        return "redirect:{id}/edit";
    }
}

共有1个答案

阳修永
2023-03-14

要在main类中实现configure方法,可以执行以下操作:

@SpringBootApplication
public class Main extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(
      SpringApplicationBuilder builder) {
        return builder.sources(Main.class);
    }
}

我认为这些依赖应该就足够了(假设你使用的是Thymeleaf):

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.3</version>
    <relativePath/>
</parent>

<dependencies>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
      <version>2.4.3</version>
    </dependency>

    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
      <version>3.0.11.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-collections4</artifactId>
      <version>4.4</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
 类似资料:
  • 我刚刚开始学习Java Spring Boot for REST API开发。在下面的代码中,GET方法可以正常工作,但POST不能。 在Postman应用程序中使用as 错误 在日志中我可以看到, maven的Java和springboot版本,

  • 我正在使用一个表单,当我点击提交时,它会点击下面的控制器。 我知道这个方法被击中了,因为我在其中放置了断点。然而,我仍然得到了上面提到的错误。 编辑:我已经发布了整个控制器,而不仅仅是方法。 Edit2:我的html表单如下: 我错过了什么?非常感谢任何帮助。

  • 我正在编写一个控制器来处理来自AJAX的帖子。我一直收到一个错误,那篇文章不受支持。我以前在尝试创建后控制器方法时从未遇到过以下错误,我希望有人能发现我在哪里搞砸了。 这是我为控制控制器中的帖子而编写的方法: 使用JQuery 1.10,这是请求它的Ajax调用: 我知道POST地址是正确的,因为将它转换成GET请求就可以了。此外,我还编写了其他POST请求,它们在同一个控制器类中也能正常工作。任

  • login.jsp 用户列表.jsp AppController.java 有2页:login.jsp-起始页,其中包括与登录和密码填充的形式-userlist.jsp结果列表“显示数据库中所有用户持久化”..首先显示登录页面,当我单击提交按钮时,我得到了这个错误:org . spring framework . web . servlet . pagenotfound-不支持请求方法“POST”

  • 下面是我的方法 当调用GET request时,它的工作很好,但是当我们调用POST request和request payload checkout_token=xxxx时,我得到以下错误 编辑 甚至我尝试删除所有参数,但仍然没有运气到目前为止。

  • 在我的项目中,我面临着一个非常奇怪的问题。它与使用spring反应式webclient bulider调用rest API有关。它在本地和prod上也可以正常工作,但在向同一个endpoint发出3或4个请求后,会异常地给出以下错误。“org.springframework.web.server.MethodNotAllowedException:405方法\u不允许“请求方法'T'不受支持”这是