简体   繁体   English

struts2填充默认文本字段和下拉列表并绑定到模型

[英]struts2 populating default textfield and dropdown and binding to model

I would like to populate my textfield value and dropdown values upon page load. 我想在页面加载时填充我的textfield值和dropdown值。 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:select和s:textfield中使用name属性。

<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. 这样,该字段将在操作中与getModel()。name和getModel()。food绑定。

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. 我编辑了答案,以使用modelDriven实现的动作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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