Spring Boot 实战(10) 解决SpringBoot中 put 和 delete 提交不生效的问题

写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。

这博客是对自己学习的一点点总结及记录,如果您对 Java算法 感兴趣,可以关注我的动态,我们一起学习。

用知识改变命运,让我们的家人过上更好的生活

相关文章:

Springboot 系列文章


controller 层使用 restful 风格,修改用 PUT 方法,删除用 DELETE 方法

 /**
     * 员工修改
     *
     * @param employee
     * @return
     */
    @PutMapping("/emp")
    public String updateEmployee(Employee employee) {
        System.out.println("修改的员工数据:" + employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 员工删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/emp/{id}")
    public ModelAndView deleteEmployee(@PathVariable("id") Integer id) {
        ModelAndView mv = new ModelAndView("redirect:/emps");
        employeeDao.delete(id);

        return mv;
    }

由于浏览器只能发送GET和POST请求,为了使得 PUT和 DELETE 提交生效,在前端html页面的 form 表单中添加 hidden

<form th:action="@{/emp}" method="post">
	<input type="hidden" name="_method" value="put" />

为了使表单可以发送PUT、DELETE等请求,需要开启mvc的HiddenHttpMethodFilter

application.properties

# 开启mvc的HiddenHttpMethodFilter,以便可以表单可以发送PUT、DELETE等请求
spring.mvc.hiddenmethod.filter.enabled=true

由于水平有限,本博客难免有不足,恳请各位大佬不吝赐教!

你可能感兴趣的:(Spring,Boot)