This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

CSS Drop Down Menu

Sunday, 26 January 2014

Hibernate : Core Concept

Note:-

This tutorial expects the user have knowledge of both Java and SQL. If you have a limited knowledge of JAVA or SQL, it is advised that

you start with a good introduction to that technology prior to attempting to learn Hibernate.

Hibernate Framework

Hibernate framework simplifies the development of java application to interact with the database. Hibernate is an open source,

lightweight, ORM (Object Relational Mapping) tool. An ORM tool simplifies the data creation, data manipulation and data access. It is a

programming technique that maps the object to the data stored in the database.
Java Application ---- object----ORM----Database


The ORM tool internally uses the JDBC API to interact with the database.

Advantages of Hibernate Framework:-
There are many advantages of Hibernate Framework. They are as follows:

1)Opensource and Lightweight: Hibernate framework is opensource under the LGPL license. The open source GNU
LGPL
(Lesser General Public License) is sufficiently flexible to allow the use of Hibernate in both open source and commercial projects.

2) Fast performance: The performance of hibernate framework is fast because cache is internally used in hibernate framework.
There are two types of cache in hibernate framework first level cache and second level cache. First level cache is
enabled bydefault.

3) Database Independent query: HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the database
independent queries. So you don't need to write database specific queries. Before Hibernate, If database is changed for the project,
we need to change the SQL query as well that leads to the maintenance problem.

4) Automatic table creation: Hibernate framework provides the facility to create the tables of the database automatically. So there is
no need to create tables in the database manually.

5) Simplifies complex join: To fetch data form multiple tables is easy in hibernate framework.

6) Provides query statistics and
database status:
Hibernate supports Query cache and provide statistics about query and database status.

Hibernate Architecture:-

The Hibernate architecture includes many objects persistent object, session factory, transaction factory, connection factory, session,
transaction etc.

There are 4 layers in hibernate architecutre java application layer, hibernate framework layer, backhand api layer and database layer.
The high level architecture of Hibernate with mapping file and configuration file.

Hibernate framework uses many objects session factory, session, transaction etc. alongwith existing Java API such as JDBC
(Java Database Connectivity), JTA (Java Transaction API) and JNDI (Java Naming Directory Interface).

Core Object Of Hibernate:-

1-SessionFactory

2-Session

3-Transaction

4-ConnectionProvider

5-TransactionFactory

SessionFactory

The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache.(optional) of data

. The org.hibernate.SessionFactory interface provides factory method to get the object of Session. You configure Hibernate's

SessionFactory. SessionFactory is a global factory responsible for a particular database. If you have several databases, for easier

startup you should use several configurations in several configuration files.

Session

The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps

the JDBC connection. It is factory of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The

org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for

Transaction, Query and Criteria.

Transaction

The transaction object specifies the atomic unit of work. It is optional. The org.hibernate.Transaction interface provides methods for

transaction management.

ConnectionProvider

It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource. It is optional.

TransactionFactory

It is a factory of Transaction. It is optional.

Steps to create A sample Example Of Hibernate (Without Using Annotation):-

Software requirement:-

1-Jdk 1.6 2-Eclipse Any Updated Version(I have Used here Eclipse Helios 3.6) 3-Hibernate Library 4-MySql DataBase

Step-1:-

First Download the hibernate jar from http://sourceforge.net/projects/hibernate/files/hibernate3/ Set it to Java build classpath (If You

Are Using the Eclipse.):-as Sample Project->right click->Properties->Java Bulid Path->Libraries->Add External JARs->ok.

Steps- 2:-

Now Create Entity Class (The Class which contains data,meta data which is to stored in to database Here )Here UserDetails.java which Is given below:-

Step 3:-

Now Create UserDetails.hbm.xml file where we configured data ,metadata attributes name of Table name where our data has to be stored in database. As given belows. This file should be in classpath or in side the src folder:-

Step 4:-

Now Create An Schema in MySql database(since here I am using MySql database), Here I have created hibernatesample schema.

Step 5:-

