如何从spring mvc表单中检索和创建嵌套对象

时间:2017-07-21 14:09:32

标签: java spring jsp spring-mvc

我正在学习spring mvc,我正面临一个问题。我有两个对象Country和Capital。我想要完成的是当我在jsp中创建一个新的国家时,我想创建一个新的资本(国家名称,人口和资本名称将由用户输入)。我不知道如何检索Capital对象以及如何将其传递给我的控制器。请解释。谢谢!

Country.java

@Entity
@Table(name="COUNTRY")
public class Country{
    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;

    @Column(name="countryName")
    String countryName; 

    @Column(name="population")
    long population;

    @OneToOne
    @JoinColumn(name="capitalId")
    Capital capital; 

    public Country() {
        super();
    }
    public Country(int i, String countryName,long population) {
        super();
        this.id = i;
        this.countryName = countryName;
        this.population=population;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public long getPopulation() {
        return population;
    }
    public void setPopulation(long population) {
        this.population = population;
    }
    public Capital getCapital() {
        return capital;
    }
    public void setCapital(Capital capital) {
        this.capital = capital;
    }   
}

Capital.java

@Entity
@Table(name="CAPITAL")
public class Capital {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;
    @Column(name="capitalName")
    private String capitalname;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getCapitalname() {
        return capitalname;
    }
    public void setCapitalname(String capitalname) {
        this.capitalname = capitalname;
    }
}

countryDetails.jsp

<form:form method="post" modelAttribute="country" action="/SpringMVCHibernateCRUDExample/addCountry">
<table>
        <tr>
            <th colspan="2">Add Country</th>
        </tr>
        <tr>
        <form:hidden path="id" />
          <td><form:label path="countryName">Country Name:</form:label></td>
          <td><form:input path="countryName" size="30" maxlength="30"></form:input></td>
        </tr>
        <tr>
                <td><form:label path="population">Population:</form:label></td>
          <td><form:input path="population" size="30" maxlength="30"></form:input></td>
        </tr>
        <tr>
            <td><form:label path="capital">Capital</form:label></td>
        </tr>       
        <tr>
            <td colspan="2"><input type="submit"
                class="blue-button" /></td>
        </tr>
    </table> 
</form:form>

0 个答案:

没有答案