【问题标题】:Ajax and Spring MVC data not getting populated on browserAjax 和 Spring MVC 数据未在浏览器上填充
【发布时间】:2017-09-12 20:30:47
【问题描述】:

我问了一个关于无法在此链接中使用 ajax 列出表格中的数据的问题:Ajax and Spring MVC view list in a table not working

上述问题已解决,现在我尝试在具有 OneToOne 关系的 Customer 对象中使用 Address 对象,我如何将其放入我的 ajax 和 jsp 代码中。这里的问题是,街道、州、邮政编码等地址值……在单击创建按钮后没有保存到数据库中,只有客户名称、电子邮件等客户详细信息才会被填充。如果有人可以帮忙。谢谢。下面是代码 sn-p:-

script.js

function doAjaxPosts() {
// get the form values

var customerName= $('#customerName').val();
var contactName= $('#contactName').val();
var email= $('#email').val();
var street= $('#street').val();
var zipCode= $('#zipCode').val();
var state= $('#state').val();
var country= $('#country').val();

$.ajax({
    type : "POST",
    url :  "createCustomer",
    data: "customerName="+ customerName + "&contactName=" + contactName + "&email=" + email + "&street=" + street +
          "&state=" + state + "&zipCode=" + zipCode + "&country=" + country,

    success : function(response) {
        // we have the response
        alert('data saved to DB');
        window.location = '/UtilityWebApplication'
    }
});

}

我的控制器类中的方法:

//这是默认主页

@RequestMapping(value="/", method=RequestMethod.GET)
    public String goToHomePage(@ModelAttribute Customer customer, Model model) {

        model.addAttribute("customers", customerServiceImpl.getAllCustomers());
        return "Home";

    }

    //Method to Create Customer 
    @RequestMapping(value="/createCustomer", method=RequestMethod.POST)
    public String createCustomer(Customer customer, Model model) {
        customer.setCreatedDate(new Date());
        customer.setCustomerDeleted(false);
        customerServiceImpl.createCustomer(customer);
        model.addAttribute("customers", customerServiceImpl.getAllCustomers());
        return "Home";

    }

jsp页面:

<!--create customer modal  -->

<div id="createCustomerModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                Create New Customer
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">



                <table class="form-table">
                    <tbody>
                        <tr valign="top">
                            <td style="width: 25% !important;"><label
                                class="not-required" for="pool-name">Customer Name:</label></td>
                            <td><input type="text" id="customerName" title="Company Name" path="#"
                                class="form-control" /></td>
                        </tr>
                        <tr valign="top">
                            <td style="width: 25% !important;"><label
                                class="not-required" for="expire-after">Contact Name:</label></td>
                            <td><input type="text" id="contactName" path="#"
                                class="form-control" /></td>
                        </tr>
                        <tr valign="top">
                            <td style="width: 25% !important;"><label
                                class="not-required" for="description">Street:</label></td>
                            <td><input type="text" id="street" path="#"
                                class="form-control" /></td>
                        </tr>
                        <tr valign="top">
                            <td style="width: 25% !important;"><label
                                class="not-required" for="expire-after">State:</label></td>
                            <td><input type="text" id="state" path="#"
                                class="form-control" /></td>
                        </tr>
                        <tr valign="top">
                            <td style="width: 25% !important;"><label
                                class="not-required" for="expire-after">Zip-Code:</label></td>
                            <td><input type="text" id="zipCode" path="#"
                                class="form-control" /></td>
                        </tr>
                        <tr valign="top">
                            <td style="width: 25% !important;"><label
                                class="not-required" for="expire-after">Country:</label></td>
                            <td><input type="text" id="country" path="#"
                                class="form-control" /></td>
                        </tr>

                        <tr valign="top">
                            <td style="width: 25% !important;"><label
                                class="not-required" for="expire-after">Email:</label></td>
                            <td><input type="text" id="email" path="#"
                                class="form-control" /></td>
                        </tr>

                    </tbody>
                </table>


            </div>
            <div class="modal-footer">
                <div>
                    <input type="submit" id="createNewCustomer" value="Create"
                        class="btn btn-default" onClick="doAjaxPosts();" />
                    <button type="button" class="btn btn-default" data-dismiss="modal">close</button>
                </div>

            </div>
        </div>
    </div>
</div>

