我正在创建一个简单的培训项目。我已经实现了一个 Controller 方法,它从列表中删除一个项目。该方法如下所示:
@Controller
@RequestMapping(value = "/topic")
public class TopicController {
@Autowired
private TopicService service;
...
@RequestMapping(value = "/deleteComment/{commentId}", method = RequestMethod.POST)
public String deleteComment(@PathVariable int commentId, BindingResult result, Model model){
Comment deletedComment = commentService.findCommentByID(commentId);
if (deletedComment != null) {
commentService.deleteComment(deletedComment);
}
return "refresh:";
}
}
此方法是从按钮标签调用的,按钮标签的查找方式如下:
<form><button formaction = "../deleteComment/1" formmethod = "post">delete</button></form>
在我的项目中,表单标签看起来像一个可点击的按钮。但有一个严重的问题: Controller 的方法永远不会被触发。如何使用按钮标签触发它?
附注该调用是从 URI http://localhost:8080/simpleblog/topic/details/2 的页面执行的, Controller 的 URI 是 http://localhost:8080/simpleblog/topic/deleteComment/2
更新:
我创建了超链接“删除”,单击该链接应删除评论,但我收到了异常
java.lang.IllegalStateException: Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature!
这是真的:我的 Controller 方法中确实没有 @ModelAttribute ,位于 BindingResult 参数之前。但我不知道应该是哪种类型?
最佳答案
<form>
的method
属性是GET
默认情况下。我不知道你想用 formmethod
做什么?和formaction
属性,但默认为 HTML它们毫无意义。
您必须尝试以下操作:
<form action="../deleteComment/1" method="post">
<button>delete</button>
</form>
编辑:
您在方法中声明了一些未使用的参数。 BindingResult 必须与 @Valid
一起使用带注释的属性(搜索 @Valid
here 查看一些示例),但这不是您的情况。所以,请尝试:
@RequestMapping(value = "/deleteComment/{commentId}", method = RequestMethod.POST)
public String deleteComment(@PathVariable int commentId){
...
}
关于java - 从数据库中删除记录的 Controller 方法应采用哪些参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12253836/