Spring MVC处理表单填充和提交

时间:2011-12-13 14:55:54

标签: java spring model-view-controller

我有一个表单,我在控制器上使用handleRequest填充,返回一个新的ModelAndView,其中包含正确的表单和传递的模型。表单填充正确。

在同一个控制器上,我有一个onSubmit方法,它应该处理我创建的表单的提交。从未调用过。当我提交表单时,页面重新加载,就像我调用了handleRequest一样,没有任何反应。

Bean定义:

<bean name="/update-user.htm" class="com.leadx.web.usermaintenance.controllers.UpdateUserController" >
    <property name="sessionForm" value="true" />
    <property name="commandName" value="updateUserSelectCommand" />
    <property name="commandClass" value="com.leadx.web.usermaintenance.commands.UpdateUserSelectCommand" />
    <property name="formView" value="update_user" />
</bean>

控制器:

public class UpdateUserController extends SimpleFormController implements Controller  {

protected final Log logger = LogFactory.getLog(getClass());

@Autowired
private UserService userService;

@Override
public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
        IOException {

    final List<User> users = this.userService.retrieveAllUsers();

    final Map<String, Object> userMaintenanceModel = new HashMap<String, Object>();
    userMaintenanceModel.put("users", users);

    this.logger.info("Count of users: " + users.size());
    this.logger.info("Returning Update User view");

    return new ModelAndView("update_user", "userMaintenanceModel", userMaintenanceModel);
}

@Override
public ModelAndView onSubmit(final Object command) throws ServletException {

    final int userId = ((UpdateUserSelectCommand) command).getId();

    this.logger.info("Preparing to update user: " + userId);

    final User user = this.userService.retrieveUserById(userId);

    final Map<String, Object> userMaintenanceModel = new HashMap<String, Object>();
    userMaintenanceModel.put("user", user);

    return new ModelAndView("update_user_details", "userMaintenanceModel", userMaintenanceModel);
}

}

和JSP:

<%@ include file="/WEB-INF/jsp/include.jsp"%>

<html>
<head>
<title>User Maintenance :: Update User</title>
</head>
<body>
    <h1>Select a User to Update</h1>
    <form:form method="post" commandName="updateUserSelectCommand">
        <table class="form">
            <select>
                <c:forEach var="user" items="${userMaintenanceModel.users}">
                    <option value="${user.getId()}">${user.getUsername()}</option>
                </c:forEach>
            </select>
        </table>
        <br>
        <input type="submit" align="center" value="Submit">
    </form:form>
</body>
</html>

我对此非常感到难过,所以任何帮助都会非常感激,谢谢。

1 个答案:

答案 0 :(得分:1)

使用SimpleFormController时,您应该覆盖referenceData()方法以使用初始数据填充表单。您不应该覆盖handleRequest(),因为它处理GET和POST请求:

@Override
public Map referenceData(HttpServletRequest request) {
    final List<User> users = this.userService.retrieveAllUsers();
    final Map<String, Object> userMaintenanceModel = new HashMap<String, Object>();
    userMaintenanceModel.put("users", users);  
    return userMaintenanceModel;
}