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

写在前面:最近利用晚上的时间在网上看视频学习Spring Boot,这博客是对学习的一点点总结及记录,技术是开源的、知识是共享的
如果你对Spring Boot 感兴趣,可以关注我的动态,我们一起学习。用知识改变命运,让家人过上更好的生活

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
发布了73 篇原创文章 · 获赞 795 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43570367/article/details/103751142