目前我正在进入Spring,到目前为止,一切都在工作,除了表格。当表单被提交时,Controller中的映射函数被调用,但值始终为null。我希望你知道如何解决这个错误。我使用的是Spring 3.1.2
控制器类:
@Controller
public class MyController{
@RequestMapping(value="/registerSave.html", method=RequestMethod.POST)
public ModelAndView registerSave(@ModelAttribute("UserInput") UserInput a) {
Logger log = LoggerFactory.getLogger(MeinController.class);
log.info("username: " + a.getUsername()); //a.getUserName() is null >.<
ModelAndView mav= new ModelAndView();
User registerUser= new User(a.getUsername(), securityService.encodePassword(a.getPassword()), a.getFullname(), a.getEmail());
try{
messageService.createUser(registerUser);
mav.setViewName("registerSuccess");
} catch(Exception exception) {
log.info("cannot create user "+ a.getUsername()+ " : "+ exception.getMessage());
mav.setViewName("registerFail");
}
return mav;
}
}
Jsp:
<!DOCTYPE HTML>
<html>
<body >
<article>
<section>
<form method="post" action="registerSave.html" modelAttribute="UserInput">
<section>E-Mail Adresse:<br>
<input id="email" autofocus="autofocus" size="35" type="text" required="required" name="email" maxlength="30"/>
</section>
<section>Username:<br>
<input size="35" type="text" required="required" name="email" maxlength="30"/>
</section>
<section>Password:<br>
<input size="35" required="required" type="password" name="passwort"/>
</section>
<section class="right">Password:<br>
<input id="inPw2" title="Password$Bitte geben sie hier das selbe Passwort ein, wie im ersten Feld$Dies dient der überprüfung, für den Fall, dass sie sich vertippt haben" size="35" required="required" type="password" name="passwort"/>
</section>
<section >Your full name:<br>
<input id="fullname" size="35" type="text" required="required" name="email" maxlength="30"/>
</section>
<p>
<input size="35" type="submit" value="Regestieren"/>
</p>
</form>
</section>
</article>
</body>
</html>
类UserInput:
public class UserInput {
private String username;
private String password;
private String fullname;
private String email;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
答案 0 :(得分:3)
好像你的用户名输入元素有name = email。用户名表单中没有输入框。除此之外的一切都是正确的,应该可行。
答案 1 :(得分:1)
请将ModelAttribute
添加到表单
<form method="post" action="registerSave.html" modelAttribute="UserInput">
我认为这是因为我们没有在GET请求中设置Command值。发布请求时,将创建一个新的命令对象。 尝试将此方法添加到控制器类,看看是否解决..
@RequestMapping(value="/registerSave.html", method=RequestMethod.GET)
public ModelAndView registerGet() {
ModelAndView mav = new ModelAndView();
UserInput userInput = new UserInput;
mav.addObject("UserInput", userInput);
mav.setViewName("registerSave.html");
return mav;
}