Spring MVC: форма не отправляется - PullRequest
1 голос
/ 24 июля 2011

В моем приложении Spring MVC контроллер форм правильно подключен и отображает форму в соответствии с назначением.

Но кнопка «Отправить» не работает.Более того, метод onSubmit () FormController никогда не вызывается, потому что мои отладочные операторы печати не отображаются.

Вместо этого, когда я нажимаю Submit, форма перезагружается и некоторые поля изменяются (оченьстранное поведение).

Я реализовал свой FormController как обычно в Spring MVC:

public class RegisterController extends SimpleFormController {

    public RegisterController()
    {
        setCommandClass(Customer.class);
        setCommandName("customer");
    }

    @Override
    protected ModelAndView onSubmit(Object command) throws Exception {
        // never gets run!
        Customer customer = (Customer) command;
        System.out.println("TEST. Obtained Customer object: " + customer.toString());
    }
}

Моя схема bean для сервлета Dispatcher:

<bean name="/register.htm" class="techbooks.web.RegisterController"
    p:formView="register" p:successView="home"/>

"register"ссылается на register.htm (.jsp) и home на home.htm (.jsp), оба из которых существуют.

JSP:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>

<head>
<meta http-equiv="Content-Language" content="en-us" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TechBooks.com</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
</head>

<body>

<center>

<table style="width: 850px" class="style2">
<form:form method="POST" commandName="customer">
    <tr>
    <td><h1>Register New Customer</h1></td>
    </tr>

    <tr>
        <td>
            <table>
                <tr>
                    <td align="left">Customer ID:</td>
                    <td align="left"><form:input path="customerId"/></td>
                </tr>
                <tr>
                    <td align="left">Customer Password:</td>
                    <td align="left"><form:password path="customerPassword"/></td>
                </tr>
                <tr>
                    <td align="left">Customer First Name:</td>
                    <td align="left"><form:input path="customerFirstName"/></td>
                </tr>
                <tr>
                    <td align="left">Customer Last Name:</td>
                    <td align="left"><form:input path="customerLastName"/></td>
                </tr>
                <tr>
                    <td align="left">Customer Address:</td>
                    <td align="left"><form:input path="customerAddress"/></td>
                </tr>
                <tr>
                    <td align="left">Customer City:</td>
                    <td align="left"><form:input path="customerCity"/></td>
                </tr>
                <tr>
                    <td align="left">Customer State:</td>
                    <td align="left"><form:input path="customerState"/></td>
                </tr>
                <tr>
                    <td align="left">Customer Zip Code:</td>
                    <td align="left"><form:input path="customerZipCode"/></td>
                </tr>
                <tr>
                    <td align="left">Customer Email Address:</td>
                    <td align="left"><form:input path="customerEmailAddress"/></td>
                </tr>
                <tr>
                    <td align="left">Date Added:</td>
                    <td align="left"><form:input path="customerDateAdded" /></td>
                </tr>
                <tr>
                    <td align="left">Is Admin?</td>
                    <td align="left"><form:checkbox path="customerIsAdmin"/></td>
                </tr>
                <tr>
                    <td align="left"><input type="submit" value="Register"/><br/><input type="button" value="Cancel"/>
                    </td>
                    <td align="left">&nbsp;</td>
                </tr>
            </table>

        </td>
    </tr>

</form:form>
</table>


</center>

</body>

</html>

Класс bean-объекта клиента:

