gpt4 book ai didi

java - Spring MVC 3 REST PUT 和 POST 用于更新和保存

转载 作者:行者123 更新时间:2023-12-04 05:17:07 25 4
gpt4 key购买 nike

我的 AccountController 中有一个方法,比如

 @RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT })
public String update(@ModelAttribute Account account) {
this.getAccountDao().save(account);
return "redirect:/users/account/";
}

我正在使用 org.springframework.web.filter.HiddenHttpMethodFilter ,所以我的 View 有一个隐藏的表单字段 -
<form:form method="POST" modelAttribute="account">
<input type="hidden" name="_method" value="PUT" />
....

现在我的问题是 Controller 如何知道何时创建新帐户或更新它,或者它如何知道请求是 POST 还是 PUT?对我来说,它看起来总是会被 PUT。

我只是不喜欢使用除了 GET 和 POST 之外的任何东西。 Controller 不需要关心它是否需要创建一个新的或更新它。如果表单有一个隐藏的帐户 id 字段,服务可以找出要调用的 DAO 方法。

编辑
如果这只是一个 PUT 请求,那么我需要为 POST 创建一个新的 jsp。不幸的是,这两个请求非常相似,因为它们需要提交几乎准确的数据,除了帐户 ID。我希望能够在 Controller 中使用相同的方法,并为 POST 和 PUT 使用相同的 jsp,并且取决于模型 - 帐户是保存还是更新。

最佳答案

Controller 不知道您是创建还是更新实体,它只知道 RequestMethod s 方法对其作出 react 。

您指定的隐藏字段和 HiddenHttpMethodFilter您正在使用,结果是 PUT作为 HTTP 方法,对您的 Controller 可见,因为过滤器会更改请求中的方法。 (根据 javadocs )。

结果,浏览器使用 POST将其数据传输到服务器,然后 Filter运行并将请求中的方法更改为 PUT ,所以对于后面的应用程序 Filter看起来请求是用 PUT 发送的.

我认为非常相似的代码没有问题,只需将相似的行为分解为另一种方法.. 例如:

@RequestMapping(method = { RequestMethod.POST})
public String update(@ModelAttribute Account account) {
// do POST specific things..

// and common operations
commonOperation();
}

@RequestMapping(method = { RequestMethod.PUT })
public String updateWithPut(@ModelAttribute Account account) {
// do PUT specific things...

// and common operations
commonOperation();
}

// code that put and post methods have in common
private void commonOperation() {
// a lot of common code
// that needs to be done
}

关于java - Spring MVC 3 REST PUT 和 POST 用于更新和保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14110967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com