如果我将一个对象传递给 jsp 页面,如何使用 setter 更新其字段并将其发送回来?
例如,如果我们有
public class Person {
private int age;
private String name;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
}
还有一个 Controller
@RequestMapping(value = "/updatePerson", method = RequestMethod.GET)
public String showPerson(Model model) {
Person person = new Person();
person.setAge(23);
person.setName("Jack");
model.addAttribute("person", person);
return "updatePerson";
}
还有一个jsp页面
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<form:form modelAttribute="person">
<form:input path="age"/>
<input type="submit"/>
</form:form>
如何让这个 JSP 页面发送修改后的 person 对象作为结果,而不是只有一个字段的新对象?
最佳答案
在 Controller 中添加一个处理表单提交的方法:
@RequestMapping(value = "/updatePerson", method = RequestMethod.POST)
public String alterPerson(@ModelAttribute Person person) {
// do stuff
}
注意更改:
-
POST
而不是GET
:提交表单默认使用POST
-请求。 -
@ModelAttribute
自动检索提交的数据并填写Person
对象与它
通过表格,您可以得到 name
但字段永远是空的。添加另一个<form:input path="name"/>
解决这个问题。
如果您不想让用户更改姓名,则 Person
对象可能根本不应该出现在你的模型中;但这取决于这些对象如何持久化。您可以使用像这样的单独对象:
public class PersonChangeRequest {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
并将其用作 @ModelAttribute
像这样:
@RequestMapping(value = "/updatePerson", method = RequestMethod.GET)
public String showPerson(Model model) {
PersonChangeRequest person = new PersonChangeRequest();
person.setAge(23);
model.addAttribute("person", person);
return "updatePerson";
}
@RequestMapping(value = "/updatePerson", method = RequestMethod.POST)
public String alterPerson(@ModelAttribute PersonChangeRequest personChangeRequest) {
Person person = findPersonToChange(personChangeRequest);
person.setAge(personChangeRequest.getAge());
}
关于java - 使用 JSP 表单更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33741674/