Action是干什么的?
无论你是使用Struts2还是SpringMVC,你都必须知道他们都是基于MVC架构的,而Struts2中的Action和SpringMVC中的Controller都属于架构中的C,也就是Control层,负责客户端与服务器的数据交换,流程控制。比如页面表单提交了用户名密码,Control层的作用就是接收用户名密码,并且调用相关服务或者类验证准确性,最后再回应客户端需要显示什么View结果。
Action在Struts2中至关重要,让数据传到后台,就已经可以把参数当做本地变量处理了。Action实质上是一个Servlet,通过框架的内部实现和功能增强,让数据不再需要通过request.getParameter()来获取,只需要将参数作为成员变量定义在Action类中,框架就会帮我们注入参数值,看起来就像是在调取本地变量。
Action的写法
要求
- 继承ActionSupport
- 方法为public修饰
- 方法无参数
- 方法返回值为String类型
写法
MyAction.java
package action;
import com.opensymphony.xwork2.ActionSupport;
public class MyAction extends ActionSupport {
private static final long serialVersionUID = 1L;
//参数直接被框架注入到Action类的成员变量中
private String name;
private int age;
//action方法,在配置文件中配置映射
public String hi(){
System.out.println("run---> hi,"+name+","+age);
return SUCCESS;
}
public String hello(){
System.out.println("run---> hello,"+name+","+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;
}
}
映射关系
配置文件struts.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>
<!-- namespace要用"/" action不用-->
<package name="myaction" extends="struts-default" namespace="/myaction">
<action name="*" class="action.MyAction" method="{1}">
<result name="success">/success.jsp</result>
</action>
<!-- 也可以写成↓↓↓
<action name="hi" class="action.MyAction" method="hi">
<result name="success">/success.jsp</result>
</action>
-->
</package>
</struts>
访问结果:
在Action中怎么访问一些常用的实例
在Action中,我们要取得像pageContext、request、response、servletContext该写什么语句呢?
//通过ServletActionContext类的静态方法取得。
ServletActionContext.getPageContext();
ServletActionContext.getRequest();
ServletActionContext.getResponse();
ServletActionContext.getServletContext();