Struts2中接受参数(二):利用ModelDriven
TeacherAction.java:
package com.oristand.test;
import javax.xml.registry.infomodel.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.oristand.vo.Person;
public class TeacherAction extends ActionSupport implements ModelDriven<Person>{
private Person person = new Person();
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
public String add(){
System.out.println("person's name is: " + person.getName() );
System.out.println("person's age is: " + person.getAge() );
return SUCCESS;
}
public String delete(){
return SUCCESS;
}
public Person getModel() {
// TODO Auto-generated method stub
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
客户端访问:
http://localhost:8888/struts2_0100_ActionConfig/Teacher_add?person.name=st&person.age=222
结果控制台打印:
person's name is: st
person's age is: 0//这个有点不正确
struts2中的错误处理:
Action中相应的方法:
public String add(){
if(name == "" || !name.equals("admin")){
this.addFieldError("name", "name is not valid");
this.addFieldError("name", "you are so clever!");
this.addFieldError("test", "test");
return ERROR;
}
return SUCCESS;
}
相应的jsp页面:
<body>
<s:fielderror name="name"></s:fielderror>
<s:property value="errors.name[1]"/>//<s:debug>中分为value Stack Contents和Stack Content,对于value Stack Contents中的Propert Name,可以通过名字(例如error直接访问),对于Stack Content中的内容,则必须通过#来访问,如#request
<s:debug></s:debug>//这个很重要,可以查看Action中的value stack,action中的error是一个map,数据结构的东西还是很重要!
</body>