DTD-Entities

Entities are variables used to define shortcuts to standard text or special characters. Entity references are references to entities Entities can be declared internally or externally.

Internal Entity Declaration

Syntax

<!ENTITY entity-name "entity-value">
DTD Example:
<!ENTITY name "Amit">
<!ENTITY company "RoseIndia">
XML example:
<Profile>&name;&company;</Profile>
Note: An entity has three parts: an ampersand (&), an entity name, and a semicolon (;).

An External Entity Declaration

Syntax

<!ENTITY entity-name SYSTEM "URI/URL">
DTD Example:
<!ENTITY name SYSTEM "http://www.roseindia.net/entities.dtd">
<!ENTITY company SYSTEM "http://www.roseindia.net/entities.dtd">
XML example:
<Profile>&name;&company;</Profile>

DTD-Attributes

In a DTD, attributes are declared with an ATTLIST declaration.
Declaring Attributes
The ATTLIST declaration defines the element having a attribute with attribute name , attribute type , and  attribute default  value. An attribute declaration has the following syntax:



<!ATTLIST element-name attribute-name attribute-type default-value>
DTD example:
<!ATTLIST reciept type CDATA "check">
XML example:
<reciept type="check" />
Attribute-type
The attribute-type can be one of the following:
Type Description
CDATA
The value is character data
(en1|en2|..)
The value must be one from an enumerated list
ID
The value is a unique id
IDREF
The value is the id of another element
IDREFS
The value is a list of other ids
NMTOKEN
The value is a valid XML name
NMTOKENS
The value is a list of valid XML names
ENTITY
The value is an entity
ENTITIES
The value is a list of entities
NOTATION
The value is a name of a notation
xml:
The value is a predefined xml value
Default-value
The default-value can be one of the following:
Value Explanation
value
The default value of the attribute
#REQUIRED
The attribute is required
#IMPLIED
The attribute is not required
#FIXED value
The attribute value is fixed

A Default Attribute Value
DTD Example:
<!ELEMENT Scale EMPTY>
<!ATTLIST Scale length CDATA "0">
In the example above, the DTD defines a "Scale" element  to be  empty with a "length " attribute of  type CDATA . If no length is specified, it has a default value of 0.
Valid XML:
<Scale length ="100" />
REQUIRED
Syntax
<!ATTLIST element-name attribute_name attribute-type #REQUIRED>
DTD Example
<!ATTLIST person number CDATA #REQUIRED>
Valid XML:
<person id="5677" />
Invalid XML:
<person />
Use the #REQUIRED keyword if you don't have an option for a default value, but still want to force the attribute to be present.
IMPLIED
Syntax
<!ATTLIST element-name attribute-name attribute-type #IMPLIED>
DTD Example
<!ATTLIST emergency no. CDATA #IMPLIED>
Valid XML:
<emergency no.="555-667788" />
Valid XML:
<emergency/>
Use the #IMPLIED keyword if you don't want to force the author to include an attribute, and you don't have an option for a default value.
FIXED
Syntax
<!ATTLIST element-name attribute-name attribute-type #FIXED "value">
DTD Example
<!ATTLIST Client CDATA #FIXED "RoseIndia">
Valid XML:
<Client ="RoseIndia" />
Invalid XML:
<Client="LotusIndia" />
Use the #FIXED keyword when you want an attribute to have a fixed value without allowing the author to change it. If an author includes another value, the XML parser will return an error.
Enumerated Attribute Values
Syntax
<!ATTLIST element-name attribute-name (en1|en2|..) default-value>
DTD Example
<!ATTLIST reciept type (check|cash) "cash">
XML example:
<reciept type="check" />
or
<reciept type="cash" />
Use enumerated attribute values when you want the attribute value to be one of a fixed set of legal values.

DTD - XML Constituent

The constituent components of XML DTD Documents.
 DTDs are made up by the following integrants:
  • Elements
  • Attributes
  • Entities
  • PCDATA
  • CDATA
Brief explanation of each of the integrants :
Elements
Elements are the main constituent components of both XML documents.
Elements can contain text, other elements, or be empty eg..
<To>Rohan</To>
<From>Amit</From>

