[英]Non-html methods Spring MVC
There is a Spring MVC app.有一个 Spring MVC 应用程序。 I need to track Put, Patch and Delete form methods.
我需要跟踪 Put、Patch 和 Delete 表单方法。 I use java configuration, so there is that file instead of web.xml:
我使用 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, "/*");
}
}
Last method registers HiddenHttpMethodFilter.最后一个方法注册了 HiddenHttpMethodFilter。 So where is the problem?
那么问题出在哪里? There are 2 pages: index.html and show.hmtl.
有 2 页:index.html 和 show.hmtl。 First page is shown when URL is "/files".
当 URL 为“/files”时显示第一页。 Second page is shown when URL is "/files/{id}".
当 URL 为“/files/{id}”时显示第二页。 Non-html methods work perfect on the first page, but absolutely don't work on the second one.
非 html 方法在第一页上工作得很好,但绝对不能在第二个页面上工作。 Controller:
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:显示.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?如何为多个 URL 添加方法映射?
I figured out what's wrong.我知道出了什么问题。
enctype="multipart/form-data"
allows only POST method so HiddenHttpMethodFilter ignored PUT method. enctype="multipart/form-data"
只允许 POST 方法,因此 HiddenHttpMethodFilter 忽略了 PUT 方法。 To fix it you may remove this form property and change mapping method argument from @RequestParam("file") MultipartFile file
to @RequestParam("file") File file
要修复它,您可以删除此表单属性并将映射方法参数从
@RequestParam("file") MultipartFile file
更改为@RequestParam("file") File file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.