2017-07-03 86 views
0

您好我正在与春天MVC和百里香叶,我无法更新数据从我的控制器,因为我有以下代码。我面临的主要问题是我的put方法没有被调用。春天+百里香叶无法更新

@GetMapping("/{id}/edit") 
    public String editUser(@PathVariable("id") int id, Model model) { 
     logger.info("++++++++++++[edit User]\n\n" + userService.findById(id)); 
     model.addAttribute("user", userService.findById(id)); 
     return "user/edit"; 
    } 

    @PutMapping("/{id}/edit") 
    public String updateUser(@PathVariable("id") int id, @ModelAttribute("user") User user, Model model) { 
     logger.info("\n\n+++++++++++++++++inside Update"); 
     User toUpdate = userService.findById(user.getId()); 
     user.setUserName(user.getUserName() != null ? user.getUserName() : toUpdate.getUserName()); 
     user.setName(user.getName() != null ? user.getName() : toUpdate.getName()); 

     logger.info(user.toString()); 
     userService.updateUser(user); 
     model.addAttribute("user", userService.findById(user.getId())); 
     return "redirect:/user/" + id; 
    } 

和我的html页面

<form action="#" th:action="@{/user/__${user.id}__}" method="put" 
        th:object="${user}"> 
        <div class="form-group"> 
         <label for="txtUserName">User-name</label> <input 
          class="form-control" id="txtUserName" placeholder="User Name" 
          th:feild="${user.userName}" /> 
        </div> 
        <div class="form-group"> 
         <label for="txtName">First Name</label> <input 
          class="form-control" id="txtName" placeholder="Full Name" 
          th:feild="${user.name}" /> 
        </div> 
        <div class="form-group"> 
         <label for="calDob">Date of Birth</label> <input 
          class="form-control" id="calDob" placeholder="dd/MM/yyyy" /> 
        </div> 

        <button type="submit" th:method="put" class="btn btn-success">Update</button> 
        <a href="#" th:href="@{/user/__${user.id}__}" 
         class="btn btn-primary">Cancel</a> <a th:method="delete" 
         href="javascript:deleteUser('${user.id}');" class="btn btn-danger">Delete</a> 
       </form> 

任何帮助将是有益的感谢

回答

1

PUT不是method attibute的form标签的有效参数。请参阅HTML specification

有效的方法是GETPOST。由于它不是REST API,因此可以使用POST方法进行更新。

所以只要更新您的地图来源:

@PutMapping("/{id}/edit") 

@PostMapping("/{id}/edit") 

,并形成标签:

<form action="#" th:action="@{/user/__${user.id}__}/edit" method="post" th:object="${user}"> 
+1

想你的意思'日:object' – bphilipnyc

+0

@bphilipnyc你”再右一点,谢谢 – ledniov

+1

你还没有在表单中定义动作以“/编辑”结尾 – cralfaro