Monday, January 13, 2014

Struts Sample Code

A Full Struts Application
//index.jsp
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>

<html:html locale="true">
<head>
<title>A Welcome Page</title>
<html:base/>
</head>
<body bgcolor="white">

<logic:notPresent name="org.apache.struts.action.MESSAGE" scope="application">
  <font color="red">
    ERROR:  Application resources not loaded -- check servlet container
    logs for error messages.
  </font>
</logic:notPresent>
    <h1>Reading User Input</h1>

    <html:form action="Data"
          Please type your name: <html:text property="text" />
          <html:submit />
    </html:form

</body>
</html:html>

//ch03_01.jsp
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<%@ taglib uri="/tags/struts-logic" prefix="logic" %>
<%@ taglib uri="/ch03" prefix="ch03" %>

<HTML>
    <HEAD>
        <TITLE>The Struts Cafe</TITLE>
    </HEAD>
    
    <BODY>
        <H1>The Struts Cafe</H1>
        <html:errors/>
        <ch03:items/>
        <ch03:toppings/>
        <html:form action="ch03_04.do">
            <TABLE>
                <TR>
                    <TD ALIGN="LEFT" VALIGN="TOP">
                        <bean:message key="toppings"/>
                        <BR>
                        <logic:iterate id="toppings1" name="toppings">
                            <html:multibox property="toppings">
                                <%= toppings1 %>
                            </html:multibox>
                            <%= toppings1 %>
                            <BR>
                        </logic:iterate>
                    </TD>
                    <TD ALIGN="LEFT" VALIGN="TOP">
                        <bean:message key="items"/>
                        <BR>
                        <html:select property="items">
                            <html:options name="items"/>
                        </html:select>
                    </TD>
                </TR>
                <TR>
                    <TD ALIGN="LEFT">
                                    <BR>
                        <bean:message key="email"/>
                        <html:text property="email"/>
                    </TD>
                <TR>
            </TABLE>
                  <BR>
            <html:submit value="Place Your Order!"/>
        </html:form>
    </BODY>
</html>

package ch03;

import ch03.DataForm;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public class DataAction extends Action {

  public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {

    String text = null;

    String target = new String("success");

    if form != null ) {

      DataForm dataForm = (DataForm)form;

      text = dataForm.getText();

    }

    return (mapping.findForward(target));
  }
}

package ch03;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;

public class DataForm extends ActionForm {

  private String text = null;

  public String getText() {

    return (text);
  }

  public void setText(String text) {

    this.text = text;
  }

  public void reset(ActionMapping mapping,
    HttpServletRequest request) {

    this.text = null;
  }

//  public ActionErrors validate(ActionMapping mapping,
//    HttpServletRequest request) {

//    ActionErrors errors = new ActionErrors();

//    if ( (symbol == null ) || (symbol.length() == 0) ) {

//      errors.add("symbol",
//        new ActionError("errors.data.symbol.required"));
//    }
//    return errors;
//  }
}

package ch03;

import java.util.*;
import javax.servlet.jsp.tagext.TagSupport;

public class ch03_02 extends TagSupport 
{
    public int doStartTag() 
      {
        
        String[] itemsArray = {"""Pizza""Calzone""Sandwich"};
        
        pageContext.setAttribute("items", itemsArray);
        
        return SKIP_BODY;
    }
}
package ch03;

import java.util.*;
import javax.servlet.jsp.tagext.TagSupport;

public class ch03_03 extends TagSupport 
{
    public int doStartTag() 
      {
        String[] toppingsArray = {"Pepperoni""Hamburger""Sausage""Ham""Cheese"};
        
        pageContext.setAttribute("toppings", toppingsArray);
        
        return SKIP_BODY;
    }
}

package ch03;

import java.io.*;
import java.util.*;
import ch03.ch03_06;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.struts.action.*;

public class ch03_04 extends Action 
{
  public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {

        ActionErrors actionerrors = new ActionErrors();
                
        ch03_06 orderForm = (ch03_06)form;
        
        String email = orderForm.getEmail();        
        if(email.trim().equals("")) {
            actionerrors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.noemail"));
        }
        
        String items = orderForm.getItems();        
        if(items.trim().equals("")) {
            actionerrors.add("ActionErrors.GLOBAL_ERROR"new ActionError("error.noitems"));
        }
        
        String[] toppings = orderForm.getToppings();        
        if(toppings == null) {
            actionerrors.add("ActionErrors.GLOBAL_ERROR"new ActionError("error.notoppings"));
        }
            
        if(actionerrors.size() != 0) {            
            saveErrors(request, actionerrors);
            return new ActionForward(mapping.getInput());            
        }
        return mapping.findForward("OK");
    }
}

A Full Struts Application

           
       

Struts Flow

Struts Flow Diagram


Struts Flow Diagram :




Struts working:

Process flow:
web.xml : Whenever the container gets start up the first work it does is to check the web.xml file and determine what struts action Servlets exist. The container is responsible for mapping all the file request to the correct action Servlet.
A Request : This is the second step performed by the container after checking the web.xml file. In this the user submits a form within a browser and the request is intercepted by the controller.
The Controller : This is the heart of the container. Most Struts application will have only one controller that is ActionServlet which is responsible for directing several Actions. The controller determines what action is required and sends the information to be processed by an action Bean. The key advantage of having a controller is its ability to control the flow of logic through the highly controlled, centralized points.
struts.config.xml : Struts has a configuration file to store mappings of actions. By using this file there is no need to hard code the module which will be called within a component. The one more responsibility of the controller is to check the struts.config.xml file to determine which module to be called upon an action request. Struts only reads the struts.config.xml file upon start up.
Model : The model is basically a business logic part which takes the response from the user and stores the result for the duration of the process. This is a great place to perform the preprocessing of the data received from request. It is possible to reuse the same model for many page requests. Struts provides the ActionForm and the Action classes which can be extended to create the model objects.
View : The view in struts framework is mainly a jsp page which is responsible for producing the output to the user.
Struts tag libraries : These are struts components helps us to integrate the struts framework within the project's logic. These struts tag libraries are used within the JSP page. This means that the controller and the model part can't make use of the tag library but instead use the struts class library for strut process control.
Property file : It is used to store the messages that an object or page can use. Properties files can be used to store the titles and other string data. We can create many property files to handle different languages. 
Business objects :  It is the place where the rules of the actual project exists. These are the modules which just regulate the day- to- day site activities.
The Response : This is the output of the View JSP object.