即使域模型对象没有设置器,也可以将表单参数绑定到域模型对象。 只需添加带有@InitBinder方法的@ControllerAdvice类,即可通过initDirectFieldAccess()方法将应用程序配置为进行字段绑定
package boottests.controllers;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
@ControllerAdvice
class BindingControllerAdvice {
@InitBinder
void initBinder(WebDataBinder binder) {
binder.initDirectFieldAccess();
}
}
我的域模型如下所示:
package boottests;
public class Person {
private final String firstname;
private final String lastname;
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
@Override
public String toString() {
return firstname + " " + lastname;
}
}
这是我的控制器:
package boottests.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import boottests.Person;
@Controller @RequestMapping("/person")
class PersonController {
@GetMapping
String postForm(Person person) {
System.out.println("YYY " + person + " YYY");
return "/";
}
}
当然,我的表格在index.html上:
<form action="person" >
Lastname: <input type="text" name="lastname"/> <br/>
Firstname: <input type="text" name="firstname"/> <br/>
<input type="submit" value="Submit"/>
</form>
如果在Spring Boot上运行此命令,则会看到表单参数已正确绑定到域模型的字段。
翻译自: https://www.javacodegeeks.com/2019/10/spring-mvc-binding-w-o-setters.html

6736

被折叠的 条评论
为什么被折叠?



