java.lang.IllegalStateException:BindingResult和bean名称'newReward'的普通目标对象都不能作为请求属性使用

时间:2013-03-07 09:16:17

标签: spring spring-mvc

我是Spring MVC的新手,遵循“Spring in Action”一书,从头开始创建我自己的项目。尝试访问'reward.jsp'时,我收到以下异常:

  

java.lang.IllegalStateException:BindingResult和bean名称'reward'的普通目标对象都不可用作请求属性

我班级的内容:

reward.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>
<html>
<head>
<title>Rewards</title>
</head>
<body>
    <h1>Rewards module</h1>

<h2>Add reward</h2>
<sf:form action="add" method="post" modelAttribute="reward">
    Reward name:<sf:input path="name" />
    Point value:<sf:input path="pointValue" />
    <input type="submit" value="Add">
</sf:form>


<br />
<h2>Reward list</h2>
<table>
    <c:forEach var="reward" items="${rewardList}">
        <tr>
            <td>${reward.name}</td>
            <td>${reward.pointValue}</td>
            <td><a href="delete/${reward.id}">delete</a></td>
        </tr>
    </c:forEach>
</table>

删除表单输入时,它可以正常工作。

RewardController.java

@Controller
public class RewardController {

@Autowired
private RewardService rewardService;

@RequestMapping("/reward")
public String listRewards(Map<String, Object> model) {
    model.put("rewardList", rewardService.listReward());
    return "reward";
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addReward(@ModelAttribute("reward") Reward reward,
        BindingResult result) {

    rewardService.addReward(reward);
    return "redirect:/reward";
}

@RequestMapping("/delete/{rewardId}")
public String deleteContact(@PathVariable("rewardId") long rewardId) {
    rewardService.removeReward(rewardId);
    return "redirect:/reward";
}
}

1 个答案:

答案 0 :(得分:0)

更改listRewards方法,以便将表单支持对象添加到模型映射model.put("reward", new Reward())

@RequestMapping("/reward")
public String listRewards(Map<String, Object> model) {
    model.put("rewardList", rewardService.listReward());
    model.put("reward", new Reward())
    return "reward";
}