How Does Struts Work - Part - 2


How Struts Works?

The basic purpose of the Java Servlets in struts is to handle requests made by the client or by web browsers. In struts JavaServerPages (JSP) are used to design the dynamic web pages. In struts, servlets helps to route request which has been made by the web browsers to the appropriate ServerPage. The use of servlet as a router helps to make the web applications easier to design, create, and maintain. Struts is purely based on the Model- View- Contoller (MVC) design pattern. It is one of the best and most well developed design patterns in use. By using the MVC architecture we break the processing in three sections named Model, the View, and the Controller. Below we are describing the working of struts.
  1. As we all are well aware of the fact that each application we develop has a deployment descriptor i.e. WEB-INF/web.xml. This is the file which the container reads. This file has all the configuration information which we have defined for our web application. The configuration information includes the index file, the default welcome page, the mapping of our servlets including path and the extension name, any init parameters, information related to the context elements.
    In the file WEB-INF/web.xml of struts application we need to configure the Struts ActionServlet which handles all the request made by the web browsers to a given mapping.  ActionServlet is the central component of the Struts controller. This servlet extends the HttpServlet. This servlet basically performs two important things.
     First is : When the container gets start, it reads the Struts Configuration files and loads it into memory in the init() method. You will know more about the Struts Configuration files below. Second point is: It intercepts the HTTP request in thedoGet() and doPost() method and handles it appropriately.
      
  2. In struts application we have another xml file which is a Struts configuration file named asstruts.config.xml. The name of this file can be changed. The name of the struts configuration file can be configured in the web.xml file. This file is placed under the WEB-INF directory of the web application.  It is an XML document that describes all or part of Struts application. This file has all the information about many types of Struts resources and configures their interaction.  This file is used to associate paths with the controller components of your application., known as Action classes like <action path ="/login" type = "LoginAction">.  This tag tells the StrutsActionServlet that whenever the incoming request is http://myhost/myapp/login.do, then it must invoke the controller component LoginAction. Above, you can see that we have written .doin the URL. This mapping is done to tell the web application that whenever a request is received with the .do extension then it should be appended to the URL.
      
  3. For each action we also have to configure Struts with the names of the resulting pages that will be shown as a result of that action. In our application there can be more than one view which depends on the result of an action. One can be for a success and the other for the failure. If the result action is "success" then the action tells the ActionServlet that the action has been successfully accomplished or vice- versa.  The struts knows how  to forward the specific page to the concerned destination. The model which we want to use is entirely to you, the model is called from within the controller components.
      
  4. Action can also get associate with a JavaBean in our Struts configuration file. Java bean is nothing but a class having getter and setter methods that can be used to communicate between the view and the controller layer. These java beans are validated by invoking the validate()method on the ActionForm by the help of the Struts system. The client sends the request by the normal form submission by using Get or Post method, and the Struts system updates that data in the Bean before calling the controller components.
      
  5. The view we use in the struts can be either Jsp page, Velocity templates, XSLT pages etc. In struts there are set of JSP tags which has been bundled with the struts distribution, but it is not mandatory to use only Jsp tags, even plain HTML files can be used within our Struts application but the disadvantage of using the html is that it can't take the full advantage of all the dynamic features provided in the struts framework.
    The framework includes a set of custom tag libraries that facilitate in creating the user interfaces that can interact gracefully with ActionForm beans. The struts Jsp taglibs has a number of generic and struts specific tags tags which helps you to use dynamic data in your view. These tags helps us to interact with your controller without writing much java code inside your jsp. These tags are used create forms, internally forward to other pages by interacting with the bean and helps us to invoke other actions of the web application.
    There are many tags provided to you in the struts frameworks which helps you in sending error messages, internationalization etc.
     
Note: The points we have described above will be in effect if and only if when the ActionServlet is handling the request. When the request is submitted to the container which call the ActionServlet, make sure that the extension of the file which we want to access should have the extension .do.
   
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.


Understanding Struts Controller

In this section I will describe you the Controller part of the Struts Framework. I will show you how to configure the struts-config.xml file to map the request to some destination servlet or jsp file.

The class org.apache.struts.action.ActionServlet is the heart of the Struts Framework. It is the Controller part of the Struts Framework. ActionServlet is configured as Servlet in the web.xml file as shown in the following code snippets.


<!-- Standard Action Servlet Configuration (with debugging) -->
<servlet>
   <servlet-name>action</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
  <param-name>config</param-name>
  <param-value>/WEB-INF/struts-config.xml</param-value>
  </init-param>
   <init-param>
  <param-name>debug</param-name>
  <param-value>2</param-value>
  </init-param>
  <init-param>
  <param-name>detail</param-name>
  <param-value>2</param-value>
   </init-param>
  <load-on-startup>2</load-on-startup>
