【发布时间】:2020-10-02 18:44:50
【问题描述】:
我有以下呈现 HTML 视图的控制器。在这个控制器内部,我定义了一个 model.attribute("bill", bill); ,它在视图上呈现 0 的默认值。控制器如下所示:
@RequestMapping(value = "/products", method = RequestMethod.GET)
public String index(Model model, Product product) {
//not relevant code above
String bill = "0";
model.addAttribute("bill", bill);
我有另一个不同类的控制器,我想更新 bill 的值并将我重定向到同一页面。我实现这一目标的尝试最终产生了这个:
@RequestMapping(value="/products/checkout", method = RequestMethod.POST)
public String getBill(@RequestParam("checkout") String order, @RequestParam("bill") String bill, @ModelAttribute Model model) {
String finalBill = "124pounds";
model.addAttribute("bill", finalBill);
视图看起来像这样:
<form th:action="@{/products/checkout}" method="post">
<h3> Please type your order:</h3>
<input type="text" th:name= "checkout" id="checkout" placeholder="banana,apple,tomato (separated with commas)">
<input type="submit" value="Checkout">
<h3>Your bill is :<span th:name="bill" th:text="' '+${bill}+' c'"></span></h3>
</form>
我想要实现的是让名为getBill() 的第二个控制器更新bill 的值并重定向到同一页面。我有点迷失了,我不确定如何实现所需的功能。
注意: String bill = "0"; 和 String finalBill = "124pounds"; 只是用来测试按下Checkout按钮时值是否发生变化。 strong> 我得到的错误是这样的。
There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'bill' is not present
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'bill' is not present
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:204)
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:114)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
现在会显示默认的0 值,但是当我单击Checkout 时出现上述错误。基本上我想从getBill() 更新值并返回相同的视图,我不确定这是否可能?!
【问题讨论】:
-
在您的 HTML 中,没有带有名称 bill 的输入,因此它不会被发送到您的控制器。这就是你得到错误的原因。我建议创建一个表单类并在表单中使用 th:object + th:field。
-
我实际上修复了它,但现在我收到了
No primary or default constructor found for interface org.springframework.ui.Model。您知道如何将纯字符串发送到我的视图吗?
标签: html spring spring-boot spring-mvc thymeleaf