1. Action类
Actions respond to requests. 它收到browser用户请求(这个请求包含一些列信息),并最终返回一个ActionForward对象名为success作为output view. That output view will be a plain old JSP.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class UserRegistrationAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
return mapping.findForward("success");
}
}
2. Action类是一个中间连接器
Actions are the glue between the Model and View.
简单的说,过程就是:
user request à Actions à [business logic] à response
问题是 用户请求如何提交到指定的Action?
Action在执行完业务逻辑后该返回什么地方?
这一系列的业务其实是由configuration file 配置文件完成的.
WEB-INF/web.xml 还有 WEB-INF/struts-config.xml
l web.xml :
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
...
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
这段关于servlet的配置文件在web容器启动的时候就被载入, 它制定了所有在browser中以.do结尾的servlets都要经由org.apache.struts.action.ActionServlet 来处理。而ActionServlet类加载的时候必须遵循初始参数中的配置文件,即 struts-config.xml
l Struts-config.xml :
<action path="/userRegistration"
type="strutsTutorial.UserRegistrationAction">
<forward name="success" path="/regSuccess.jsp"/>
</action>
The Struts ActionServlet will invoke our action based on the path attribute of the above action mapping. The ActionServlet will handle all requests that end in *.do.
The ActionMapping that gets passed to the execute method of the Action handler is the object representation of the action mapping in the Struts config file.
Web.xml中的<servlet-name>action</servlet-name> 与
Struts-config.xml中的 <action path> 相互影射.
<action type> 则表示该request将被提交到哪个Action类来处理,而forward则表示Action类返回的那个ActionForward对象的逻辑名称,path则是对应该logic name的physical file.
所以这个基本的流程就是:
浏览器发出request (abc.do),经由web.xml控制,转到struts-config.xml中找寻与该请求 abc.do 相对应的Action处理类,并将配置文件中有关该请求的设置作为一个对象(ActionMapping)传递给Action类,最后Action类根据ActionMapping中的信息返回一个指定的位置.