Now Create a Configuration File hibernate.cfg.xml, where I have configured database configuration and mapping file UserDetails.hbm.xml. which is given below:-

Step 6:-

Now create the main class For Hibernate like given below:-
Now Run The main Class of Hibernate.java as here is HibernateTest.java Then Check the schema Definatly You will find Datas stored in Schema configured in .cfg file.

Steps to create A sample Example Of Hibernate (Using Annotation):-

Software requirement:-

1-Jdk 1.6 2-Eclipse Any Updated Version(I have Used here Eclipse Helios 3.6) 3-Hibernate Library 4-MySql DataBase

Step-1:-

First Download the hibernate jar from http://sourceforge.net/projects/hibernate/files/hibernate3/ Set it to Java build classpath (If You

Are Using the Eclipse.):-as Sample Project->right click->Properties->Java Bulid Path->Libraries->Add External JARs->ok.

Steps- 2:-

Now Create Entity Class (The Class which contains data,meta data which is to stored in to database Here )Here UserDetails.java which Is given below:-

Step 3:-

Now Create An Schema in MySql database, Here I have created hibernatesample schema:-

Step 4:-

Now Create a Configuration File hibernate.cfg.xml, where I have configured database configuration and mapping file UserDetails.java which is given below. This file should be in classpath or in side the src folder:--

Step 5:-

Now create the main class For Hibernate like given below:-
Now Run The main Class of Hibernate.java as here is HibernateTest.java Then Check the schema Definatly You will find Datas stored in Schema configured in .cfg file.

Thursday, 23 January 2014

Checking the palindrome Of An given Integer/Reverse Integer

Copy the Text from one To another which file path given by command line argument

Find the file with Special Extension from Folder

Find Unique And Frequent words of Input any file

Find IP address And garbage Collection

For Grabage Collection:-

For IP Address:-

Sorting : Buble Sort

Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that need to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This passing procedure is repeated until no swaps are required, indicating that the list is sorted. Bubble sort gets its name because smaller elements bubble toward the top of the list.

Bubble Sort

Bubble sort is also referred to as sinking sort or comparison sort. Bubble sort has a worst-case and average complexity of O(n2), where n is the number of items sorted. Unlike the other sorting algorithms, bubble sort detects whether the sorted list is efficiently built into the algorithm. Bubble sort performance over an already sorted list is O(n).

Binary Tree ,Depth and Height

Step [1]:-

First Create Binary Tree class here is TreeNode.java which is given below:-

Step [2]:-

Create A class for all Its Methods like PreOrder,PostOrder,InOrder Traversal ,Depth and Height.Here class name is BinaryTreeMethods.java which is given below:-

Step [3]:-Now Create Main class For the Tree As below:-

LinkedList

Step [1]:-Create Node to create linked list as below:-

Step [2]:-Now create to All Methods of Linked List:-

Step [3]:-Now Create the mainClass to create LinkedList as Below:-

Transpose of Matrix

With help of Tranpose of Matrix we can also find out about the matrix whether it is symmetric or not . i.e. If Tranpose of matrix is equal to the matrix then Matrix is Called as Symmetric.

Multiplication Of Two Matrix

Addition Of Two Matrix

Print all Substring of Input

Check and Prime Number and Also Print The Prime Number

Fibonacci Series

Comparision of Two String

Reverse String And Checking the Palindrom

Floyed’s Triangle

Armstrong Number

Find Factorial of Input Number

Largest of three number

Swapping two number

Farenheit to Celsius

Find odd or even number

Printing of alphabet

Wednesday, 22 January 2014

JSP : Core Concept

JSP :-Introduction

Jsp technology is used to web application like servlet.It can be thought as extension of servlet as it provides more functionality more than that of servlet like expression language,jstl etc. Life Cycle of JSP:

1- Translation

2- Compilation

3- Classloading(class file is loaded by classloader)

4- Instantiation(Object Of generated servlet is created )

5- Initialization( jspInit() method is invoked by container)

6- Request Processing( _jspService() method is invoked by container)

7- Destroy( jspDestroy() method is invoked by container)

Note: in _jspService() ,underscore points out that it can not be overrides.

