非html 方法Spring MVC

Non-html methods Spring MVC

有一个 Spring MVC 应用程序。我需要跟踪 Put、Patch 和 Delete 表单方法。我使用 java 配置,所以有那个文件而不是 web.xml:

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

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

   @Override
   protected String[] getServletMappings() {
       return new String[]{"/"};
   }

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

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

最后一个方法注册了HiddenHttpMethodFilter。 那么问题出在哪里呢?有 2 页:index.html 和 show.hmtl。当 URL 为“/files”时显示第一页。当 URL 为“/files/{id}”时显示第二页。非 html 方法在第一页上运行完美,但在第二页上绝对不起作用。 控制器:

@Controller
@RequestMapping("/files")
public class FilesController {

    ...

    //works
    @DeleteMapping() 
    public String delete(@RequestParam("id") int id){
        ...
        return "redirect:/files";
    }

    //works
    @PatchMapping()
    public String copy(@RequestParam("id") int id){
        ...
        return "redirect:/files";
    }

    @PostMapping()
    public String uploadFile(@RequestParam("file") MultipartFile file,Model model) {
        ...
        return "redirect:/files";
    }

    @GetMapping("/{id}")
    public String show(@PathVariable("id") int id, Model model){
        ...
        return "show";
    }

    //doesn't work. 405 error. Method not allowed. App maps it like POST method
    @PutMapping("/{id}")
    public String rewrite(@PathVariable("id") int id, @RequestParam("file") MultipartFile file, Model model){
        ...
        return "redirect:/files/"+id;
    }
}

show.html:

<form th:action="@{/files/{x}(x=${file.getId()})}" th:method="Put" enctype="multipart/form-data">
            ...
            <input type="submit" value="Download">
</form>

如何为多个 URL 添加方法映射?

我知道出了什么问题。 enctype="multipart/form-data" 仅允许 POST 方法,因此 HiddenHttpMethodFilter 忽略了 PUT 方法。要修复它,您可以删除此表单 属性 并将映射方法参数从 @RequestParam("file") MultipartFile file 更改为 @RequestParam("file") File file