There is a Spring MVC app. I need to track Put, Patch and Delete form methods. I use java configuration, so there is that file instead of 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, "/*"); } }
Last method registers HiddenHttpMethodFilter. So where is the problem? There are 2 pages: index.html and show.hmtl. First page is shown when URL is “/files”. Second page is shown when URL is “/files/{id}”. Non-html methods work perfect on the first page, but absolutely don’t work on the second one. Controller:
@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>
How to add method mapping for multiple URLs?
Advertisement
Answer
I figured out what’s wrong. enctype="multipart/form-data"
allows only POST method so HiddenHttpMethodFilter ignored PUT method. To fix it you may remove this form property and change mapping method argument from @RequestParam("file") MultipartFile file
to @RequestParam("file") File file