Sunday, February 14, 2016

Struts1 internal mechanism with an example to use

Seeing the diagram from here

To understand Struts1 internal mechanism, we will do manual setup and config for one web login request.

  1. ActionServlet: core servlet of Struts, is the call center of struts
  2. web.xml: Config web.xml to load ActionServlet as a normal servlet(the entrance of struts framework)
         Assign ActionServlet's own config file in <init-param>: struts-config.xml
         In this config, all *.do url requests will be forward to use structs framework
        The ActionServlet is important to be initialized before the first call, so:
    <load-on-startup>2</load-on-startup> is important to set, when you see error :  Module 'null' not found. 
  3.   <servlet>
       <!-- struts-config -->
  4. struts-config.xml: ActionServlet load this file to config all actions and actionForms
    (a)action's path will be the requested url's resource part(take the string ".do" out)
    (b)<form-bean>'s name will be used to match <action>'s name
    (c)<forward> name will be used to forward to target output file

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
      <form-bean name="UserForm" type="com.gvace.struts1login.forms.UserForm"></form-bean>
      <!-- localhost:8080/webapp/, action path is the requested url path -->
      <!-- form-bean connect to the action identified by name -->
      <action path="/login" name="UserForm" type="com.gvace.struts1login.actions.LoginAction">
       <!-- action choose which forward to go by forward name -->
       <forward name="ok" path="/WEB-INF/welcome.jsp"></forward>
       <forward name="err" path="/WEB-INF/err.jsp"></forward>
  5. Form-bean( in the example), extends ActionForm, is a javabean
    Set all field names match to the form attributes
  6. Action class( in the example),extends Action, contains the logic to process the Form
    Override the ActionForward function to process all logic
     public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
       throws Exception {
      UserForm userForm = (UserForm)form;
       return mapping.findForward("ok");
      return mapping.findForward("err");
  7. ActionMapping: use ActionMapping to tell ActionServlet which path to forward, by telling it the forward name, using findForward function: mapping.findForward("ok");

No comments:

Post a Comment