客户类别:

 import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class Customer {
    @Id
    @GeneratedValue
    private long id;
    private String customerName;
    private String contactName;
    private String email;


    private Boolean customerDeleted= false;
    @OneToMany(cascade=CascadeType.ALL, mappedBy="customer", fetch=FetchType.LAZY, orphanRemoval= true)
    private List<Certificate> certificates;
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="address_id")
    private Address address;
    @Temporal(TemporalType.TIMESTAMP)
    private Date deletedDate;
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdDate;
    private String street;
    private String state; 
    private int zipCode;
    private String country;

    public Customer() {

    }



    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String contactName) {
        this.contactName = contactName;
    }


    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public List<Certificate> getCertificates() {
        return certificates;
    }

    public void setCertificates(List<Certificate> certificates) {
        this.certificates = certificates;
    }

    public Boolean getCustomerDeleted() {
        return customerDeleted;
    }

    public void setCustomerDeleted(Boolean customerDeleted) {

        this.customerDeleted = customerDeleted;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Date getDeletedDate() {
        return deletedDate;
    }

    public void setDeletedDate(Date deletedDate) {
        this.deletedDate = deletedDate;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {

        this.createdDate = createdDate;
    }
}

地址类:

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class Address {
    @Id
    @GeneratedValue
    private long id;
    private String street;
    private String state; 
    private int zipCode;
    private String country;

    @OneToOne(cascade=CascadeType.MERGE, mappedBy="address", orphanRemoval=true)
    private Customer customer;

    public Address() {}
    public Address(String street,String state,int zipCode,String country) {
        this.street=street;
        this.state=state;
        this.zipCode=zipCode;
        this.country=country;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public int getZipCode() {
        return zipCode;
    }

    public void setZipCode(int zipCode) {
        this.zipCode = zipCode;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    }

CustomerDaoImp 类只有 CreatePart:

    @Override
    public void createCustomer(Customer customer) {

        sessionFactory.getCurrentSession().persist(customer);

    }

CustomerServiceImp 类:

@Override
    public void createCustomer(Customer customer) {


        customerDao.createCustomer(customer);

    }

【问题讨论】:

    标签: javascript jquery ajax spring jsp


    【解决方案1】:

    尝试在 ajax 数据参数中发送一个对象,对象键应与 spring 中的客户模型属性名称相同,如果仍然无法正常工作,请尝试在您的服务中创建一个 Address 类型的新实例并将其设置给您的客户保存客户之前的对象

      $.ajax({
            type : "POST",
            url :  "createCustomer",
            data: {customerName: customerName, contactName: contactName, email: email, address: {
          street: street, zipCode: zipCode, country: country
        }}
            success : function(response) {
                // we have the response
                alert('data saved to DB');
                window.location = '/UtilityWebApplication'
            }
        });
    
    
            //Method to Create Customer 
                    @RequestMapping(value="/createCustomer", method=RequestMethod.POST)
                    public String createCustomer(@Requestbody Customer customer, Model model) {
                        customer.setCreatedDate(new Date());
                        customer.setCustomerDeleted(false);
                        customerServiceImpl.createCustomer(customer);
                        model.addAttribute("customers", customerServiceImpl.getAllCustomers());
                        return "Home";
    
                    }
    
    
    
    @Entity
    @Table(name = "address")
    public class Address implements Serializable {
    
        @Id
        @GeneratedValue
        private Long id;
    
        @Column
        private String street;
    
        @Column
        private String country;
    
        @Column
        private int zipCode;
    
        @OneToOne(mappedBy = "address", fetch = FetchType.EAGER)
        private Customer customer;
    
        public Address() {
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getStreet() {
            return street;
        }
    
        public void setStreet(String street) {
            this.street = street;
        }
    
        public String getCountry() {
            return country;
        }
    
        public void setCountry(String country) {
            this.country = country;
        }
    
        public int getZipCode() {
            return zipCode;
        }
    
        public void setZipCode(int zipCode) {
            this.zipCode = zipCode;
        }
    
        public Customer getCustomer() {
            return customer;
        }
    
        public void setCustomer(Customer customer) {
            this.customer = customer;
        }
    }
    
    @Table(name = "customer")
    public class Customer implements Serializable {
    
        @Id
        @GeneratedValue
        private Long id;
    
        @Column
        private String name;
    
        @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
        @JoinColumn(name = "address_id")
        private Address address;
    
        public Customer() {
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Address getAddress() {
            return address;
        }
    
        public void setAddress(Address address) {
            this.address = address;
        }
    }
    

    【讨论】:

    • 我使用了您在 ajax 上建议的代码,我收到这样的错误:org.springframework.beans.InvalidPropertyException: bean 类 [com.model.Customer] 的无效属性“地址 [国家]”:索引属性路径'address[country]'中引用的属性既不是数组也不是List也不是Map;返回值为 [usa]
    • 我建议了两种解决方案,一种在客户端,另一种在服务器端。你都试过了吗?您可以发布您的客户实体和地址实体吗?
    • 您的客户实体应具有地址实体作为属性,并带有@OneToOne 关系注释
    • 我已经发布了所有的模型和服务类。我也尝试了你的第二个建议,但我得到了同样的错误。如果可能的话,你能否在上面的代码中添加你的第二个建议谢谢。
    猜你喜欢
    • 2021-10-25
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2012-06-16
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多