如上所述,如何传递参数?我已成功将ID参数从我的应用程序中的上一页传递到包含表单的页面的URI。我想发布此表单的内容以及要保存到我的数据库的相同ID参数。
我在我的应用程序中使用Spring Security,我怀疑这可能是问题,因为我的表单的POST方法按预期工作,如果我不尝试传递ID参数(即将我的表单数据对象发送到Service类,然后成功将数据保存到数据库中)。但是,只要我添加了旨在传递ID参数的代码,我就会收到HTTP 405错误(“不支持请求方法'POST')。
我的页面的URI包含form = http://localhost:8080/acceptOffer?id=(idvalue)
形成:
<form autocomplete="off" action="#" th:action="@{/acceptOffer}"
th:object="${offer}" method="POST" class="form-horizontal"
role="form">
Note
<label th:if="${#fields.hasErrors('note')}" th:errors="*{note}"
class="validation-message"></label>
<input type="text" th:field="*{note}" placeholder="Type Here"
class="form-control" />
<button type="submit">Accept Offer</button>
</form>
控制器方法:
@RequestMapping(value={"/acceptOffer?id={id}"}, method = RequestMethod.POST)
public ModelAndView acceptOffer(@Valid Offer offer, @PathVariable String id, BindingResult bindingResult){
ModelAndView modelAndView = new ModelAndView();
offerService.setId(Integer.valueOf(id));
offerService.saveOffer(offer);
modelAndView.addObject("successMessage", "Your offer of acceptance has been received");
modelAndView.addObject("user", new User());
modelAndView.setViewName("acceptOffer");
return modelAndView;
}
如果您使用路径变量,则将控制器代码更改为
@RequestMapping(value={"/acceptOffer/{id}"}, method = RequestMethod.POST)
public ModelAndView acceptOffer(@Valid Offer offer, @PathVariable String id, BindingResult bindingResult){
ModelAndView modelAndView = new ModelAndView();
offerService.setId(Integer.valueOf(id));
offerService.saveOffer(offer);
modelAndView.addObject("successMessage", "Your offer of acceptance has been received");
modelAndView.addObject("user", new User());
modelAndView.setViewName("acceptOffer");
return modelAndView;
}
并称之为
我没有按原定的方式解决这个问题,但我通过以下方式解决了这个问题:
我不知道,但它有效...