Understanding Struts Controller: Definition: A Framework Is A Collection of

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Definition: A framework is a collection of classes and applications, libraries of SDKs and APIs

to help the different components all work together.

Definition: SDK is short for Software Development Kit and it's basically a library of software that helps
you develop applications and utilities. It will include an API or two, some utilities applications and
probably an installer. There will also be extensive documentation and examples.

 Struts Architecture
Struts is an open source framework used for developing J2EE web applications using Model
View Controller (MVC) design pattern. It uses and extends the Java Servlet API to encourage
developers to  adopt an MVC architecture.
  Struts is a light weight package.It consists of 5 core packages and 5 tag lig directories.
 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.

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 (for
Welcome.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


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.

In this lesson you learned how to create Action Class and add the mappings in the struts-
config.xml. Our Action Class returns the ActionForward  mapping of the TestAction.jsp.
 

Hibernate
Hibernate is an open-source object-relational mapping tool (ORM) that lets you develop
persistent classes and objects in a relationa database using following common Java idiom such as
- association, inheritance, polymorphism, composition and the Java collections framework. It
provides facilities for database connection pooling, data retrieval and update, transaction
management, programmatic queries, as well as entity
relationship management. In addition, it allows transparent persistence that enables the
applications to switch any database.

Hibernate is a better and an effective way to interact with a database. It provides an easyto- use
and powerful object-relational persistence framework for Java applications. It can be used in
Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session
beans.

Hibernate also supports persisting objects for collections and object relations providing a rich
data query language to retrieve objects from the database that significantly reduce the
development time. It maps the Java classes to
the database tables. It is most useful with object-oriented domain modes and business logic in the
Java-based middle-tier.

Features of Hibernate

Some of the main features of hibernate are listed below:

 Hibernate works with classes and objects instead of queries and result sets. It reduces the
development time as it supports inheritance, polymorphism, composition and the Java
collection framework. So it is fully Object Oriented tool with less procedural.
 Hibernate generates SQL expressions for Java. It relieves you from manual JDBC result
set handling and object conversion, and keeps your application portable to all SQL
databases.
 It handles all create-read-updatedelete (CRUD) operations using simple API, and
generates DDL scripts to create DB schema (tables, constraints,
sequences).
 Hibernate is Free under LGPL. It can be used to develop/package and distribute the
applications for free.
 Hibernate XML binding enables data to be represented as XML and POJOs
interchangeably.
 Hibernate offers full-featured query options, through which you can write plain SQL,
object-oriented HQL (Hibernate Query Language), or create programatic Criteria and
Example
queries.
 It provides filters for working with temporal (historical), regional or authorized data as
well as runtime performance monitoring via JMX or local Java API, including a second-
level cache
browser.
 Hibernate not only supports higher versions of JDK but also runs perfectly with JDK 1.2
supporting automatic generation of primary key.
 Hibernate is released under the GNU Public License, which can be used in all open
source and commercial applications without limitations. It supports for a wide range of
databases, including Oracle and DB2, Sybase as well as
popular open source databases such as PostgreSQL and MySQL.

Hibernate is a popular open source object relational mapping tool for a Java™ environment.
Object relational mapping refers to the technique of mapping the data representation from an
object model to a relational data model with a SQL-based schema. What this means is that
Hibernate provides you with one more level of abstraction when interacting with a database.

Hibernate is flexible and supports several approaches. On one end, using the minimum subset of
the Hibernate API, it can be used simply for interacting with a database, in which case the
application will have to provide its own connection and manage its own transactions; which
middleware such as WebSphere Application Server takes care of. On the other end, you can use
the complete version of Hibernate even if you aren't running middleware, in which case you
supply Hibernate with the database configuration information, and it will not only create and
manage the connections for you, but it will also manage transactions by delegating them to the
underlying database.

To use Hibernate, you create Java classes that represent tables in a database and then map
instance variables in a class with columns in the database. You can then call methods on
Hibernate to select, insert, update, and delete records in the underlying table, rather than create
and execute queries yourself, as you typically would.

Hibernate architecture has three main components:

 Connection management
Since opening and closing the connection is the most expensive part of interacting with a
database, you will want to pool and reuse your database connection.
 Transaction management
A transaction is used when you want to execute more than one query in one batch; the result
being either that everything within the transaction succeeds or everything fails.
 Object relational mapping
This is the part where a given Java object Hibernate inserts or updates data; for example, when
you pass instance of an object to a Session.save() method, Hibernate will read the state of
instance variables of that object, and then create and execute the necessary query. In the case
of a select query, objects representing ResultSets will be returned.

Hibernate is very flexible and provides different approaches for how these components should be
used:

 "Lite" architecture
Use when you only want to use the Hibernate object relational mapping component. In this
case, you will need to implement connection and transaction management yourself, for
example, with WebSphere Application Server.
 "Full cream" architecture
Use when you want to implement all three Hibernate components. Hibernate will manage
connections for you when you provide it with connection information like driver class name,
user name, password, and so on, through XML configuration. When managing transactions, you
can call begin, commit, and rollback methods on a Hibernate object.

Hibernate is very good tool when it comes to object relational mapping, but in terms of
connection management and transaction management, it is lacking in performance and
capabilities. Fortunately, we can mix Hibernate's object relational mapping with the connection
and transaction management of WebSphere Application Server to create very powerful
application.

This article assumes a basic knowledge of Hibernate, Enterprise JavaBean (EJB) components,
and Struts. If you are new to Hibernate, refer to Object relational mapping without container,
which discusses how to use Hibernate for simple insert, update, and delete operations.

Spring :

Developed by Rod Johnson and Jurgen Hoeller and the spring framework is an open source
application framework that solves many problems of J2EE. It has many features that can be used
in a variety of Java environments except the classic J2EE. It is based on Java Bean configuration
management with Inversion of control principle (IoC). Spring uses its IoC container as the
principal building block for a comprehensive solution that reflects all architectural features. Its
unique data access system with a simple JDBC framework improves its productivity with less
error. Its AOP program written in standard Java provides better transaction management services
and also enables it for different applications.

Hibernate:
It’s a Java framework that provides object or relational mapping mechanism that helps in
determining how Java objects are stored and updated. It also offers query service for Java and
helps in developing within the SQL and JDBC environment, and following some common Java
idioms like inheritance, polymorphism, composition and collection. This kind of framework set
up an easy way between the Java objects and the relational database.

Struts:

This is an open-source framework that in combination with standard Java technologies like Java
Servlets, Java Beans, XML helps in effective development of web application. Struts framework
illustrates all the related issues that engineers face while building large-scale web applications. It
is widely used in the development of application architecture based on the classic Model-View-
Controller (MVC) design paradigm.

what is the purpose and activity of SessionFactory in hibernate?


#1

To Create Session object to use hibernate in an


application SessionFactory is required.
When buildSessionFactory()method is called hibernate
decides about various sql statements,that has to be used
to
access various tables and creates SeessionFactory object.
This operation is expensive and it should be used only
once.

Q: What is Struts?
A: The core of the Struts framework is a flexible control layer based on standard technologies
like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons
packages. Struts encourages application architectures based on the Model 2 approach, a variation
of the classic Model-View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies to provide
the Model and the View. For the Model, Struts can interact with standard data access
technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate,
iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages,
including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.

The Struts framework provides the invisible underpinnings every professional web application
needs to survive. Struts helps you create an extensible development environment for your
application, based on published standards and proven design patterns.

Q: What is Jakarta Struts Framework?


A: Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for
the development of web based applications. Jakarta Struts is robust architecture and can be used
for the development of application of any size. Struts framework makes it much easier to design
scalable, reliable Web applications with Java.

Q: What is ActionServlet?
A: The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the
Jakarta Struts Framework this class plays the role of controller. All the requests to the server
goes through the controller. Controller is responsible for handling all the requests.

Q: How you will make available any Message Resources Definitions file to the Struts
Framework Environment?
A: T Message Resources Definitions file are simple .properties files and these files contains the
messages that can be used in the struts project. Message Resources Definitions files can be added
to the struts-config.xml file through {message-resources /} tag.
Example:

{message-resources parameter=\"MessageResources\” /}.

Q: What is Action Class?


A: The Action Class is part of the Model and is a wrapper around the business logic. The
purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the
Action, we need to Subclass and overwrite the execute() method. In the Action Class all the
database/business processing are done. It is advisable to perform all the database related stuffs in
the Action Class. 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.

Q: What is ActionForm?
A: An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm
maintains the session state for web application and the ActionForm object is automatically
populated on the server side with data entered from a form on the client side.
Q: What is Struts Validator Framework?
A: Struts Framework provides the functionality to validate the form data. It can be use to validate
the data on the users browser as well as on the server side. Struts Framework emits the java
scripts and it can be used validate the form data on the client browser. Server side validation of
form can be accomplished by sub classing your From Bean with DynaValidatorForm class.
The Validator framework was developed by David Winterfeldt as third-party add-on to Struts.
Now the Validator framework is a part of Jakarta Commons project and it can be used with or
without Struts. The Validator framework comes integrated with the Struts Framework and can be
used without doing any extra settings.

Q: Give the Details of XML files used in Validator Framework?


A: The Validator Framework uses two XML configuration files validator-rules.xml and
validation.xml. The validator-rules.xml defines the standard validation routines, these are
reusable and used in validation.xml. to define the form specific validations. The validation.xml
defines the validations applied to a form bean.

Q: How you will display validation fail errors on jsp page?


A: Following tag displays all the errors:
{html:errors/}

Q: How you will enable front-end validation based on the xml in validation.xml?
A: The {html:javascript} tag to allow front-end validation based on the xml in validation.xml.
For example the code: {html:javascript formName=\"logonForm\” dynamicJavascript=\"true\”
staticJavascript=\"true\” /} generates the client side java script for the form \"logonForm\” as
defined in the validation.xml file. The {html:javascript} when added in the jsp file generates the
client site validation script.

Q: How to get data from the velocity page in a action class?


A: We can get the values in the action classes by using data.getParameter(\"variable name
defined in the velocity page\");

Q: What is Struts?
A: The core of the Struts framework is a flexible control layer based on standard technologies
like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons
packages. Struts encourages application architectures based on the Model 2 approach, a variation
of the classic Model-View-Controller (MVC) design paradigm.

Struts provides its own Controller component and integrates with other technologies to provide
the Model and the View. For the Model, Struts can interact with standard data access
technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate,
iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages,
including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.

The Struts framework provides the invisible underpinnings every professional web application
needs to survive. Struts helps you create an extensible development environment for your
application, based on published standards and proven design patterns.
Q: What is Jakarta Struts Framework?
A: Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for
the development of web based applications. Jakarta Struts is robust architecture and can be used
for the development of application of any size. Struts framework makes it much easier to design
scalable, reliable Web applications with Java.

Q: What is ActionServlet?
A: The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the
Jakarta Struts Framework this class plays the role of controller. All the requests to the server
goes through the controller. Controller is responsible for handling all the requests.

Q: How you will make available any Message Resources Definitions file to the Struts
Framework Environment?
A: T Message Resources Definitions file are simple .properties files and these files contains the
messages that can be used in the struts project. Message Resources Definitions files can be added
to the struts-config.xml file through {message-resources /} tag.
Example:

{message-resources parameter=\"MessageResources\” /}.

Q: What is Action Class?


A: The Action Class is part of the Model and is a wrapper around the business logic. The
purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the
Action, we need to Subclass and overwrite the execute() method. In the Action Class all the
database/business processing are done. It is advisable to perform all the database related stuffs in
the Action Class. 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.

Q: What is ActionForm?
A: An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm
maintains the session state for web application and the ActionForm object is automatically
populated on the server side with data entered from a form on the client side.

Q: What is Struts Validator Framework?


A: Struts Framework provides the functionality to validate the form data. It can be use to validate
the data on the users browser as well as on the server side. Struts Framework emits the java
scripts and it can be used validate the form data on the client browser. Server side validation of
form can be accomplished by sub classing your From Bean with DynaValidatorForm class.
The Validator framework was developed by David Winterfeldt as third-party add-on to Struts.
Now the Validator framework is a part of Jakarta Commons project and it can be used with or
without Struts. The Validator framework comes integrated with the Struts Framework and can be
used without doing any extra settings.
Q: Give the Details of XML files used in Validator Framework?
A: The Validator Framework uses two XML configuration files validator-rules.xml and
validation.xml. The validator-rules.xml defines the standard validation routines, these are
reusable and used in validation.xml. to define the form specific validations. The validation.xml
defines the validations applied to a form bean.

Q: How you will display validation fail errors on jsp page?


A: Following tag displays all the errors:
{html:errors/}

Q: How you will enable front-end validation based on the xml in validation.xml?
A: The {html:javascript} tag to allow front-end validation based on the xml in validation.xml.
For example the code: {html:javascript formName=\"logonForm\” dynamicJavascript=\"true\”
staticJavascript=\"true\” /} generates the client side java script for the form \"logonForm\” as
defined in the validation.xml file. The {html:javascript} when added in the jsp file generates the
client site validation script.

Q: How to get data from the velocity page in a action class?


A: We can get the values in the action classes by using data.getParameter(\"variable name
defined in the velocity page\");

Struts
Struts is a open source framework which make building of the web applications easier based
on the java Servlet and JavaServer pages technologies.

Struts framework was created by Craig R. McClanahan and donated to the Apache Software
Foundation in 2000. The Project now has several committers, and many developers are
contributing to overall to the framework.

Developing web application using struts frame work is fairly complex, but it eases things
after it is setup. It encourages software development following the MVC design pattern.
Many web applications are JSP-only or Servlets-only. With JSP and Servlets, Java code is
embedded in the HTML code and the Java code calls println methods to generate the HTML
code respectively. Both approaches have their advantages and drawbacks; Struts gathers
their strengths to get the best of their association.

Struts is based on Model-View-Controller (MVC) design paradigm, it is an implementation of


JSP Model 2 Architecture. For more of Model-View-Controller (MVC) click here.

Consists of 8 Top-Level Packagesand approx 250 Classes and Interfaces.

Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2
design. This definition implies that Struts is a framework, rather than a library, but Struts
also contains an extensive tag library and utility classes that work independently of the
framework.

The overview of struts


Client browser
An HTTP request from the client browser creates an event. The Web container will respond
with an HTTP response.

Controller
The controller is responsible for intercepting and translating user input into actions to
be performed by the model. The controller is responsible for selecting the next view based
on user input and the outcome of model operations.The Controller receives the request from
the browser, and makes the decision where to send the request. With Struts, the Controller
is a command design pattern implemented as a servlet. The struts-config.xml file configures
the Controller.

Business logic
The business logic updates the state of the model and helps control the flow of the
application. With Struts this is done with an Action class as a thin wrapper to the actual
business logic.

Model
A model represents an application’s data and contains the logic for accessing and
manipulating that data. Any data that is part of the persistent state of the application should
reside in the model objects. The business objects update the application state. ActionForm
bean represents the Model state at a session or request level, and not at a persistent level.
Model services are accessed by the controller for either querying or effecting a change in the
model state. The model notifies the view when a state change occurs in the model.The JSP
file reads information from the ActionForm bean using JSP tags.

View
The view is responsible for rendering the state of the model. The presentation semantics are
encapsulated within the view, therefore model data can be adapted for several different
kinds of clients.The view modifies itself when a change in the model is communicated to the
view. A view forwards user input to the controller.The view is simply a JSP file. There is no
flow logic, no business logic, and no model information -- just tags. Tags are one of the
things that make Struts unique compared to other frameworks like Velocity.

The Model component of MVC provides data from a database and saves it to the data store. Data
access and validation are also parts of the Model component. In View, the user is able to view the
application, and takes inputs and forwards the request to the controller. The response from the
controller is then displayed to the user. The final component, Controller, receives requests from the
client and executes the applicable logic from the Model, before generating the output using the View
component.

Read more: Struts Tutorial for Beginners | eHow.com http://www.ehow.com/how_6730075_struts-


tutorial-beginners.html#ixzz1E6Kgo5ZH
Global Action Forwards and Action
Mappings
What is an action forward?
A action forward can be used to forward to a jsp or action mapping. There are two different
action forwards. The global action forward and the local action forward. You can access a global
action forward on each jsp or action class. A local action forward can only be accessed by the
assigned action class.

What is a action mapping?


The action mapping is the heart of struts. It managed all actions between the application and the
user. You can define which action will be executed by creating a action mapping.

The diagram show you, how the application server manage the request of the index.jsp or a non
existing action mapping.

What is struts flow? Explain in detail

all the above answers are can be fitted in the what is struts?

Struts is based on MVC architecuture. Flow of struts is as follows if my understanding of


question is correct

1. request comes.

2. corrosponding action class will be searched in the struts.xml

3. mapped form-bean will be populated with data.


4. execute method of mapped action servlet will be executed and result will be mapped in
struts.xml with <forward> tag.

5. mapped jsp/html page with forward will be displayed.

Struts Flow-How Struts Works?

Struts Flow start with ActionServlet then call to process() method of RequestProcessor.

Step 1. Load ActionServlet using load-on-startup and do the following tasks.

Any struts web application contain the ActionServlet configuration in web.xml file.
On load-on-startup the servlet container Instantiate the ActionServlet .
First Task by ActionServlet : The ActionServlet takes the Struts Config file name as an init-
param.
At startup, in the init() method, the ActionServlet reads the Struts Config file and load into
memory.
Second Task by ActionServlet : If the user types http://localhost:8080/app/submitForm.do in
the browser URL bar, the URL will be intercepted and processed by the ActionServlet since the
URL has a pattern *.do, with a suffix of "do". Because servlet-mapping is
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Third Task by ActionServlet : Then ActionServlet delegates the request handling to another
class called RequestProcessor by invoking its process() method.

<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

Step 2. ActionServlet calls process() method of RequestProcessor.

The RequestProcessor does the following in its process() method:


a) The RequestProcessor looks up the configuration file for the URL pattern /submitForm (if the
URL is http://localhost:8080/app/submitForm.do). and and finds the XML block
(ActionMapping).

ActionMapping from struts-config.xml

<action path="/submitForm"
type="com.techfaq.emp.EmpAction"
name="EmpForm"
scope="request"
validate="true"
input="EmpForm.jsp">
<forward name="success"
path="success.jsp"/>
<forward name="failure" path="failure.jsp" />
</action>

b) The RequestProcessor instantiates the EmpForm and puts it in appropriate scope – either
session or request.
The RequestProcessor determines the appropriate scope by looking at the scope attribute in the
same ActionMapping.
c) RequestProcessor iterates through the HTTP request parameters and populates the EmpForm.
d) the RequestProcessor checks for the validateattribute in the ActionMapping.
If the validate is set to true, the RequestProcessor invokes the validate() method on the
EmpForm instance.
This is the method where you can put all the html form data validations.
If Validate fail the RequestProcessor looks for the input attribute and return to JSP page
mentioned in input tag.
If Validate pass goto next step.
e) The RequestProcessor instantiates the Action class specified in the ActionMapping
(EmpAction) and invokes the execute() method on the EmpAction instance.

signature of the execute method is

public ActionForward execute(ActionMapping mapping,


ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
return mapping.findForward("success");
}
f) In return mapping.findForward("success")
RequestProcessor looks for the success attribute and forward to JSP page mentioned in success
tag. i.e success.jsp.
In return mapping.findForward("failure")
RequestProcessor looks for the failure attribute and forward to JSP page mentioned in failure
tag. i.e. failure.jsp

Struts

What Is the Struts Framework?

The Struts Framework is a standard for developing well-architected Web applications. It has the
following features:

 Open source
 Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three
levels:
o Model: application state
o View: presentation of data (JSP, HTML)
o Controller: routing of the application flow
 Implements the JSP Model 2 Architecture
 Stores application routing information and request mapping in a single core file, struts-
config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the
developer.

Struts is a popular open source framework from Apache Software Foundation to


build web applications that integrate with standard technologies such as Servlets,
Java Beans and Java Server pages.

Struts offers many benefits to the web application developer,including the Model-
View-Controller (MVC) design patterns (best practice) in web applications.

The Model-View-Controller paradigm applied to web applications lets you separately


display code (for example, HTML and tag libraries) from flow control logic (action
classes) from the data model to be displayed and updated by the application.

Struts offers a set of tag libraries to support the faster development of the different
layers of the web application.

The basic idea of the MVC architecture is to divide the application into three layers:
Model that represents the data layer, a view layer that represents the data
processed by the model component; and a Controller component that is responsible
for interaction between the model and the controller.

So when we say Struts is an MVC framework for web based applications, we


actually mean that it facilitates the rapid development of applications by providing a
Controller that helps interaction between the model and the view so that an
application developer has not to worry about how to make view and the model
independent of each other and yet exist in coordination.

Struts Home http://struts.apache.org

Popular Struts Tutorial

Ttorial Site- Roseindia

Ttorial Site-visualbuilder

Ttorial Site-laliluna

Ttorial Site-exadel.

Table: Important attributes and elements of ActionMapping entry in struts-config.xml

Attribute/Element name Description


The URL path (either path mapping or suffix mapping) for which
Path 
this Action Mapping is used. The path should be unique
Type  The fully qualified class name of the Action
The logical name of the Form bean. The actual ActionForm
associated with this Action Mapping is found by looking in the
Name  Form-bean definition section for a form-bean with the matching
name. This informs the Struts application which action mappings
should use which ActionForms.
Scope  Scope of the Form bean – Can be session or request
Can be true or false. When true, the Form bean is validated on
Validate 
submission. If false, the validation is skipped.
The physical page (or another ActionMapping) to which control
Input 
should be forwarded when validation errors exist in the form bean.
The physical page (or another ActionMapping) to which the control
Forward  should be forwarded when the ActionForward with this name is
selected in the execute method of the Action class.
The ActionMapping section contains the mapping from URL path to an Action class (and also
associates a Form bean with the path). The type attribute is the fully qualified class name of the
associated Action. Each action entry in the action-mappings should have a unique path. This
follows from the fact that each URL path needs a unique handler. There is no facility to associate
multiple Actions with the same path. The name attribute is the name of the Form bean associated
with this Action. The actual form bean is defined in Form bean definition section. Table above
shows all the relevant attributes discussed so far for the action entry in action-mappings section.

//Sample struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config> Form bean Definitions
<form-beans>
<form-bean name="CustomerForm"
type="mybank.example.CustomerForm"/>
<form-bean name="LogonForm"
type="mybank.example.LogonForm"/>
</form-beans> Global Forward Definitions
<global-forwards>
<forward name="logon" path="/logon.jsp"/>
<forward name="logoff" path="/logoff.do"/>
</global-forwards> Action Mappings
<action-mappings>
<action path="/submitDetailForm"
type="mybank.example.CustomerAction"
name="CustomerForm"
scope="request"
validate="true"
input="/CustomerDetailForm.jsp">
<forward name="success"
path="/ThankYou.jsp"
redirect=”true” />
<forward name="failure"
path="/Failure.jsp" />
</action>
<action path=”/logoff” parameter=”/logoff.jsp”
type=”org.apache.struts.action.ForwardAction” />
</action-mappings> Controller Configuration
<controller
processorClass="org.apache.struts.action.RequestProcessor" />
<message-resources parameter="mybank.ApplicationResources"/>
</struts-config> Message Resource Definition
In the ActionMapping there are two forwards. Those forwards are local forwards – which means
those forwards can be accessed only within the ActionMapping. On the other hand, the forwards
defined in the Global Forward section are accessible from any ActionMapping. As you have seen
earlier, a forward has a name and a path. The name attribute is the logical name assigned. The
path attribute is the resource to which the control is to be forwarded. This resource can be an
actual page name as in

<forward name="logon" path="/logon.jsp"/>

or it can be another ActionMapping as in

<forward name="logoff" path="/logoff.do "/>

The /logoff (notice the absence of “.do”) would be another ActionMapping in the struts-
config.xml. The forward – either global or local are used in the execute() method of the Action
class to forward the control to another physical page or ActionMapping.

The next section in the config file is the controller. The controller is optional. Unless otherwise
specified, the default controller is always the org.apache.struts.action.RequestProcessor. There
are cases when you want to replace or extend this to have your own specialized processor. For
instance, when using Tiles (a JSP page template framework) in conjunction with Struts, you
would use TilesRequestProcessor.

The last section of immediate interest is the Message Resource definition. In the ActionErrors
discussion, you saw a code snippet that used a cryptic key as the argument for the ActionError.
We stated that this key maps to a value in a properties file. Well, we declare that properties file
in the struts-config.xml in the Message Resources definition section. The declaration in Listing
above states that the Message Resources Bundle for the application is called
ApplicationResources.properties and the file is located in the java package mybank.

If you are wondering how (and why) can a properties file be located in a java package, recall that
any file (including class file) is a resource and is loaded by the class loader by specifying the
package.
What is HQL?

HQL stands for Hibernate Query Language, and is the data query language that comes with
Hibernate. Hibernate is a Java-based library for accessing relational data. You can download
Hibernate at www.hibernate.org.

HQL is very similar to SQL, but has two powerful benefits:

1. HQL provides one language for accessing different SQL databases, each with its own slightly
different flavor of SQL; and
2. HQL has object oriented extensions which can be very powerful.

A Simple Example: SQL vs HQL

A normal SQL query looks something like this:

SELECT name
FROM customer
WHERE state = "CA"

In HQL, this same query looks something like this:

SELECT cust.name
FROM customer AS cust
WHERE cust.state = "CA"

You might also like