担任MVC/Model 2控制器角色核心的是ActionServlet.
ActionServlet必须在web.xml里进行配置。具体配置参数参见“web.xml参数设置.doc”
Servlet容器在启动时,或者用户首次请求ActionServlet时加载ActionServlet类,在上述情况下,Servlet容器都会在ActionServlet被加载后立即执行它的init()方法。具体的init()方法代码解读参见“ActionServlet的init()方法.doc”。
可以继承ActionServlet来定义自己的控制器,通常的目的是重新定义ActionServlet的init()方法,增加自己的初始化动作:
定义如下的类:
import sample;
public class ExtendedActionServlet extends ActionServlet {
public void init() throws ServletException {
super.init();
//加入自己的代码
……………
}
}
扩展完类后,还应该在web.xml文件中如下配置:
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>sample.ExtendedActionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>/ *.do<url-pattern>
<servlet-mapping>
客户端的所有请求都必须先通过ActionServlet,在Struts 1.1中,有关于请求的处理大部份已交由RequestProcessor,当ActionServlet收到GET或POST的请求,其doGet() 或doPost()会呼叫process()方法来处理请求:
ActionServlet的doGet()方法:
/**
* Process an HTTP "GET" request.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
ActionServlet的doPost()方法:
/**
* Process an HTTP "POST" request.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
process(request, response);
}
ActionServlet的process()方法:
protected void process(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
//取得请求路径以选择应用程序模块来处理请求
RequestUtils.selectApplication(request, getServletContext());
/* getApplicationConfig(request)获得Applicationconfig对象
* Applicationconfig对象调用getProcessor()方法获得RequestProcessor对象
* RequestProcessor对象调用process()方法处理请求,具体的方法代码参见“RequestProcessor的process()方法.doc”
*/
getApplicationConfig(request).getProcessor().process(request, response);
}
您可以继承RequestProcessor,并改写其中的processXXXXX()方法来自定义请求的处理方式
如果您要使用自己的 RequestProcessor,要要在struts-config.xml中使用<controller>标签来定义,例如:
struts-config.xml中:
<controller
contentType="text/html;charset=GB2312"
nocache="true"
processorClass="onlyfun.caterpillar.CustomRequestProcessor"/>
struts-config.xml:
评论