我有一些简单的类Man,它包含构造函数,getter和setter
public class Man {
@Size(min = 3, max = 20, message = "Username must be between 3 and 20 characters long.")
@Pattern(regexp="^[a-zA-Z0-9]+$", message = "Username must be alphanumeric with no spaces")
private String name;
@Size(min = 1, max = 2, message = "Age must be between 1 and 2 characters long")
@Pattern(regexp = "^[0-9]+$", message = "Age must be numerical with no spaces")
private String age;
Man(){
}
Man(String name, String age){
super();
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public String getAge(){
return age;
}
public void setName(String name){
this.name = name;
}
public void setAge(String age){
this.age = age;
}
}
服务:
@Service
public class ManService {
Map<String, Man> people = new HashMap();
public void saveMan(Man man){
System.err.println(man); // after the form is submitted object is created
System.err.println(man.getName()); // but it name == null
System.err.println(man.getAge()); // and age == null
people.put(man.getName(), man);
}
}
通用控制器。 当转到/ user?new时,将创建对象Man()并插入到框架modelAttribute中,但是在提交表单之后,名称和年龄Man()对象的字段将等于null值。
@RequestMapping(value="/user", method = GET, params = "new")
public String outputParam(Model model){
model.addAttribute("box",new Man());
return "param";
}
@RequestMapping(value="/user", method = POST)
public String addFromForm(@Valid Man man, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
return "param";
}
manService.saveMan(man);
return "redirect:../list";
}
查看:
<sf:form method="POST" modelAttribute="box" enctype="multipart/form-data">
<fieldset>
<table cellspacing="0">
<tr>
<th><sf:label path="name">User name:</sf:label></th>
<td><sf:input path="name" size="15" /></td>
<sf:errors path="name" cssClass="error"/>
</tr>
<tr>
<th><sf:label path="age">Age:</sf:label></th>
<td><sf:input path="age" size="20" /></td>
<sf:errors path="name" cssClass="error"/>
</tr>
<input name="commit" type="submit" value="sent this shit" />
</table>
</fieldset>
</sf:form>
结果POST表单中没有绑定输入字段的值。
答案 0 :(得分:2)
尝试使用此
@RequestMapping(value="/user", method = POST)
public String addFromForm(@Valid @ModelAttribute("box") Man man, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
return "param";
}
manService.saveMan(man);
return "redirect:../list";
}
正如@M所建议的那样。 Deinum
在发出POST请求时,您必须对数据和请求进行编码。
HTML表单提供了三种编码方法。
如果您的表单中有一个文件,那么您必须使用multipart / form-data。
我不会想到你应该使用它的正常形式。而是使用application / x-www-form-urlencoded(默认情况下是)。