问题
I can't understand what I am doing wrong. I have a controller:
@Controller
@RequestMapping(value = "/index.htm")
public class LoginController {
@Autowired
private AccountService accountService;
@RequestMapping(method = RequestMethod.GET)
public String showForm(Map model) {
model.put("index", new LoginForm());
return "index";
}
@ModelAttribute("index")
public LoginForm getLoginForm() {
return new LoginForm();
}
@RequestMapping(method = RequestMethod.POST)
public String processForm(LoginForm loginForm, BindingResult result,
Map model) {
if (result.hasErrors()) {
HashMap<String, String> errors = new HashMap<String, String>();
for (FieldError error : result.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
model.put("errors", errors);
return "index";
}
List<Account> accounts = accountService.findAll();
loginForm = (LoginForm) model.get("loginForm");
model.put("index", loginForm);
return "loginsuccess";
}
}
And Spring html form:
<form:form action="index.htm" commandName="index">
<table cellspacing="10">
<tr>
<td>
<form:label path="username">
<spring:message code="main.login.username"/>
</form:label>
</td>
<td>
<form:input path="username" cssClass="textField"/>
</td>
</tr>
<tr>
<td>
<form:label path="password">
<spring:message code="main.login.password"/>
</form:label>
</td>
<td>
<form:password path="password" cssClass="textField"/>
</td>
</tr>
<tr>
<td>
<input type="submit" class="button" value="Login"/>
</td>
</tr>
</table>
</form:form>
When I try to access URL: http://localhost:8080/webclient/index.htm
I keep getting this exception:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'index' available as request attribute
What is wrong with my controller and why I keep getting an exception like that?
回答1:
I would make the following changes. First your GET method should be something like:
@RequestMapping(method = RequestMethod.GET)
public String showForm(@ModelAttribute("index") LoginForm loginForm) {
return "index";
}
Using the @ModelAttribute annotation will automatically put "index" into the model for the request.
And your POST method declaration should be something like:
@RequestMapping(method = RequestMethod.POST)
public String processForm(@ModelAttribute("index") LoginForm loginForm,
BindingResult result, Map model) {
Finally, and probably the real issue, change the controller class's @RequestMapping annotation to:
@RequestMapping(value = "/index")
The ".htm" that you have is redundant. You've already configured web.xml and your Spring config to respond to ".htm" requests.
来源:https://stackoverflow.com/questions/12585790/keep-getting-neither-bindingresult-nor-plain-target-object-for-bean-name-index