1. 程式人生 > >Struts2之action接收請求引數

Struts2之action接收請求引數

1. 採用基本型別接受請求引數(get/post)

action:

public class GetparamAction extends ActionSupport {
private int age;
private String name;
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;
}
public String get() {
System.out.println( "age=" + age + "name=" + name);
return "get";
}
}

JSP:

<a href="${pageContext.request.contextPath }/getparam/GetparamAction.action?name=aa&age=11">請求GetparamAction</a>

說明:看了別人寫的,“在Action類中定義與請求引數同名的屬性,struts2便能自動接收請求引數並賦予給同名的屬性。”,其實這句話是不對的,這會讓人誤以為action屬性名必須和請求引數名一樣,其實action類中的屬性名不一定要和請求引數同名,可以試驗一下。Struts2是通過反射技術呼叫了set方法來獲取請求引數的。

如:請求引數str=aa,那麼就會去呼叫action中的

public void setStr(String 引數名){

this.name=引數名;//但是不推薦這樣寫,這樣沒約定好,可讀性差

//這樣同樣能接收到引數

}

請求引數名要和set***方法中的***匹配,這樣就會呼叫相應的set方法。

2. 採用複合型別接受請求引數

action:

public class DomainModelAction extends ActionSupport {
private Person person;//Person類
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}

public String test() {
System.out.println("name:" + person.getName());
System.out.println("age:" + person.getAge());
return "test";
}


}

jsp:

<a href="${pageContext.request.contextPath }/getparam/DomainModelAction.action?person.age=22&person.name=aa">請求DomainModelAction</a>

轉到get.jsp

獲取屬性<s:property value="person.name"/>

          <s:property value="person.age"/>