struts2怎么实现模型驱动

如题所述

当我们在action类中使用某个对象来封装页面中传递的参数时,如果我们仍然想使用原来的参数名来作为标签的命名,则可以使用模型驱动。
温馨提示:内容为网友见解,仅供参考
第1个回答  2018-12-13

    1、Struts2模型驱动方式获得参数

第一步:创建对象

public class User { 
    private String name; 
    private Integer age; 
    private Date birthday; 
    public String getName() { 
        return name; 
        } 
    public void setName(String name) { 
        this.name = name; 
        } 
    public Integer getAge() { 
        return age; 
        } 
    public void setAge(Integer age) { 
        this.age = age; 
        } 
    public Date getBirthday() { 
        return birthday; 
        } 
    public void setBirthday(Date birthday) { 
        this.birthday = birthday; 
        } 
    public String toString() { 
        return "User [name=" + name + ", age=" + age + ", birthday=" + birthday + "]"; 
        }
}

第二步:创建jsp页面

<form action="${pageContext.request.contextPath}/api/DemoApi6" method="post"> 
    <label>姓名:<input type="text" name="username" ></label><br/> 
    <label>年龄:<input type="number" min="18" max="90" name="age" >
    </label><br/> <label>生日:<input type="date" name="birthday" ></label><br/> 
    <input type="submit" value="OK"> 
</form>

第三步:创建Action方法

// struts2使用模型驱动获得参数 
public class DemoApi6 extends ActionSupport implements ModelDriven<User>{ 
    // 准备一个user对象; 
    private User user = new User(); 
    public String action_name() throws Exception { 
        System.out.println("名称:" + user.getName() + ";年龄" + user.getAge() + ";生日:" + user.getBirthday()); 
        return SUCCESS; 
        } 
    public User getModel() {
        return user; 
        }
}

第四步:配置文件

<!-- 模型驱动获取参数 --> 
<action name="DemoApi6" class="com.java.Demo.api.DemoApi6" method="action_name"> 
    <result name="success" type="dispatcher">/form3.jsp</result> 
</action>

网络电虫 ,你可以看看这篇文章,如果有什么不懂的话,讲的还算是蛮详细的~


相似回答