简体   繁体   中英

struts2 populating default textfield and dropdown and binding to model

I would like to populate my textfield value and dropdown values upon page load. When the user clicks on submit, the textfield and dropdown value should be binded to the model (Person class).

How can I do so?

public class Person {

    private String name;
    private String food;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setFood(String food) {
        this.food = food;
    }

    public String getFood() {
        return food;
    }
}


public class PersonAction extends ActionSupport implements ModelDriven  {

    private Map<String,String> foodList = new HashMap()<String,String>;
    private String name = "What is your name?"
    private Person person;

    public String execute() {
        foodList.put("IC","Ice Cream");
        foodList.put("CA","Cake");
        return SUCCESS;
    }

    public Object getModel() {
        return person;
    }

}

<s:form action="addPerson" >
    <s:textfield name="name">
    <s:select list="foodList" name="" />
    <s:submit type="button" name="submit" />
</s:form>

You should use the name attribute in the tags s:select and s:textfield

<s:textfield name="name">
<s:select list="foodList" name="food" />

This way, the field are going to be binded with getModel().name and getModel().food in the action.

To show the "What is your name" text, you have two options:

In the action class, set the person name as "What is your name".

public String execute() {
    person = new Person();
    person.setName("What is your name?");
    foodList.put("IC","Ice Cream");
    foodList.put("CA","Cake");
    return SUCCESS;
}

Or you could use the placeholder tag attribute to show the "what's your name" text by default.

<s:textfield name="name" placeholder="What is your name?">

I edited the answer to use the modelDriven implemented action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM