Action 接受参数的3中方式(4)

Action 接受参数的3中方式

1.继承ActionSupport的Action

在Action中添加字段,这些字段的名字与参数的名字相同,并添加相应的setters与getters方法。

package com.bjsxt.struts2.user.action;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
	
	private String name;
	private int age;
	
	public String add() {
		System.out.println("name=" + name);
		System.out.println("age=" + age);
		return SUCCESS;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
}

传参:action!method?name=gaoweigang&age=8 

 

2.DomainModel(最常用)

编写Model

package com.bjsxt.struts2.user.model;

public class User {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

 编写Action

package com.bjsxt.struts2.user.action;

import com.bjsxt.struts2.user.model.User;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
	
	private User user;
	//private UserDTO userDTO;//数据传输对象,里面并不是每个字段都必须有值
	public String add() {
		System.out.println("name=" + user.getName());
		System.out.println("age=" + user.getAge());
		return SUCCESS;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
}

 传参:action!method?user.name=gaoweigang&user.age=8 

 

第三种方式 ModelDriven (这种方式并不常用)
package com.bjsxt.struts2.user.action;

import com.bjsxt.struts2.user.model.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<User>{//1.实现ModelDriven接口
	
	private User user = new User();//2. new一个model
	
	public String add() {
		System.out.println("name=" + user.getName());
		System.out.println("age=" + user.getAge());
		return SUCCESS;
	}

	@Override
	public User getModel() {//3.getModel
		return user;
	}
	
}

传参:namespace/action!methodname?name=gaoweigagn&age=8

你可能感兴趣的:(action)