public ActionForward execute(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response) throws Exception; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception;由于Action通常处理HTTP相关请求,所以常会使用第二个方法,execute()方法最后要传回ActionForward对象给 RequestProcessor,来回顾一下 第一个 Struts 程序 中的HelloAction的例子:
package onlyfun.caterpillar;这要配合struts-config.xml中的请求URI与对应的Action设定,所以改写 第一个 Struts 程序 的struts-config.xml设定:
import java.util.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class HelloAction extends Action {
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
// get information from request object
String username = request.getParameter("user");
// no more carrying information from client
request.removeAttribute("user");
// prepare model
Map model = new HashMap();
if(username != null)
model.put("username", username);
else
model.put("username", "nobody");
// pass information to View by using reqeust object
request.setAttribute("userInfo", model);
return mapping.findForward("helloUser");
}
}
<?xml version="1.0" encoding="ISO-8859-1" ?>在 MVC / Model 2 中,理想上所有客户端的请求都经由Controller来协调转发,客户端不会直接指定真正的地址来请求资源,您可以将资源放在/WEB-INF目录下 (如例子中的/WEB-INF/pages/hello.jsp),如此客户端就只能透过Controller的转发取得资源。
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<global-forwards>
<forward
name="welcome"
path="/welcome.do"/>
</global-forwards>
<action-mappings>
<action
path="/welcome
type="org.apache.struts.actions.ForwardAction"
patameter="/WEB-INF/pages/welcome.jsp"/>
<action
path="/hello"
type="onlyfun.caterpillar.HelloAction">
<forward
name="helloUser"
path="/WEB-INF/pages/hello.jsp"/>
</action>
<action-mappings>
</struts-config>
... <action path="/someresource" type="org.apache.struts.actions.IncludeAction" parameter="/path/someResource"/> ...Action对象是Controller的一部份,在Action对象中的逻辑最好只与Web层的资料准备有关,而不涉及业务逻辑,基本上在Action 中您所要作的是: