struts2获取表单数据有三种方式
一丶借用ActionContext类得到域对象实现获取
public class FormDemo1 extends ActionSupport {
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
ActionContext context = ActionContext.getContext();
Map<String,Object> map = context.getParameters();
Set<String> keys = map.keySet();
for (String key : keys) {
Object[] obj = (Object[]) map.get(key);
System.out.println(Arrays.toString(obj));
}
return NONE;
}
}
二丶借用ServletActionContext类得到域对象实现获取
public class FormDemo2 extends ActionSupport {
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
HttpServletRequest request = ServletActionContext.getRequest();
String username=request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username+":"+password);
return NONE;
}
}
三丶java类实现ServletContextAware接口实现
public class FormDemo3 extends ActionSupport implements ServletContextAware {
//这是得到表单数据的第三种方式
@Override
public void setServletContext(ServletContext arg0) {
// TODO Auto-generated method stub
}
public String execute(){
return NONE;
}
}
struts2封装表单数据也有三种方式
一丶简单封装
-直接手动封装
二丶属性封装
-在Action中添加属性(属性的值必须和页面中的name属性相同才能实现封装)
而且该属性必须要有set方法
三丶模型驱动封装
-让Action实现ModelDriven接口
public class DataDemo2 extends ActionSupport implements ModelDriven<User>{
private User user = new User();
@Override
public User getModel() {
// TODO Auto-generated method stub
return user;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return super.execute();
}
}