struts学习心得

来源:互联网 发布:室内设计常用的软件 编辑:程序博客网 时间:2024/04/30 17:31

一,struts框架初始化基本流程:
1.Web服务器接到Request请求时,首先加载并初始化ActionServlet.
2.ActionServlet会读取struts-config.xml配置文件,把配置文件信息存入ActionMapping对象中.

二,struts框架响应客户请求的工作流程
1.查找ActionMapping实例.
2.查找ActionForm实例,如果没有,会创建一个ActionForm实例.把表单中的数据存入ActionForm中.
3.根据配置信息决定是否要进行数据验证.如果validate="true",则表示需要验证,要调用ActionForm中

的validate()方法.
4.如果validate()方法返回的是null或者数据验证成功则根据配置文件调用相应Action中的execute()

方法.execute()方法可以完成业务逻辑层的工作.比如操作DAO层进行CRUD.然后可以返回ActionForward

对象,决定返回给客户端哪个页面.
5.如果validate()方法返回了ActionMessage的ActionErrors对象,则表示表单验证失败.把错误信息返

回给客户端.


三,扩展ActionServlet类.
1.可以自己写一个类myActionServlet继承至ActionServlet.然后覆盖父类的init()方法.但必须先调用

super.init();方法.之后再写自己需要的扩展功能.
2.如果使用了ActionServlet的子类.则必须要在web.xml中时行配置.
  <servlet>
   <servlet-name>myActionServlet</servlet-name>
   <servlet-class>mystruts.myActionServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>myActionServlet</servlet-name>
  <url-pattern>/action/*</url-pattern>
  </servlet-mapping>
以后再访问http://localhost:8080/xx/action/yy 就会把该请求转发给myActionServlet处理.

四,在Struts中,擔任MVC/Model 2控制器角色核心的是ActionServlet,所有的請求都必須先通過它,

在Struts 1.1中,有關於請求的處理大部份已交由RequestProcessor,當ActionServlet收到GET或POST

的請求,其doGet()或doPost()會呼叫process()方法來處理請求:

protected void process(HttpServletRequest request,
                             HttpServletResponse response)
throws IOException, ServletException {
    RequestUtils.selectApplication(request, getServletContext());
    getApplicationConfig(request).getProcessor().process(request, response);
}


RequestUtils是個工具類,ActionServlet呼叫其selectApplication()方法,藉由

request.getServletPath()來取得請求路徑以選擇應用程式模塊來處理請求,之後從

ApplicationConfig物件取得RequestProcessor物件,將使用者的請求委託它來進行處理。

您可以繼承RequestProcessor,並改寫其中的processXXXXX()方法來自定義請求的處理方式,如果您要

使用自己的RequestProcessor,要要在struts-config.xml中使用<controller>標籤來定義,例如:

<controller
    contentType="text/html;charset=Big5"
    locale="true"
    nocache="true"
    processorClass="onlyfun.caterpillar.CustomRequestProcessor"/>
 
五,DispatchAction类
1.通常,在一个Action通过execute方法中只能完成一种业务操作.如果希望在同一个Action类中完成一

组相关的业务操作.如CRUD操作.那么就得使用DispatchAction.
 
  自己写一个DispatchAction的子类来扩展它.不必覆盖execute()方法.而是根据业务操作来创建一些

需要的方法.这些方法的参数和返回值类型必须都和exectue()方法相同并抛出异常.

在struts-config.xml中要写入
  </action>
      <action path="/cart" type="my.struts.action.CartAction"
      parameter="method" scope="request">
   
 </action>
必须要有parameter参数.当用户请求DispatchAction时,要提供method请求参数,表明要调用

DispatchAction中的哪个方法.
如: http://localhost:8080/xx/cart.do?method=yy

六.LookupDispatchAction类
LookupDispatchAction也是DispatchAction的子类.在LookupDispatchAction中通常是处理一个表单中

有多个提交按钮的操作.


*********************************************************
1.struts控制器的组件
ActionServlet类
RequestProcessor类
Action类

2.内置struts Action类
DispatchAction类
IncludeAction类
ForwardAction类
LookupDispatchAction类
SwingAction类