Attributes
Attributes provide extra information about elements.
Attributes are always placed inside the opening tag of an element. Attributes always come in name/value pairs. The following "img" element has additional information about a source file:
<img src="computer.gif" />
The name of the element is "img". The name of the attribute is "src". The value of the attribute is "computer.gif". Since the element itself is empty it is closed by a " /".
Entities:
Entities are expanded when a document is parsed by a XML parser. Some characters have a special meaning in XML, like the less than sign (<) that defines the start of an XML tag , the greater than sign (>) that defines the end of a XML tag.
The following entities are predefined in XML:
Entity References    Character
&lt;     <
&gt;     >
&amp;    &
&quot;     "
&apos;     '
 
PCDATA:
PCDATA means parsed character data. It can be thought as the character data ( text ) found between the start tag and the end tag of a XML element.
PCDATA is a text to be parsed by a parser. The text is checked by the parser for entities and markup.
Tags inside the text will be treated as markup and entities will be expanded. However, parsed character data should not contain any &, <, or > characters. These should  be represented by the &amp , &lt, and &gt entities, respectively.
CDATA:
CDATA is character data that will NOT be parsed by a parser. Tags inside the text will NOT be treated as markup and entities will not be expanded.

DTD:Document Type Definition

A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines the document structure with a list of legal    elements and attributes.
A DTD can be defined  inside a  XML document, or a  external reference can be declared .

Internal DTD 

If the DTD is defined inside the XML document, it should be wrapped in a DOCTYPE definition with the following syntax:
<!DOCTYPE root-element [element-declarations]>



