我看过一些与此相关的帖子。但是,我似乎看到了一些我不理解的东西。以下是我的代码的一部分:
package com.mvctest;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.dao.User;
@Controller
public class LoginController {
@RequestMapping("/newAccount")
public String createAccountScreen (Model model) {
model.addAttribute("user", new User());
return "createaccountscreen";
}
@RequestMapping(value="/createAccount", method=RequestMethod.POST)
public String createAccount (@Valid User user, BindingResult result) {
if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
for(ObjectError error : errors) {
System.out.println(error.getDefaultMessage());
}
return "createaccountscreen";
}
return "accountcreated";
}
然后在我的jsp文件createaccountscreen.jsp中我有以下内容:
<sf:form method="post"
action="${pageContext.request.contextPath}/createAccount"
commandName="user">
这很好用。
但是,如果我将addAttribute()调用更改为以下
model.addAttribute("myuser", new User());
并将jsp中的commandName更改为
<sf:form method="post"
action="${pageContext.request.contextPath}/createAccount"
commandName="myuser">
我收到以下错误
java.lang.IllegalStateException:BindingResult和bean名称'myuser'的普通目标对象都不可用作请求属性
基本上,我将'user'替换为'myuser'。
Bean类是'User'。这是否意味着commandName需要是'user'?