</servlet>

  
This servlet is responsible for handing all the request for the Struts Framework, user can map the specific pattern of request to the ActionServlet. <servlet-mapping> tag in the web.xml file specifies the url pattern to be handled by the servlet. By default it is *.do, but it can be changed to anything. Following code form  the web.xml file shows the mapping.

 

<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
  <servlet-name>action</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

The above mapping maps all the requests ending with .do to the ActionServlet. ActionServlet uses the configuration defined in struts-config.xml file to decide the destination of the request. Action Mapping Definitions (described below) is used to map any action. For this lesson we will create Welcome.jsp file and map the "Welcome.do" request to this page.
Welcome.jsp
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html locale="true">
<head>
   <title><bean:message key="welcome.title"/></title>
   <html:base/>
</head>
  <body bgcolor="white">
  <h3><bean:message key="welcome.heading"/></h3>
  <p><bean:message key="welcome.message"/></p>
</body>
</html:html>
Forwarding the Welcome.do request to Welcome.jsp
The "Action Mapping Definitions" is the most important part in the struts-config.xml. This section takes a form defined in the "Form Bean Definitions" section and maps it to an action class.
Following code under the <action-mappings> tag is used to forward the request to the Welcome.jsp.
<action  path="/Welcome"
  forward="/pages/Welcome.jsp"
/>
  
To call this Welcome.jsp file we will use the following code.
<html:link page="/Welcome.do">First Request to the controller</html:link>
Once the use clicks on on First Request to the controller link on the index page, request (forWelcome.do) is sent to the Controller and the controller forwards the request to Welcome.jsp. The content of Welcome.jsp is displayed to the user.

 Understanding Struts Action Class 

In this lesson I will show you how to use Struts Action Class and forward a jsp file through it. 

What is Action Class?
An Action class in the struts application extends Struts 'org.apache.struts.action.Action" Class. Action class acts as wrapper around the business logic and provides an inteface to the application's Model layer. It acts as glue between the View and Model layer. It also transfers the data from the view layer to the specific business process layer and finally returns the procssed data from business layer to the view layer.
An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it. Then the struts controller (ActionServlet) slects an appropriate Action and creates an instance if necessary, and finally calls execute method.
To use the Action, we need to  Subclass and overwrite the execute() method. In the Action Class don't add the business process logic, instead move the database and business process logic to the process or dao layer.
The ActionServlet (commad) passes the parameterized class to Action Form using the execute()method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.
Developing our Action Class?
Our Action class (TestAction.java) is simple class that only forwards the TestAction.jsp. Our Action class returns the ActionForward  called "testAction", which is defined in the struts-config.xml file (action mapping is show later in this page). Here is code of our Action Class:
TestAction.java
package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action
{
  public ActionForward execute(
  ActionMapping mapping,
  ActionForm form,
  HttpServletRequest request,
  HttpServletResponse response) throws Exception{
  return mapping.findForward("testAction");
  }
}

Understanding
 Action Class
Here is the signature of the Action Class.
public ActionForward execute(ActionMapping mapping,
                             ActionForm form,
                             javax.servlet.http.HttpServletRequest request,
                             javax.servlet.http.HttpServletResponse response)
                      throws java.lang.Exception
Action Class process the specified HTTP request, and create the corresponding HTTP response (or forward to another web component that will create it), with provision for handling exceptions thrown by the business logic. Return an ActionForward instance describing where and how control should be forwarded, or null if the response has already been completed.
Parameters:
mapping - The ActionMapping used to select this instance
form - The optional ActionForm bean for this request (if any)
request - The HTTP request we are processing
response - The HTTP response we are creating
Throws:
Action class throws java.lang.Exception - if the application business logic throws an exception
Adding the Action Mapping in the struts-config.xml
To test the application we will add a link in the index.jsp 
<html:link page="/TestAction.do">Test the Action</html:link>
Following code under the <action-mappings> tag is used to for mapping the TestAction class.
   <action
      path="/TestAction"
      type="roseindia.net.TestAction">
      <forward name="testAction" path="/pages/TestAction.jsp"/>
   </action>          
To test the new application click on Test the Action link on the index page. The content of TestAction.jsp should be displayed on the user browser.
 

Comments

Popular posts from this blog

Servlets, JSP, Struts and MVC

Hibernate Avg() Function (Aggregate Functions)

Hibernate Count Query