package techbooks.model;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class Customer implements Serializable {

    @Id
    private String customerId;
    private String customerPassword;
    private String customerFirstName;
    private String customerLastName;
    private String customerAddress;
    private String customerCity;
    private String customerState;
    private String customerZipCode;
    private String customerEmailAddress;
    private Date customerDateAdded;
    private Boolean customerIsAdmin;

    /**
     * @return the customerId
     */
    public String getCustomerId() {
        return customerId;
    }

    /**
     * @param customerId the customerId to set
     */
    public void setCustomerId(String customerId) {
        this.customerId = customerId;
    }

    /**
     * @return the customerPassword
     */
    public String getCustomerPassword() {
        return customerPassword;
    }

    /**
     * @param customerPassword the customerPassword to set
     */
    public void setCustomerPassword(String customerPassword) {
        this.customerPassword = customerPassword;
    }

    /**
     * @return the customerFirstName
     */
    public String getCustomerFirstName() {
        return customerFirstName;
    }

    /**
     * @param customerFirstName the customerFirstName to set
     */
    public void setCustomerFirstName(String customerFirstName) {
        this.customerFirstName = customerFirstName;
    }

    /**
     * @return the customerLastName
     */
    public String getCustomerLastName() {
        return customerLastName;
    }

    /**
     * @param customerLastName the customerLastName to set
     */
    public void setCustomerLastName(String customerLastName) {
        this.customerLastName = customerLastName;
    }

    /**
     * @return the customerAddress
     */
    public String getCustomerAddress() {
        return customerAddress;
    }

    /**
     * @param customerAddress the customerAddress to set
     */
    public void setCustomerAddress(String customerAddress) {
        this.customerAddress = customerAddress;
    }

    /**
     * @return the customerCity
     */
    public String getCustomerCity() {
        return customerCity;
    }

    /**
     * @param customerCity the customerCity to set
     */
    public void setCustomerCity(String customerCity) {
        this.customerCity = customerCity;
    }

    /**
     * @return the customerState
     */
    public String getCustomerState() {
        return customerState;
    }

    /**
     * @param customerState the customerState to set
     */
    public void setCustomerState(String customerState) {
        this.customerState = customerState;
    }

    /**
     * @return the customerZipCode
     */
    public String getCustomerZipCode() {
        return customerZipCode;
    }

    /**
     * @param customerZipCode the customerZipCode to set
     */
    public void setCustomerZipCode(String customerZipCode) {
        this.customerZipCode = customerZipCode;
    }

    /**
     * @return the customerEmailAddress
     */
    public String getCustomerEmailAddress() {
        return customerEmailAddress;
    }

    /**
     * @param customerEmailAddress the customerEmailAddress to set
     */
    public void setCustomerEmailAddress(String customerEmailAddress) {
        this.customerEmailAddress = customerEmailAddress;
    }

    /**
     * @return the customerDateAdded
     */
    public Date getCustomerDateAdded() {
        return customerDateAdded;
    }

    /**
     * @param customerDateAdded the customerDateAdded to set
     */
    public void setCustomerDateAdded(Date customerDateAdded) {
        this.customerDateAdded = customerDateAdded;
    }

    /**
     * @return the customerIsAdmin
     */
    public Boolean getCustomerIsAdmin() {
        return customerIsAdmin;
    }

    /**
     * @param customerIsAdmin the customerIsAdmin to set
     */
    public void setCustomerIsAdmin(Boolean customerIsAdmin) {
        this.customerIsAdmin = customerIsAdmin;
    }
}

Как я уже сказал, форма никогда не отправляется, а onSubmit () контроллера никогда не выполняется.Спасибо за любые идеи

Ответы [ 2 ]

1 голос
/ 25 июля 2011

Я думаю, что могут быть некоторые ошибки привязки, поэтому я предлагаю переопределить

protected ModelAndView processFormSubmission(HttpServletRequest request,
                                             HttpServletResponse response,
                                             Object command,
                                             BindException errors)
                                      throws Exception

и проверить, что errors.hasErrors () возвращает false, просто чтобы убедиться, что отправка прошла успешно.1005 * См. processFormSubmission

0 голосов
/ 06 сентября 2014

В дополнение к принятому выше ответу я хотел бы отметить несколько вещей -

Если вы переопределили

Защищенные ссылочные данные карты (запрос HttpServletRequest, Команда объекта, Ошибки ошибок)

Метод

в вашем контроллере, который обычно вызывается по запросу GET, будет вызываться даже при отправке формы (POST). Это связано с тем, что при наличии какой-либо формы ошибки Binding будет перезагружен с повторным вызовом referecenData(). Конечно, вы можете переопределить метод processFormSubmission(), но если вы просто заинтересованы в переопределении метода onSubmit(), я предлагаю переопределить

защищенный ModelAndView onSubmit (запрос HttpServletRequest, ответ HttpServletResponse, команда Object, ошибки BindException)

метод и увидеть ошибку BindException.

...