Saturday, September 24, 2016

Struts Overview


Struts Overview



Background


This will be the first in a series of articles about the way that Struts is used and the use of open-source components.

Framework Overview (Theoretical)


Struts is a development framework that simplifies some of the more challenging aspects of Java web development. Struts is based on the Model-View-Controller pattern.

  • The Model represents the data model and business logic
  • The View is the interface (UI)
  • The controller acts as a director controlling the flow


Struts is a Free Framework based on the collaboration of a community of developers. They abstracted common characteristics that exist in all web applications, but lead with the controller.

  • Controller
  • Actions-Model
  • View-Result/Presentation











What you need


To use Struts, you need the following jar files:

·         struts-core-1.3.10.jar

·         struts-taglib-1.3.10.jar

Getting it to work with Struts


A traditional Struts application used in my experience has the basic three elements; the Form Bean, the Action and the Java Server Page or JSP.  Their interaction is orchestrated by the Struts-config.xml.  Let’s see an example.

The Players


START HERE


The super-simple “Start Here” part of our application will do the following:

1.   Display greeting

2.   Display a list of links to other sample applications

To accomplish this we will need the following:

·         StartHereAction.java

·         StartHereForm.java

·         Step1.jsp

They reside here:




StartHereForm.java


This simple java bean is the setter and getter for our greeting.

StartHereAction.java


This java program passes the greeting to StartHereForm.java and returns “success” to Struts to let it know where to go next.

StartHere.jsp


Displays our greeting and a list of links.

STRUTS-CONFIG.XML


SSA’s use of Struts-Config.xml relies on the use of wildcards in their action mappings.  The following example explains how it is used.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
     "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
  <!-- ========== Form Beans Definitions ========================== -->
  <!—- The form bean definition is required so that Struts can know -->
  <!—- where to get the information. -->
  <form-beans>
    <form-bean name="StartHereForm" type="forms.StartHereForm" />
  </form-beans>
  <!-- ========== Global Exceptions Definitions =================== -->
  <global-exceptions>
  </global-exceptions>
  <!-- ========== Global Forwards Definitions ===================== -->
  <global-forwards>
    <!-- These "forwards" direct STRUTS to perform the actions associated with these URL's.
    For example, when someone has http://localserver/thisApp/StartHere.do, it triggers
    the launch of StartHereAction.java and, if the Action returns “success”, it will display
    StartHere.jsp.
    -->
    <forward name="StartHere" path="./StartHere.do" /><!-- Maps to /StartHere action -->
  </global-forwards>
  <!-- ========== Action Mapping Definitions ====================== -->
  <!-- The /StartHere in the path attribute allows the mapping to match the request.       
   -->
  <action-mappings>
  <!-- As redirected from the "StartHere" forward (above). This will show our Main Menu. -->
    <action
       path="/StartHere"
       type="actions.StartHereAction"
       name="StartHereForm">
      <forward name="success" path= "./WEB-INF/StartHere/Step1.jsp" />
    </action>
  </action-mappings>
  <controller nocache="true" /> 
</struts-config>

In short it is kind of like saying to Struts:

When someone types in StartHere.do, find the matching action. When you find the action, use the form bean that will have the information we will need to process this request. Once you have it use the java program labeled as type to perform the functionality on that bean. When you are done, if the application returns the word “success”, display the jsp associated with “success”.

All of that in one little xml doc…cool.

And here is the code


StartHereForm.java


Has getters and setters for the greeting.

package forms;
import com.organization.ocelot.forms.BaseForm;
public class StartHereForm extends BaseForm {
    private static final long serialVersionUID = -6688708519508889724L;
    private String GREETING;
      public String getGREETING() {
            return GREETING;
      }
      public void setGREETING(String greeting) {
            GREETING = greeting;
      }
}

…and it gets the greeting from

StartHereAction.java


package actions;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import forms.StartHereForm;
import com.organization.common.environmentManager.EnvironmentException;
import com.organization.common.environmentManager.EnvironmentManager;
import com.organization.common.environmentManager.IEnvironmentHandler;
import com.organization.common.propertyManager.IPropertyHandler;
import com.organization.common.propertyManager.PropertyException;
import com.organization.common.propertyManager.PropertyManager;
public class StartHereAction extends GSOBaseAction {
    private static final long serialVersionUID = 1L;
    public static HttpServletRequest req;
    public static HttpServletResponse res;
    //This section is merely our property handler and environment handler settings.
    //ideally, they will not be in individual pages, but this is strictly for
    //use as an example.
    static {
        IPropertyHandler pm = null;
      
        try {
           IEnvironmentHandler env = EnvironmentManager.getEnvironmentHandler();
           String envProp = env.getEnvironmentPrefix();
           pm = PropertyManager.getPropertyHandler();
           pm.load(envProp);
        }
        catch (PropertyException propEx) {
           String msg = "Unable to get Property Manager";
           System.out.println(msg + " for " + pm);
        }catch (EnvironmentException envEx) {
            String msg = "Unable to get Environment Manager";
            System.out.println(msg + ":" + envEx);              
        }
     }
     // This is our code the system.out stuff is just for reference in case you want  
     // to see what is happening.
      @Override
      public ActionForward execute(ActionMapping mapping, ActionForm form,
                  HttpServletRequest request, HttpServletResponse response) {
            System.out.println("ActionMapping is: " + mapping);
            System.out.println("ActionForm is: " + form);
            System.out.println("HttpServletRequest is: " + request);
            System.out.println("HttpServletResponse is: " + response);
            //create an instance of the form
            StartHereForm shf = (StartHereForm) form;
            System.out.println("ActionForm is: " + shf);
            //Send it the greeting
            shf.setGREETING("Getting Started with Ocelot");
            //Pass control back to the Struts-config.xml which should run the jsp
            // associated with "success"
            return mapping.findForward("success");
      }
}

Step1.jsp


Will display our greeting…

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
    <%@ taglib uri="http://struts.apache.org/tags-html" prefix="s" %>
   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Step 1</title>
</head>
<body>
<!—- This code is used to pull the value “GREETING” from our StartHereForm form.-->
<h1><bean:write name="StartHereForm" property="GREETING"/></h1>
<table>
<tr><td>Component</td>
<td>Description</td>
</tr>
      <tr>
            <td>
<s:link action="AHView.do">Available Hours</s:link>
</td>
            <td>
            <div><font size="3">The Available Hours component provides functionality
            for an application to specify available hours and generates warnings
            if a session is started close to the cut-off times.</font></div>
            </td>
      </tr>
      <tr>
<td>
<s:link action="Ent010View.do">User Experience Framework</s:link>
</td>
            <td>Helps make fancy-shmancy looking SSA web pages. This example also includes examples of <b>Navigator</b> and <b>Struts
            Extension</b>.</td>
      </tr>
<tr>
<td>
<s:link action="DPropView.do">Data Propagation</s:link>
</td>
            <td>Helps communication between applications using keys and cookies...all very cool</td>
      </tr>
</table>
</body>
</html>

I have created an index.jsp page that immediately redirect to StartHere.do, which you will recall triggers the StartHere action.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<logic:redirect forward="StartHere"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome 2 Ocelot</title>
</head>
<body>
Welcome 2 Ocelot (Struts 1)!
</body>
</html>

So when we run the program:

I hope this gives you a good understanding of how Struts is used and how beneficial it is in building flexible, un-tightly coupled web applications.