Example of a XML document with an internal DTD: E-mail.xml
<?xml version="1.0"?>
<!DOCTYPE E-mail[
  <!ELEMENT E-mail (To,From,subject,Body)>
  <!ELEMENT To (#PCDATA)>
  <!ELEMENT From (#PCDATA)>
  <!ELEMENT Subject (#PCDATA)>
  <!ELEMENT Body (#PCDATA)>
]>
<E-mail>
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will 
catch u  tonight</Body>
</E-mail>

Open the file E-mail.xml in a web-browser . you will see  the following :
External DTD 
If the DTD is defined in an external file, it should be wrapped in a DOCTYPE definition with the following syntax:
<!DOCTYPE root-element SYSTEM "filename">
This is the same XML document as above,(but with an external DTD ) : E-mail.xml
<?xml version="1.0"?>
<!DOCTYPE E-mail SYSTEM 
"E-mail.dtd">
<E-mail>
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will 
catch u  tonight</Body>
</E-mail>
And this is the file "E-mail.dtd" which contains the following DTD:
<!ELEMENT E-mail (To,From,subject,Body)>
<!ELEMENT To (#PCDATA)>
<!ELEMENT From (#PCDATA)>
<!ELEMENT Subject (#PCDATA)>
<!ELEMENT Body (#PCDATA)>

Open the file E-mail.xml in a web-browser. It will display the following :
Importance of a DTD?
  • With a DTD, a XML file carries a description of its own format.
  • With a DTD, independent groups of people can agree to use a standard DTD for interchanging data.
  •  User application can use a standard DTD to verify that the data he receives from the outside world is valid.
  • User can also use a DTD to verify his own data.

XML Validation

XML with correct syntax is Well Formed XML.
XML validated against a DTD or a Schema  is a Valid XML.
Well Formed XML Documents
A "Well Formed" XML document has correct XML syntax.
A "Well Formed" XML document is a document that conforms to the XML syntax rules that were described in the previous chapters:
  • XML documents must have a root element
  • XML elements must have a closing tag
  • XML tags are case sensitive
  • XML elements must be properly nested
  • XML attribute values must always be quoted

<?xml version="1.0" encoding="ISO-8859-1"?>
<E-mail>
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will catch u  tonight</Body>
</E-mail>

Valid XML Documents:
A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules of a Document Type Definition (DTD) or a XML Schema .
The following xml document is validated against a DTD , notice the highlighted text.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE e-mail SYSTEM "InternalE-mail.dtd">
<E-mail>
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will catch u  tonight</Body>
</E-mail

XML DTD
A DTD defines the legal elements of an XML document. The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements.
XML Schema 
XML Schema is an XML based alternative to DTD .W3C supports an alternative to DTD called XML Schema.

XML Syntax Rules

The syntax  rules  for  XML are very simple and strict. These  are  easy to learn and  use. Because of this, creating software that can read and manipulate XML is very easy. Xml enables an user to create  his own tags.
Note - XML documents use a self-describing and simple syntax
Let's develop a simple XML document :
<?xml version="1.0" encoding="ISO-8859-1"?>
<E-mail>
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will catch u  tonight</Body>
</E-mail>

The XML declaration:  Always the first line in the xml document: 
The XML declaration should always be included. It defines the XML version and the character encoding used in the document. In this case the document conforms to the 1.0 specification of  XML and uses the ISO-8859-1 (Latin-1/West European) character set.
<?xml version="1.0" encoding="ISO-8859-1"?>
Root Element: The next line defines the first element of the document . It is called as the root element 
<E-mail>
Child Elements: The next 4 lines describe the four child elements of the root (To, From, Subject and Body).
<To>Rohan</To>
<From>Amit</From>
<Subject>Surprise....</Subject>
<Body>Be ready for a cruise...i will catch u  tonight</Body>
And finally the last line defines the end of the root element .
</E-mail>
you may feel from this example that the XML document contains a  E-mail To Rohan  From Amit. Don't you agree that XML is quite self-descriptive?
Now let's discuss its syntax-rules which are very simple to learn.

All XML elements must have a closing tag

In XML all the elements must have a closing tag like this:
<To>Rohan</To>
<From>Amit</From>

XML tags are case sensitive

XML tags are case sensitive. The tag <To> is different from the tag <to>.Hence the opening and closing tags must  be written with the same case:
<To>Rohan</To>
<to>Rohan</to>

XML Elements Must be Properly Nested

Improper nesting of tags makes no sense to XML. In XML all elements must be properly nested within each other like this in a logical order:
<b><i>Hi , how are you.....</i></b>

XML Documents Must Have a Root Element

All XML documents must contain a single tag pair to define a root element. All other elements must be written within this root element. All elements can have sub elements called as child elements. Sub elements must be correctly nested within their parent element:
<root>
  <child>
    <subchild>.....</subchild>
  </child>
</root> 

Always Quote the XML Attribute Values 

In XML the attribute value must always be quotedXML elements can have attributes in name/value pairs just like in HTML. Just look the two XML documents below.  
The error in the first document is that the date and version attributes are not quoted .
<?xml version=1.0 encoding="ISO-8859-1"?>
<E-mail date=12/11/2002/>
The second document is correct:
<?xml version="1.0" encoding="ISO-8859-1"?>
<E-mail date="12/11/2002"/>

With XML, White Space is Preserved

With XML, the white space in a document is  preserved .
So a sentence like this :   Hello              How are you, will be displayed like this:
Hello              How are you,

Comparing XML with HTML

The Main Differences Between XML and HTML

XML is designed to carry data.

XML describes and focuses on the data while HTML only displays and focuses on how data looks. HTML is all about displaying information but XML is all about describing information. In current scenario XML is the most common tool for data manipulation and data transmission.

XML is used to store data in files and for sharing data between diverse applications. Unlike HTML document where data and display logic are available in the same file, XML hold only data. Different presentation logics could be applied to display the xml data in the required format. XML is the best way to exchange information.
XML tags are not predefined. User must "invent" his tags.


XML allows the user to define his own tags and document structure.

XML Tags are Case Sensitive

Unlike HTML, XML tags are case sensitive. In HTML the following will work:
This is incorrect

In XML opening and closing tags must therefore be written with the same case:

This is correctThis text is bold and italic

In XML all elements must be properly nested within each other like this:

This text is bold and italic

XML is a Complement to HTML

XML is not a replacement for HTML.

It is important to understand that XML is not a replacement for HTML. In Web development it is most likely that XML will be used to describe the data, while HTML will be used to format and display the same data.

XML: An Introduction - Brief History

In the 1970’s, Charles Goldfarb, Ed Mosher and Ray Lorie invented GML at IBM. GML was used to describe a way of marking up technical documents with structural tags. The initials stood for Goldfarb, Mosher and Lorie.

Goldfarb invented the term “mark-up language” to make better use of the initials and it became the Standard Generalised Markup Language .

In 1986 , SGML was adopted by the ISO .

SGML is just a specification for defining markup languages.

SGML (Standardized Generalized Markup Language) is the mother of all markup languages like HTML, XML, XHTML, WML etc...

In 1986, SGML became an international standard for defining the markup languages. It was used to create other languages, including HTML, which is very popular for its use on the web. HTML was made by Tim Berners Lee in 1991.

While on one hand SGML is very effective but complex, on the other, HTML is very easy, but limited to a fixed set of tags. This situation raised the need for a language that was as effective as SGML and at the same time as simple as HTML. This gap has now been filled by XML.

The development of XML started in 1996 at Sun Microsystems. Jon Bosak with his team began work on a project for remoulding SGML. They took the best of SGML and produced something to be powerful, but much simpler to use.

The World Wide Web Consortium also contributes to the creation and development of the standard for XML. The specifications for XML were laid down in just 26 pages

How Can You Use XML?

Few Applications of XML

Although there are countless applications that use XML, here are a few examples of the applications that are making use of this technology.

Refined search results - With XML-specific tags, search engines can give users more refined search results. A search engine seeks the term in the tags, rather than the entire document, giving the user more precise results.

EDI Transactions - XML has made electronic data interchange (EDI) transactions accessible to a broader set of users. XML allows data to be exchanged, regardless of the computing systems or accounting applications being used.

Cell Phones - XML data is sent to some cell phones, which is then formatted by the specification of the cell phone software designer to display text, images and even play sounds!
File Converters - Many applications have been written to convert existing documents into the XML standard. An example is a PDF to XML converter.

VoiceXML - Converts XML documents into an audio format so that a user can listen to an XML document.

XML--What is XML?

"XML is a cross-platform, software and hardware independent tool for transmitting information"

XML is a W3C Recommendations. It stands for Extensible Markup Language . It is a markup language much like HTML used to describe data. In XML, tags are not predefined. A user defines his own tags and XML document structure like Document Type Definition (DTD) , XML Schema to describe the data. Hence it is self-descriptive too.There is Nothing Special About XML It is just plain text with the addition of some XML tags enclosed in angle brackets. In a simple text editor, the XML document is easily visible .


Why Is XML So Important?

There are number of reasons that contributes to the XML's increasing acceptance , few of them are:

Plain Text

In XML it is easy to create and edit files with anything from a standard text editor to a visual development environment. XML also provides scalability for anything from small configuration files to a company-wide data repository.

Data Identification

The markup tags in XML documents identifiy the information and break up the data into parts for example.. a search program can look for messages sent to particular people from the rest of the message. Different parts of the information are identified and further they can be used in different ways by different applications.

Stylability

When display matters, the stylesheet standard, XSL (an advance feature of XML), lets you dictate over the convectional designs ( like using HTML) to portray the data. XML being style-free, uses different stylesheets to produce output in postscript, TEX, PDF, or some new format that hasn't even been invented yet. A user can use a simple XML document to display data in diverse formats like

* a plain text file
* an XHTML file
* a WML (Wireless Markup Language) document suitable for display on a PDA
* an Adobe PDF document suitable for hard copy
* a VML (Voice Markup Language) dialog for a voicemail information system
* an SVG (Scalable Vector Graphic) document that draws pictures of thermometers and water containers

Universally Processed

Apart from being valid , restrictions are imposed on a xml file to abide by a DTD or a Schema to make it well-formed .Otherwise, the XML parser won't be able to read the data. XML is a vendor-neutral standard, so a user can choose among several XML parsers to process XML data.

Hierarchical Approach

XML documents get benefitted from their hierarchical structure. Hierarchical document structures are, faster to access. They are also easier to rearrange, because each piece is delimited. This makes xml files easy to modify and maintain.

Inline Reusabiliy

XML documents can be composed of separate entities. XML entities can be included "in line" in a XML document. And this included sections look like a normal part of the document .A user can single-source a section so that an edit to it is reflected everywhere the section is used, and yet a document composed looks like a one-piece document.

I have two textboxes as TextBox1 and TextBox2 and a checkbox also on the form




Test Page



-----------------------------------------------------------------



















copy value below















Struts 2 Theme & Template

Please click the link:
Working with Struts 2 Theme & Template

Struts Tiles

Tiles is a framework for the development user interface. Tiles is enables the developers to develop the web applications by assembling the reusable tiles (jsp, html, etc..). Tiles uses the concept of reuse and enables the developers to define a template for the web site and then use this layout to populate the content of the web site. For example, if you have to develop a web site having more that 500 page of static content and many dynamically generated pages. The layout of the web site often changes according to the business requirement. In this case you can use the Tiles framework to design the template for the web site and use this template to populate the contents. In future if there is any requirement of site layout change then you have to change the layout in one page. This will change the layout of you whole web site.

Steps To Create Tiles Application


Tiles is very useful framework for the development of web applications. Here are the steps necessary for adding Tiles to your Struts application:

1. Add the Tiles Tag Library Descriptor (TLD) file to the web.xml.
2. Create layout JSPs.
3. Develop the web pages using layouts.
4. Repackage, run and test application.

Add the Tiles TLD to web.xml file
Tiles can can be used with or without Struts. Following entry is required in the web.xml file before you can use the tiles tags in your application.

/tags/struts-tiles
/WEB-INF/struts-tiles.tld



Create layout JSPs.
Our web application layout is divided into four parts: To Banner, Left Navigation Bar, Content Area and Bottom of the page for copy right information. Here is the code for out template (template.jsp):
<%@ page language="java" %>
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>



<tiles:getAsString name="title" ignore="true"/>







Custom Validators in STRUTS

Struts Validator framework provides many validation rules that can be used in the web applications. If you application needs special kind of validation, then you can extend the validator framework to develop your own validation rule.

The client-side validation in Struts is well known. Here are some of the available features:

* required
* requiredif
* validwhen
* minlength
* maxlength
* mask
* byte
* short
* integer
* long
* float
* double
* byteLocale
* shortLocale
* integerLocale
* longLocale
* floatLocale
* doubleLocale
* date
* intRange
* longRange
* floatRange
* doubleRange
* creditCard
* email
* url

These are found in the validator-rules.xml inside the tags. The validator-rules.xml file is found in the commons-validator jar.

Let us know create a new validator for entering the name field of a form. The form should accept only "administrator" for the name field. To accomplish this edit the validator-rules.xml and add the following code under the tag:


0) {
jcv_handleErrors(fields, focusField);
}
return isValid;
}
]]>

Client Side Address Validation in Struts

1. Enabling the Validator plug-in: This makes the Validator available to the system.
2. Create Message Resources for the displaying the error message to the user.
3. Developing the Validation rules We have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation.
4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript.
5. Build and test: We are required to build the application once the above steps are done before testing.

Enabling the Validator plug- in
To enable the validator plug-in open the file struts-config.xml and make sure that following line is present in the file.





Creating Message Resources
Message resources are used by the Validator Framework to generate the validation error messages. In our application we need to define the messages for name, Address and E-mail address. Open the Struts\strutstutorial\web\WEB-INF\MessageResources.properties file and add the following lines:
AddressForm.name=Name
AddressForm.address=Address
AddressForm.emailAddress=E-mail address

Developing Validation rules
In this application we are adding only one validation that the fields on the form should not be blank. Add the following code in the validation.xml.











The above definition defines the validation for the form fields name, address and emailAddress. The attribute depends="required" instructs the Validator Framework to generate the JavaScript that checks that the fields are not left blank. If the fields are left blank then JavaScript shows the error message. In the error message the message are taken from the key defined in the tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEB-INF\MessageResources.properties).

Applying Validation rules to JSP
Now create the AddressJavascriptValidation.jsp file to test the application. The code for AddressJavascriptValidation.jsp is as follows:
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>



<bean:message key="welcome.title"/>





This application shows the use of Struts Validator.

The following form contains fields that are processed by Struts Validator.

Fill in the form and see how JavaScript generated by Validator Framework validates the form.























Please Enter the Following Details

Name



Address



E-mail address



Save

Cancel









The code is used to plug-in the Validator JavaScript.

Create the following entry in the struts-config.xml for the mapping the /AddressJavascriptValidation url for handling the form submission through AddressJavascriptValidation.jsp.




Add the following line in the index.jsp to call the form.


  • Client Side Validation for Address Form


    The Address Form that validates the data on the client side using Stuts Validator generated JavaScript.
  • Struts 2 Features

    The strut-2 framework is designed for the compilation of the entire development cycle including of building, developing and maintaining the whole application. It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own. The basic platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.

    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 the doGet() and doPost() method and handles it appropriately.

    2. In struts application we have another xml file which is a Struts configuration file named as struts.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 . This tag tells the Struts ActionServlet 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 .do in 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

    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.








    action
    org.apache.struts.action.ActionServlet

    config /WEB-INF/struts-config.xml


    debug 2


    detail 2

    2


    This servlet is responsible for handing all the request for the Struts Framework, user can map the specific pattern of request to the ActionServlet. 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.


    action
    *.do


    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



    What is ActionForm?


    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.

    We will first create the class AddressForm which extends the ActionForm class. Here is the code of the class:

    AddressForm.java
    package roseindia.net;

    import javax.servlet.http.HttpServletRequest;

    import org.apache.struts.action.*;


    /**
    * @author Deepak Kumar
    * @Web http://www.roseindia.net
    * @Email roseindia_net@yahoo.com
    */

    /**
    * Form bean for the Address Entry Screen.
    *
    */
    public class AddressForm extends ActionForm
    {
    private String name=null;
    private String address=null;
    private String emailAddress=null;

    public void setName(String name){
    this.name=name;
    }

    public String getName(){
    return this.name;
    }

    public void setAddress(String address){
    this.address=address;
    }

    public String getAddress(){
    return this.address;
    }


    public void setEmailAddress(String emailAddress){
    this.emailAddress=emailAddress;
    }

    public String getEmailAddress(){
    return this.emailAddress;
    }


    /**
    * Reset all properties to their default values.
    *
    * @param mapping The mapping used to select this instance
    * @param request The servlet request we are processing
    */
    public void reset(ActionMapping mapping, HttpServletRequest request) {
    this.name=null;
    this.address=null;
    this.emailAddress=null;
    }

    /**
    * Reset all properties to their default values.
    *
    * @param mapping The mapping used to select this instance
    * @param request The servlet request we are processing
    * @return errors
    */
    public ActionErrors validate(
    ActionMapping mapping, HttpServletRequest request ) {
    ActionErrors errors = new ActionErrors();

    if( getName() == null || getName().length() < 1 ) { errors.add("name",new ActionMessage("error.name.required")); } if( getAddress() == null || getAddress().length() < 1 ) { errors.add("address",new ActionMessage("error.address.required")); } if( getEmailAddress() == null || getEmailAddress().length() < 1 ) { errors.add("emailaddress",new ActionMessage("error.emailaddress.required")); } return errors; } } The above class populates the Address Form data and validates it. The validate() method is used to validate the inputs. If any or all of the fields on the form are blank, error messages are added to the ActionMapping object.
    Struts HTML Tags



    Struts provides HTML tag library for easy creation of user interfaces. In this lesson I will show you what all Struts HTML Tags are available to the JSP for the development of user interfaces.

    To use the Struts HTML Tags we have to include the following line in our JSP file:

    <%@ taglib uri="/tags/struts-html" prefix="html" %>

    above code makes available the tag to the jsp.


    Struts HTML Tags
    Looks up the message corresponding to the given key in the message resources and displays it.
    Tag creates the password field. The string is stored in the property named prop in the form bean.
    Tag creates the text field. The string is retrieved from and later stored in the property named text1 in the form bean.
    Submit Tag creates a submit button with the provided content as the button text.
    Reset Tag creates a reset button with the provided content as the button text.
    Tag prints all the available error on the page.
    Tag creates the file upload element on the form. The property must be of the type org.apache.struts.upload.FormFile.
    Tag creates check box on the form.
    Tag creates the hidden html element on the form.
    Tag creates the check box on the form.
    Tag creates list box on the form. The property selectBox must be an array of supported data-types, and the user may select several entries. Use to specify the entries.
    Tag creates the text area on the form.
    Tag is used to create the HTML Form for posting the data on the server.
    Tag generates the base tag. tells the browser to pretend that the current page is located at some URL other than where the browser found it. Any relative reference will be calculated from the URL given by instead of the actual URL. goes in the section.
    Tag renders an HTML Element.