我有一个模型对象Person
public class Person {
public String firstName;
public String lastName;
public String country;
public String sex;
private Integer age;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString(){
return firstName + " " + sex;
}
}
并在控制器i中填充以下方法
中的参考数据 countryList @ModelAttribute
public void populateCountryList(Model model){
System.out.println("inside populateCountryList");
Map<String,String> country = new LinkedHashMap<String,String>();
country.put("Select", "-----Select------");
country.put("US", "United Stated");
country.put("CHINA", "China");
country.put("SG", "Singapore");
country.put("MY", "Malaysia");
country.put("MY1", "India");
country.put("MY2", "UK");
country.put("MY3", "SA");
country.put("MY4", "Newzeland");
model.addAttribute("countryList", country);
}
还在另一个方法中填充了 Person 对象
@ModelAttribute
public Person populateModel(){
System.out.println("inside populateCountry");
Person person = new Person();
person.setCountry("India");
person.setSex("M");
return person;
}
现在在jsp中我的组件是firstName,age,乡村下拉和性别单选按钮的文本框。我想要性别(M)的单选按钮,在下拉列表中默认选择国家“India”。我的jsp在下面。
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
...
<h1>Person page</h1>
<p>This is Person page</p>
<form:form method="POST" commandName="person" action="process-person.html">
<table>
<tbody><tr>
<td><form:label path="firstName">Name:</form:label></td>
<td><form:input path="firstName"></form:input></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age"></form:input></td>
</tr>
<tr>
<td><form:label path="country">Country:</form:label></td>
<td>
<form:select path="country">
<form:options items="${countryList}" />
</form:select>
</td>
</tr>
<tr>
<td>Sex :</td>
<td><form:radiobutton path="sex" value="M" />Male
<form:radiobutton path="sex" value="F" />Female
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit">
</td>
<td></td>
<td></td>
</tr>
</tbody></table>
</form:form>
当我运行应用程序时,未选择默认值。我还尝试在jsp中打印Person对象,它正在打印Person对象的属性值为null。
请告诉我这个实施中有什么问题。
解 在处理程序方法中,我编写了以下代码。
**@RequestMapping(value="/person-form")
public ModelAndView personPage() {
return new ModelAndView("person-page", "person", new Person());
}**
所以我已将代码更改为
**@RequestMapping(value="/person-form")
public ModelAndView personPage() {
return new ModelAndView("person-page");
}**
答案 0 :(得分:0)
这是因为您需要在人物对象中设置KEY而不是Value:
person.setCountry("MY1");