职责,线程安全,scope为session,ForwardAction, DispatchAction
Action的职责:
校验输入数据
调用业务逻辑方法
检测处理异常
根据逻辑进行转向操作
scope为session主要是用在如电子商务网站中的购物流程page1->page2->page3...,即多个页面的数据放到一个ActionForm里面,但是在大型的购物网站的话,一般也不放在session里面的,一般是放在cookie里面,一点需要注意的是应该在开始时把以前的数据先清空才对的
public class StartAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
SessionScopeActionForm ssaf=(SessionScopeActionForm)form;
ssaf.resetData(mapping, request);
return mapping.findForward("success");
}
}
ForwardAction:他的作用跟那个forward属性一样,就是用来分发,用来转向的
用法:在struts-config.xml中进行配置即可,我们自己就不用写了,他的源码:
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
// Create a RequestDispatcher the corresponding resource
String path = mapping.getParameter();
if (path == null) {
throw new ServletException(messages.getMessage("forward.path"));
}//所以ForwardAction是需要配置一个path属性的
// Let the controller handle the request
ActionForward retVal = new ActionForward(path);
retVal.setContextRelative(true);
return retVal;
}
跟forward属性的区别主要是生命周期的差异,这都可以通过分析源码知道的
DispatchAction:它也是一个Action,
怎么用:我们写一个Action继承自这个DispatchAction,以后所有的增删改查都在一个Action里面即可,通过方法来做,这个Action里面的crud的方法名跟execute不能一样,并且其他参数等等跟execute一样,而且也不能够覆盖了父类的execute方法,或者你覆盖了之后要显示的调用一下父类的execute方法
看它源码中execute方法:
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (isCancelled(request)) {
ActionForward af = cancelled(mapping, form, request, response);
if (af != null) {
return af;
}
}
// Get the parameter. This could be overridden in subclasses.
String parameter = getParameter(mapping, form, request, response);//是通过配置文件中得来的,所以action标签里面必须得配parameter
// Get the method's name. This could be overridden in subclasses.
String name = getMethodName(mapping, form, request, response, parameter);
// Prevent recursive calls
if ("execute".equals(name) || "perform".equals(name)){
String message =
messages.getMessage("dispatch.recursive", mapping.getPath());
log.error(message);
throw new ServletException(message);
}
// Invoke the named method, and return the result
return dispatchMethod(mapping, form, request, response, name);//这个方法就是用来对Action里面的方法进行处理的,它会采用反射来处理
}
他的典型配置如下:
<action path="/user/usermgr"
type="cn.wenping.struts.UserAction"
parameter="command"
>
<forward name="add_success" path="/user/add_success.jsp"></forward>
<forward name="del_success" path="/user/del_success.jsp"></forward>
<forward name="update_success" path="/user/update_success.jsp"></forward>
</action>
unspecified方法可以覆盖,如果页面中没有传过来任何的命令时就会调用这个方法