在struts2框架中接收参数的方式主要有属性驱动获取参数、对象驱动获取参数、模型驱动获取参数以及集合类型获取参数这四种,本章节就模型驱动方式获得参数进行学习~
1、Struts2模型驱动方式获得参数
从名字上就可以看出,此方式需要有一个对象模型,使用对象模型进行封装传递过来的参数,其根本上来说此方式仍旧利用的是属性驱动方式获取参数,其代码步骤如下所示:
第一步:创建对象
创建一个User类对象,其代码如下:
User.java
package com.java.Demo.api.domain;
import java.util.Date;
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页面
其前端代码不需要像对象驱动获取参数那样在每个输入框的键名前(ingput标签内的name属性值)加上类名,其代码如下所示:
form3.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方法
其代码如下:
DemoApi6.java
// 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;
}
}
第四步:配置文件
struts.xml
<!-- 模型驱动获取参数 -->
<action name="DemoApi6" class="com.java.Demo.api.DemoApi6" method="action_name">
<result name="success" type="dispatcher">/form3.jsp</result>
</action>
第五步:Demo测试
输入参数:
显示结果:
成功~
总结:
(1)在使用User类对象时一定要注意类对象中的属性名和jsp页面中输入框的键名称(name值)对应好;
(2)模型驱动获取参数在struts2框架的项目里还是比较常用的,应为比较方便~
struts2中几种参数传递获取方式如下:
属性驱动方式获得参数:https://blog.csdn.net/qq_40762011/article/details/84975163
对象驱动方式获得参数:https://blog.csdn.net/qq_40762011/article/details/84975677
模型驱动方式获得参数:https://blog.csdn.net/qq_40762011/article/details/84976004
List集合封装传递获取参数:https://blog.csdn.net/qq_40762011/article/details/84976453
Map集合封装传递获取参数:https://blog.csdn.net/qq_40762011/article/details/84988210