Jsp scriptlet tag(Scriptlet Elements):-

1-scriptlet tag

2-expression tag

3-Jsp Declaration tag

1-scriptlet tag

This one is used to write the java source code.for eg. <% java source code %>

2-expression tag

This one replacement of output stream in case of servlet. <%= source code %> For eg..
Note:-

Basic Difference between Jsp declaration and expression tag. Jsp declaration tag only declare the variable and methods and most thing is the it is placed out side the _jspService() method so that it doesn’t memory get every time when service method is called.

For eg.

JSP Standard Tag Library:-

The JSP Standard Tag Library represents a set of tags to simplify the JSP development.JSTL mainly 5 types of tags:-

1-core tags

2-Sql tags

3-xml tags

4-internationalization tags

5-Functions tags

The JSTL core tag provides variable support, URL management, Flow Control, etc.the url for the core tag is http://java.sun.com/jsp/jstl/core The prefix of the core tag is c.There are following jstl core tags that are given below:-

TagDescription
Like <%= ... >, but for expressions.
Sets the result of an expression evaluation in a 'scope'
Removes a scoped variable (from a particular scope, if specified).
Catches any Throwable that occurs in its body and optionally exposes it.
Simple conditional tag which evalutes its body if the supplied condition is true.
Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by and
Subtag of that includes its body if its condition evalutes to 'true'.
Subtag of that follows tags and runs only if all of the prior conditions evaluated to 'false'.
Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'var Reader'.
The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality .
Iterates over tokens, separated by the supplied delimeters.
Adds a parameter to a containing 'import' tag's URL.
Redirects to a new URL.
Creates a URL with optional query parameters.

Snapshot of Code

2-Sql tags:-

provides SQL support and its url is http://java.sun.com/jsp/jstl/sql The prefix of this tag is sql. The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server. Following is the syntax to include JSTL SQL library in your JSP:

Following is the list of SQL JSTL Tags:

TagDescription
Creates a simple DataSource suitable only for prototyping
Executes the SQL query defined in its body or through the sql attribute.
Executes the SQL update defined in its body or through the sql attribute.
Sets a parameter in an SQL statement to the specified value.
Sets a parameter in an SQL statement to the specified java.util.Date value.
Provides nested database action elements with a shared Connection, set up to execute all statements as one transaction.

3-xml tags:-

Provides Flow control and transformation etc. Its url is http://java.sun.com/jsp/jstl/xml The prefix is x. The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents. Following is the syntax to include JSTL XML library in your JSP. The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing XML, transforming XML data, and flow control based on XPath expressions.

Before you proceed with the examples, you would need to copy following two XML and XPath related libraries into your \lib: [1]- XercesImpl.jar: Download it from http://www.apache.org/dist/xerces/j/ [2]- xalan.jar: Download it from http://xml.apache.org/xalan-j/index.html Following is the list of XML JSTL Tags:

TagDescription
Like <%= ... >, but for XPath expressions.
Use to parse XML data specified either via an attribute or in the tag body.
Sets a variable to the value of an XPath expression.
Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is false, the body is ignored.
To loop over nodes in an XML document.
Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by and
Subtag of that includes its body if its expression evalutes to 'true'
Subtag of that follows tags and runs only if all of the prior conditions evaluated to 'false'
Applies an XSL transformation on a XML document

4-internationalization tags:-

Provides message formatting,number and date formatting etc. the url for this is http://java.sun.com/jsp/jstl/fmt and prefix is fmt. The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web sites. Following is the syntax to include Formatting library in your JSP:

Following is the list of Formatting JSTL Tags:

TagDescription
To render numerical value with specific precision or format..
Parses the string representation of a number, currency, or percentage.
Formats a date and/or time using the supplied styles and pattern
Parses the string representation of a date and/or time
Loads a resource bundle to be used by its tag body.
Stores the given locale in the locale configuration variable.
To display an internationalized message.
Specifies the time zone for any time formatting or parsing actions nested in its body.

5-Functions tags:-

Provide for String manipulation and length url of this is http://java.sun.com/jsp/jstl/functions Its prefix is fn. JSTL includes a number of standard functions, most of which are common string manipulation functions. Following is the syntax to include JSTL Functions library in your JSP:

Following is the list of JSTL Functions:

TagDescription
fn:contains()Tests if an input string contains the specified substring.
fn:containsIgnoreCase()Tests if an input string contains the specified substring in a case insensitive way.
fn:endsWith()Tests if an input string ends with the specified suffix.
fn:indexOf()Returns the index withing a string of the first occurrence of a specified substring.
fn:join() Joins all elements of an array into a string.
fn:length()Returns the number of items in a collection, or the number of characters in a string.
fn:split()Splits a string into an array of substrings.
fn:startsWith()Tests if an input string starts with the specified prefix.
fn:substring()Returns a subset of a string.
fn:substringAfter()Returns a subset of a string following a specific substring.
fn:toUpperCase()Converts all of the characters of a string to upper case..

JSP implicit Objects:-

There are 9 implicit objects that are availabale for all jsp pages. A list of the 9 implicit objects are given below:

ObjectType
outJspWriter.
requestHttpServletRequest
responseHttpServletResponse
configServletConfig
application ServletContext
sessionHttpSession
pageContextPageContext.
PageObject.
exceptionThrowable.

JSP directives:

These are the message which tells to container how to translate a JSP page into the corresponding servlet. There are three type of directive:-

[1]-Page directive

[2]-Include directive

[3]-Taglib directive

[1]-Page directive:-

Page directive defines the attribute that apply an entire JSP page.

Attributes of JSP pages are:-

[1]- import

[2]- contentType

[3]- extends

[4]- info

[5]- buffer

[6]- language

[7]- isELIgnored

[8]- isThreadSafe

[9]- autoFlush

[10] session

[11]- pageEncoding

[12]- errorPage

[13]- isErrorPage

[2]-include directive:-

this is used to include the contents of any resourcesit may be jsp file,html file or text file,since JSP page is translated only once so better to use static resources. <% include file=”resourcesName”%> <% include file=”header.html”%>

[3]-Taglib:-

The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior. The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page. The taglib directive follows the following syntax:

Where the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions. You can write XML equivalent of the above syntax as follows:

Check more detail related to taglib directive at Taglib Directive.

Example: suppose the custlib tag library contains a tag called hello. If you wanted to use the hello tag with a prefix of mytag,

your tag would be and it will be used in your JSP file as follows:


Advantage Of JSTL over JSP scriptlet tags:-

1- Automatic JavaBean Introspection Support-

if you consider that JSTL's expression language handles JavaBean introspection automatically—which means you don't need to downcast objects you retrieve as scoped attributes—
Because of JSP's automatic support of JavaBean introspection, this block of code becomes much more simple in JSTL.

2-Standardized Support for Formatting and I18N:-

In proper Web design, JSP pages should be responsible only for the presentation of data. Two very common components to this presentation are the formatting of numbers and strings, and internationalization (I18N) support. Prior to JSTL, there was no official way to support these two features in JSP scriptlet code. Many companies developed their own sets of objects that could be used to support multiple languages. Data formatting was handled in a similar fashion

JSP EL(Expression Languange):-

Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. Within a JSP EL expression, you can use integers, floating point numbers, strings, the built-in constants true and false for boolean values, and null.

Simple Syntax:-

${expr}

Note :-

When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate the expression and substitues the value of expresson.

Monday, 20 January 2014

Struts2.x:Features And MVC Architecture

Struts 2 Framework:-

The struts 2 framework is used to develop MVC-based web application.Apache Struts is a free, open-source, MVC framework for creating elegant, modern Java web applications. The Struts 2 framework is used to develop MVC (Model View Controller) based web applications. Apache Struts 2 was originally known as WebWork 2. After working independently for several years, the WebWork and Struts communities joined forces to create Struts2. This new version of Struts is simpler to use and closer to how Struts was always meant to be.In Another word we can say that Struts 2 is the combination of webwork framework of opensymphony and struts1. struts2 = webwork + struts1 The Struts 2 provides supports to POJO based actions, Validation Support, AJAX Support, Integration support to various frameworks such as Hibernate, Spring, Tiles etc, support to various result types such as Freemarker, Velocity, JSP etc.
Note :-
OpenSymphony was an Open Source computer software project dedicated to providing enterprise class Java EE components. OpenSymphony shut down sometime around 2009-2011, but some of the subprojects are now maintained elsewhere. Patrick Lightbody was one of the main programmers at the company.
WebWork and XWork : Core Engine Of OpenSymphony

Struts 2 Features:-

Struts 2 provides many features that were not in struts 1. The important features of struts 2 framework are as follows:
[1]:-Configurable MVC components
In struts 2 framework, we provide all the components (view components and action) information in struts.xml file. If we need to change any information, we can simply change it in the xml file.
[2]:-POJO based actions
In struts 2, action class is POJO (Plain Old Java Object) i.e. a simple java class.
[3]:-AJAX support
Struts 2 provides support to ajax technology.
[3]:-Integration support
We can simply integrate the struts 2 application with hibernate, spring, tiles etc. frameworks.
[4]:-Various Result Types
We can use JSP, freemarker, velocity etc. technologies as the result in struts 2.
[5]:-Various Tag support
Struts 2 provides various types of tags such as UI tags, Data tags, control tags etc to ease the developement of struts 2 application.
[6]:-Theme and Template support
Struts 2 provides three types of theme support: xhtml, simple and css_xhtml. The xhtml is default theme of struts 2. Themes and templates can be used for common look and feel.

WorkFlow in Struts-2.x:-

Image Courtesy: struts.apache.org [1]-The normal lifecycle of struts begins when the request is sent from client. This results invoke the servlet container which in turn is passed through standard filter chain. [2]-The FilterDispatcher filter is called which consults the ActionMapper to determine whether an Action should be invoked. [3]-If ActionMapper finds an Action to be invoked, the FilterDispatcher delegates control to ActionProxy. [4]-ActionProxy reads the configuration file such as struts.xml. ActionProxy creates an instance of ActionInvocation class and delegates the control. [5]-ActionInvocation is responsible for command pattern implementation. It invokes the Interceptors one by one (if required) and then invoke the Action. [6]-Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml. [7]-The Interceptors are executed again in reverse order and the response is returned to the Filter (In most cases to FilterDispatcher). And the result is then sent to the servlet container which in turns send it back to client.
Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml. The result is then executed, which often (but not always, as is the case for Action Chaining) involves a template written in JSPor FreeMarker to be rendered. While rendering, the templates can use the Struts Tags provided by the framework. Some of those components will work with the ActionMapper to render proper URLs for additional requests.
Note :-
Action Chaining:- The framework provides the ability to chain multiple actions into a defined sequence or workflow. This feature works by applying a Chain Result to a given Action, and intercepting its target Action's invocation with a ChainingInterceptor. FreeMarker:- FreeMarker is a Java-based template engine that is a great alternative to JSP. FreeMarker is ideal for situations where your action results can possibly be loaded from outside a Servlet container. For example, if you wished to support plugins in your application, you might wish to use FreeMarker so that the plugins could provide the entire action class and view in a single jar that is loaded from the classloader.
All objects in this architecture (Actions, Results, Interceptors, and so forth) are created by an ObjectFactory. This ObjectFactory is pluggable. We can provide our own ObjectFactory for any reason that requires knowing when objects in the framework are created. A popular ObjectFactory implementation uses Spring as provided by the Spring Plugin.

MVC Architecture:-

Model The model represents the state (data) and business logic of the application. View The view module is responsible to display data i.e. it represents the presentation. Controller The controller module acts as an interface between view and model. It intercepts all the requests i.e. receives input and commands to Model / View to change accordingly
Disadvantage MVC Architecture:-
We need to write the controller code self. If we change the controller code, we need to recompile the class and redeploy the application

Sunday, 19 January 2014

Struts2.x: Core Component

Core Components Of Struts2.x :-

[1]- Interceptors
[2]- ValueStack
[3]- ActionContext
[4]- ActionInvocation
[5]- OGNL

[1]-Interceptors :-

Interceptor is an object that is invoked at the preprocessing and postprocessing of a request. In Struts 2, interceptor is used to

perform operations such as validation, exception handling, internationalization, displaying intermediate result etc.

Advantage of interceptors :-

Pluggable If we need to remove any concern such as validation, exception handling, logging etc. from the application, we don't need to

redeploy the application. We only need to remove the entry from the struts.xml file.

Struts 2 default Interceptors :-

There are many interceptors provided by struts 2 framework. We have option to create our own interceptors. The struts 2 default interceptors are as follows:
[1]- alias It converts similar parameters that have different names between requests.
[2]- chainIf it is used with chain result type, it makes the properties of previous action available in the current action.
[3]- cookie It adds a cookie to the current action.
[4]- createSession It creates and HttpSession object if it doesn't exists.
[5]- clearSession I It unbinds the HttpSession object.
[6]- execAndWait It sends an intermediate waiting page for the result.
[7]- exception It maps exception to a result.
[8]- fileUpload It provides support to file upload in struts 2.x
[9]- i18n It provides support to internationalization and localization.
[10]- i18n It provides support to internationalization and localization.
[11]- logger It outputs the action name.
[12]- params It populates the action properties with the request parameters.
[13]- roles It supports role-based action.
[14]- scope It is used to store the action state in the session or application scope.
[15]- servletConfig It provides access to maps representing HttpServletRequest and HttpServletResponse.
[16]- staticParams It maps static properties to action properties.
[17]- timer It outputs the time needed to execute an action.
[18]- validation It provides support to input validation.
[19]- workflow It calls the validate method of action class if action class implements Validateable interface.

[2]- Struts2 ValueStack :-

A valueStack is simply a stack that contains application specific objects such as action objects and other model object. At the

execution time, action is placed on the top of the stack. We can put objects in the valuestack, query it and delete it. The value stack

can be accessed via the tags provided for JSP, Velocity or Freemarker. There are various tags which we will study in separate

chapters, are used to get and set struts 2.0 value stack. You can get valueStack object inside your action as follows:

[3]- ActionContext :-

The ActionContext is a container of objects in which action is executed. The values stored in the ActionContext are unique per

thread (i.e. ThreadLocal). So we don't need to make our action thread safe. We can get the reference of ActionContext by calling

the getContext()
method of ActionContext class. It is a static factory method. For example:

[4]- ActionInvocation :-

The struts framework provides ActionInvocation interface to deal with ActionInvocation. It provides many methods, some of them can be used to get the instance of ValueStack, ActionProxy, ActionContext, Result etc. The ActionInvocation represents the execution state of an action. It holds the action and interceptors objects.

[5]-OGNL :-

The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion. The OGNL is very similar to the JSP Expression Language. OGNL is based on the idea of having a root or default object within the context. The properties of the default or root object can be referenced using the markup notation, which is the pound symbol(#). [The symbol (#) for a pound as a unit of weight..] As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The ActionContext map consists of the following:-
application - application scoped variables
session - session scoped variables
root / value stack - all your action variables are stored here
request - request scoped variables
parameters - request parameters
atributes - the attributes stored in page, request, session and application scope
It is important to understand that the Action object is always available in the value stack. So, therefore if your Action object has properties x and y there are readily available for you to use. Objects in the ActionContext are referred using the pound symbol(#), however, the objects in the value stack can be directly referenced, for example if employee is a property of an action class then it can ge referenced as follows:
instead of

Friday, 17 January 2014

Struts 2.x: Configuration File

The struts application contains two main configuration files struts.xml file and struts.properties file.The struts.properties file is

used to override the default values of default.xml file provided by struts framework. So it is not mandatory. Mostly, you will not use

struts.properties file. We will learn about it later.Here, we are going to learn all about struts.xml file. First of all let us see the simple

example of struts.xml file.

1:- package element

We can easily divide our struts application into sub modules. The package element specifies a module. You can have or or more

packages in the struts.xml file.
Attributes of package element:-

[a]-  name is must for defining any package.

[b]-  namespace is an optional attribute of package. If namespace is not present, / is assumed as the default namespace. In such

case, to invoke the action class, you need this URI:    /actionName.action

If you specify any namespace, you need this URI:    /namespacename/actionName.action

extends The package element mostly extends the struts-default package where interceptors and result types are defined. If you

extend struts-default, all the actions of this package can use the interceptors and result-types defined in the struts-default.xml file.

2:- action element

The action is the subelement of package and represents an action.
Attributes of action element:-

[a]:-name is must for defining any action.

[b]:-classclass is the optional attribute of action. If you omit the class attribute, ActionSupport will be considered as the

default action. A simple action may be as:



method It is an optional attribute. If you don't specify method attribute, execute method will

be considered as the method of action class. So this code:

3:- result element

It is the sub element of action that specifies where to forward the request for this action.
Attributes of result element:-

[a]-name is the optional attribute. If you omit the name attribute, success is assumed as the default result name.

[b]-type is the optional attribute. If you omit the type attribute, dispatcher is assumed as the default result type.


Why Struts 2.x???

Or

Difference between Struts1.x and Struts2.x


Let us see the component and functional differences between struts 1.x and struts 2.x
[a]- In struts 1.x front controller is ActionServlet while In 2.x front controller is FilterDispatcher.

[b]- In struts 1.x we have RequestProcessor class In 2.x we have Interceptors instead RequestProcessor will see about this

concept later just remember as of now.

[c]- In struts 1.x we have multiple tag libraries like, html, logic, bean..etc. In 2.x we do not have multiple libraries, instead we have

single
library which includes all tags.

[d]- In struts 1.x the configuration file name can be [any name].xml and we used to place in WEB-INF-folder. In 2.x

the configuration file must be struts.xml only and this must be in classes folder or WEB-INF/Classes/.

[e]- In struts 1.x we have form beans and Action classes separately In 2.x form bean, Action classes are combindly given as

Action class only, of course we can take separately if we want .

[f]- In struts 1.x properties file must be configured in struts-config.xml. But in 2.x we need to configure our resource

bundle(s)
in struts.properties file.

[g]- In struts 1.x we have programmatic and declarative validations only In 2.x we have annotations support too along

with programmatic and declarative validations.

Functional Differences:-

[a]:-In struts 1.x declarative validations are done by using validation frame work. In 2.x , declarative validations are done by using

xwork2 frame work
. [b]:- In struts 1.x an Action class is a singleton class, so Action class object is not a thread safe, as a

programmer we need to

make it as thread safe by applying synchronization In 2.x an Action class object will be created for each request, so it is by default

thread safe
, so we no need to take care about safety issues here.

[c]:- In struts 1.x we have only jsp as a view technology while In 2.x we have support of multiple view technologies like velocity,

Freemarker, jasper reports, jsp etc.


[d]:- In struts 1.x Action class is having servlet dependency, because in execute() method accepts req,res parameter

right.
In 2.x Action class doesn’t have any servlet dependency, because its execute() method doesn’t accepts any

parameters,
however we can access all servlet objects with dependency injection .

FilenameDescription
struts2-core.jar Framework library itself, found in distribution root directory
xwork.jar XWork 2 library on which Struts 2 is built (version 2.0 or later)
ognl.jar Object Graph Navigation Language (OGNL), the expression language used throughout the framework
freemarker.jar All UI tag templates are written in Freemarker (also a good option for your own views)
commons-logging.jar Commons logging, which the framework uses to support transparently logging to either Log4J or JDK 1.4+
commons-fileupload.jar The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.
commons-io.jar Commons IO is a library of utilities to assist with developing IO functionality.
web.xml Java web application configuration file that defines the filters (and other components) for your web application
struts.xml Framework configuration file that defines the actions, results, and interceptors for your application
Note:-
If any Struts 2 Plugins are included, then other JARs may be needed too. For example, the optional Spring Plugin requires the Spring JARs to be present.