gpt4 book ai didi

java - 基本的 Spring MVC 数据绑定(bind)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:09 26 4
gpt4 key购买 nike

我正在学习 Spring MVC,我到处寻找只做一个基本的 Controller 来查看数据绑定(bind),但我没有尝试过任何工作。我可以绑定(bind) View 回发到 Controller ,我可以在那里看到带有属性的 pojo,但是每当我尝试将该对象添加到模型时,我什么也得不到。这是我目前所拥有的:

Controller

@Controller
public class HomeController {

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {

model.addAttribute(new Person());
return "home";
}

@RequestMapping(value="/about", method=RequestMethod.POST)
public void about(Person person, Model model)
{
model.addAttribute("person", person);
}
}

我要绑定(bind)的类

public class Person {
private String _firstName;
private String _lastName;
private Date _Birthday;

//Set
public void setFirstName(String FirstName){this._firstName = FirstName; }
public void setLastName(String LastName){this._lastName= LastName; }
public void setBirthDate(Date BirthDate){ this._Birthday = BirthDate;}

//get
public String getFirstName(){return _firstName;}
public String getLastName(){return _lastName;}
public Date getBirthDate(){return _Birthday;}
}

View - Controller 到表单!工作

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<html>
</head>
<body>
FirstName: ${model.person.getFirstName}
LastName: ${model.person.getLastName}
</body>
</html>

我可以或需要做什么来让它绑定(bind)?

最佳答案

model 属性是您在这里缺少的东西。

@Controller
public class HomeController {

@ModelAttribute("person")
public Person getPerson(){
return new Person();
}

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
return "home";
}

@RequestMapping(value="/about", method=RequestMethod.POST)
public void about(@ModelAttribute("person") Person person, BindingResult result, Model model)
{
if( ! result.hasErrors() ){
// note I haven't compiled this code :)
}
}
}

想法是 @ModelAttribute 方法将在 GET 和 POST 上调用,在 GET 请求上它只会暴露给 View ,而在 POST 上它将用于绑定(bind)请求参数。

请注意,BindingResult 已传递给 POST 方法,因此您可以使用该命令执行某些操作。

关于java - 基本的 Spring MVC 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10198335/

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