action获取表单提交的数据主要的三种方式
(1)使用 actionContext类
(2) 使用ServletActionContext类
(3)使用接口注入的方式
一、使用actionContext类
package com.tui;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import org.apache.struts2.dispatcher.Parameter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Form1DemoAction extends ActionSupport {
@Override
public String execute() throws Exception {
// TODO 自动生成的方法存根
ActionContext actionContext= ActionContext.getContext();
Map<String, Parameter>map= actionContext.getParameters();
Set<String>keys=map.keySet();
for(String key:keys)
{
Parameter objects=map.get(key);
System.out.println( objects.getValue());
}
return NONE;
}
}
二、使用ServletActionContext类
package com.tui;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Parameter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Form1DemoAction2 extends ActionSupport {
@Override
public String execute() throws Exception {
// TODO 自动生成的方法存根
HttpServletRequest httpServletRequest= ServletActionContext.getRequest();
String username=httpServletRequest.getParameter("uname");
String upassword=httpServletRequest.getParameter("upassword");
String uaddress=httpServletRequest.getParameter("uaddress");
System.out.println(username+":"+upassword+":"+uaddress);
return NONE;
}
}
三、实现ServletRequestAware接口
package com.tui;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Parameter;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Form1DemoAction3 extends ActionSupport implements ServletRequestAware {
private HttpServletRequest request;
@Override
public void setServletRequest(HttpServletRequest request) {
// TODO 自动生成的方法存根
this.request=request;
}
@Override
public String execute() throws Exception {
// TODO 自动生成的方法存根
String username=request.getParameter("uname");
String userpassword=request.getParameter("upassword");
String useraddress=request.getParameter("uaddress");
System.out.println(username+":" +userpassword+":"+useraddress);
return NONE;
}
}
struts2.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="form1" class="com.tui.Form1DemoAction">
</action>
<action name="form2" class="com.tui.Form1DemoAction2">
</action>
<action name="form3" class="com.tui.Form1DemoAction3">
</action>
</package>
</struts>
实现结果: