Tag: modelattribute

Spring Framework – 同一类型的多个ModelAttributes

我正在结帐页面,需要送货地址和帐单邮寄地址。 它与第三方库集成,这些库都实现了相同的类型:地址。 我需要做的是: @RequestMapping(method = RequestMethod.POST) @ResponseBody public Response createOrder( @ModelAttribute(“customer”) Customer customer, @ModelAttribute(“shipping”) Address shippingAddress, @ModelAttribute(“payment”) Payment paymentInformation, @ModelAttribute(“billing”) Address billingAddress ) { // Create the order } 我坚持如何将两个相同类型的独立模型发送到我的Spring应用程序,以使其工作。 我可以制作外观模型并将它们映射到控制器内部的真实模型,但如果我可以避免它,我宁愿不去那条路线。 编辑:更改模型属性名称以希望使问题区域更清晰。

SpringformsModelAttribute字段validation,以避免400 Bad Request Error

我有一个ArticleFormModel包含由普通html form发送的数据,由Spring使用@ModelAttribute注释注入,即 @RequestMapping(value=”edit”, method=RequestMethod.POST) public ModelAndView acceptEdit(@ModelAttribute ArticleFormModel model, HttpServletRequest request, BindingResult errors) { //irrelevant stuff } 在某些方面,一切都很完美。 问题是ArticleFormModel包含一个double字段( protected ,使用普通的setter设置)。 只要用户发送的数据是数字,一切正常。 当他们输入一个单词时,我得到的就是400 Bad Request Http Error 。 我已经为这个控制器注册了一个WebDataBinder @InitBinder protected void initBinder(WebDataBinder binder) throws ServletException { binder.setValidator(validator); } 其中validator是实现org.springframework.validation.Validator接口的自定义类的实例,但我不知道接下来该做什么。 我希望能够解析模型,获得有效的HTTP响应并在表单中显示错误消息。 调用initBinder()方法,我可以从中调用validator.validate() ,但它不会更改错误(对于错误的数据)。 我知道我可以使用setter来解析字符串,检查它是否为数字,如果没有,将该信息存储在变量中,然后在validation期间检索该变量,但这似乎太多了。 必须有一种更简单的方法来强制字段上的类型而不会出现错误。 此外,问题是数据绑定,而不是validation,所以我觉得它应该放在相应的代码层。 我也在考虑实现java.beans.PropertyEditor并调用binder.registerCustomEditor() ,但我缺乏可靠的知识源。 客户端validation(通过JavaScript检查数据是否为数字)是不可能的。 TL; DR: 如何在不获取400 Bad Request Http […]

使用Spring MVC进行动态表单和数据绑定

在我的Spring MVC应用程序中,我需要实现一个动态的问卷表单:我有N个问题,每个我有3个选项。 所以在我的页面中我会有这样的事情: | Question 1 | 1 | 2 | 3 | | Question 2 | 1 | 2 | 3 | | Question 3 | 1 | 2 | 3 | | … | 1 | 2 | 3 | | Question N | 1 | 2 | 3 | 问题存储在数据库中,对于选项,我将使用单选按钮。 我将使用forEach标记来创建动态行,但我不知道如何发布数据并在此场景中处理ModelAttribute绑定… 对于我的模型属性类,这可能是一个很好的结构? […]