Wednesday, July 25, 2012

Struts2 Notes Part1

Jakarta Struts

- Apache Struts is an open-source framework that is used for developing Java web application.

- Originally developed by the programmer and author Craig R. McClanahan, this was later taken over by the Apache Software Foundation in 2002.

- Struts have provided an excellent framework for developing application easily by organizing JSP and Servlet based on HTML formats and Java code.

- Strut1 with all standard Java technologies and packages of Jakarta assists to create an extensible development environment.

- However, with the growing demand of web application, Strut 1 does not stand firm and needs to be changed with demand.

- This leads to the creation of Strut2, which is more developer friendly with features like Ajax, rapid development and extensibility.

Jakarta Struts is incredibly useful in helping you create excellent Web appli­cations. When you use Jakarta Struts, your applications should work more effectively and have fewer bugs.

Struts is a framework that structures all the components of a Java-based Web application into a unified whole.These components of a Web application are

1. Java Servlets: Programs written in Java that reside on a Web server and respond to user requests.

2. JavaServer Pages: A technology for generating Web pages with both static and dynamic content.

3. JavaBeans: Components that follow specific rules, such as naming conventions.

4. Business logic: The code that implements the functionality or rules of your specific application.

Jakarta Struts uses a specific paradigm, or design pattern, to structure your application. The design pattern is called Model-View-Controller (MVC). The MVC design pattern helps you organize the various pieces of the application puzzle for maximum efficiency and flexibility.

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

Structuring a Web Application

A Web application is a program that resides on a Web server and produces static and dynamically created pages in a markup language (most commonly HTML) in response to a user’s request. The user makes the request in a browser, usually by clicking a link on the Web page.

To build Web applications, you use Java 2 Enterprise Edition (J2EE), which provides support for Servlets, JSP, and Enterprise JavaBeans (EJB), a distributed, multi-tier, scalable component technology.

A Web container is a program that manages the components of a Web applica­tion, in particular JSP pages and Java Servlets. A Web container provides a number of services, such as

Security: Restricted access to components, such as password protection.
Concurrency: The capability to process more than one action at a time.
Life-cycle management: The process of starting up and shutting down a component.

--------------------------------------------------------------------------------------------------------------------------
Understanding MVC Design Pattern

. The MVC (Model View Controller) design pattern is used by the struts for building an applications.

. It makes the application more maintainable.

. The main aim of using this design pattern is to separate the business data from the presentation of the users.

. This design pattern is very flexible and allows the users (developers) to extend their meet for specific project.

. The MVC architecture contains the three parts they are Model, View, Controller.

1. Model

- This components contains the application data which is represented by the view.

- Those data which is part of persistent state must reside in model object.

- When the state of data changes it notify the view.

- The controller access the model object data for effecting their state change.

- It represents and maintains the application state.

2. View

- The view represents the state of the model to the user.

- It is actually represents the application data to the user and also takes the data from the user and send to the controller.

- There is no business logic, flow logic inside the view it contains tags.

- The view renders the model data for presenting to the user.

- An application can contain many view.

Controller

- The controller is responsible for controlling entire application.

- It accepts the input coming from the view, translates into the action to be performed by the view.

- The controller is only responsible for accessing model and and rendering it to the various user interfaces.

- Simply you can say a controller accepts the data from the client, performs the business operation, and return it to the client.

- The flow of data in the application is controlled by the controller.

- It it responsible for forwarding the request to the appropriate handelar.

-----------------------------------------------------------------------------------------
Difference between Model 1 and Model 2 architecture:

Features of MVC1:

- Html or jsp files are used to code the presentation. To retrieve the data JavaBean can be used.

- In mvc1 archictecture all the view, control elements are implemented using Servlets or Jsp.

- In MVC1 there is tight coupling between page and model as data access is usually done using Custom tag or through java bean call.

Features of MVC2:

- The MVC2 architecture removes the page centric property of MVC1 architecture by separating Presentation, control logic and the application state.

- In MVC2 architecture there is only one controller which receives all the request for the application and is responsible for taking appropriate action in response to each request.

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

What’s a framework?

A web application framework is a piece of structural software that provides automation of common tasks of the domain as well as a built-in architectural solution that can be easily inherited by applications implemented on the framework.

. A FRAMEWORK AUTOMATES COMMON TASKS
. A FRAMEWORK PROVIDES AN ARCHITECTURAL SOLUTION

The Struts 2 framework

- Struts 2 is a second-generation web application framework that implements the Model-View-Controller (MVC) design pattern.

- Struts 2 is built from the ground up on best practices and proven, community-accepted design patterns.

- Struts2 is not just the next version of Struts 1, but it is a complete rewrite of the Struts architecture.

----------------------------------------------------------------------------------------------------------------
Key Core Features

1. Pluggable framework architecture that allows request lifecycles to be customized for each action.

2. Flexible validation framework that allows validation rules to be decoupled from action code.

3. Hierarchical approach to internationalization that simplifies localizing applications.

4. Integrated dependency injection engine that manages component lifecycle and dependencies.

5. By default, the framework utilizes Spring for dependency injection

6. Modular configuration files that use packages and namespaces to simplify managing large projects with hundreds of actions.

7. Java 5 annotations that reduce configuration overhead .Java 1.4 is the minimum platform

Struts 2 framework features:

1. POJO forms and POJO actions

- Struts2 has done away with the Action Forms that were an integral part of the Struts framework.
- With Struts2, you can use any POJO to receive the form input.
- Similarly, you can now see any POJO as an Action class.
- POJOs: plain old Java objects

2. Tag support

- Struts2 has improved the form tags and the new tags allow the developers to write less code.

3. AJAX support

- Struts2 has recognised the take over by Web2.0 technologies, and has integrated AJAX support into the product by creating AJAX tags, that function very similar to the standard Struts2 tags.

4. Easy Integration

- Integration with other frameworks like Spring, Tiles and SiteMesh is now easier with a variety of integration available with Struts2.

5. Template Support

- Support for generating views using templates.

6. Plugin Support

- The core Struts2 behaviour can be enhanced and augmented by the use of plugins.
- A number of plugins are available for Struts2.

7. Profiling

- Struts2 offers integrated profiling to debug and profile the application.
- In addition to this, Struts also offers integrated debugging with the help of built in debugging tools.

8. Easy to modify tags

- Tag markups in Struts2 can be tweaked using Freemarker templates.
- This does not require JSP or java knowledge.
- Basic HTML, XML and CSS knowledge is enough to modify the tags.

9. Promote less configuration

- Struts2 promotes less configuration with the help of using default values for various settings.
- You don't have to configure something unless it deviates from the default settings set by Struts2.

10. View Technologies:

- Struts2 has a great support for multiple view options (JSP, Freemarker, Velocity and XSLT)
--------------------------------------------------------------------------------------------------------
Request Lifecycle in Struts 2 applications

1. User Sends request:
User sends a request to the server for some resource.

2. FilterDispatcher determines the appropriate action:
The FilterDispatcher looks at the request and then determines the appropriate Action.

3. Interceptors are applied:
Interceptors configured for applying the common functionalities such as workflow, validation, file upload etc. are automatically applied to the request.

4. Execution of Action:
Then the action method is executed to perform the database related operations like storing or retrieving data from the database.

5. Output rendering:
Then the Result renders the output.

6. Return of Request:
Then the request returns through the interceptors in the reverse order. The returning request allows us to perform the clean-up or additional processing.

7. Display the result to user:
Finally the control is returned to the servlet container, which sends the output to the user browser.

------------------------------------------------------------------------------------------------------------------
Interceptors

Interceptors are Struts 2 components that execute both before and after the rest of the request processing. They provide an architectural component in which to define various workflow and cross-cutting tasks so that they can be easily reused as well as separated from other architectural concerns.

The Valuestack And OGNL

Struts 2 uses the ValueStack as a storage area for all application domain data that will be needed during the processing of a request. Data is
moved to the ValueStack in preparation for request processing, it is manipulated there during action execution, and it is read from there when the results render their response pages.

OGNL is a powerful expression language (and more) that is used to reference and manipulate properties on the ValueStack.

---------------------------------------------------------------------------------------------------------------------
Improvements made in Struts 2

1. Simplified Design
- Most of the Struts 2 classes are based on interfaces and most of its core interfaces are HTTP independent.
- Struts 1 programming model requires implementing the abstract classes while Struts 2 uses interfaces.

2. Intelligent Defaults
- Most configuration elements have a default value which can be set according to the need.
- "Convention over configuration" philosophy There are xml-based default configuration files that can be extended according to the need.

3. Improved Results
- Unlike ActionForwards (of Struts 1), Struts 2 Results provide flexibility to create multiple type of outputs.

4. POJO Action's
- Struts 1
Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse objects are passed to the
execute() method

- Struts 2
Any java class with execute() method can be used as an Action class. Actions are neutral to the underlying framework

5. No More ActionForm's
- ActionForms feature (of Struts 1) is no more known to the Struts 2 framework.
- Simple JavaBean flavored actions are used (in Struts 2) to put properties directly

6. Enhanced Testability
- Struts 2 Actions are HTTP independent and framework neutral.
- This enables to test struts applications very easily without resorting to mock objects.

7. Better Tag Features
- Struts 2 tags enables to add style sheet-driven markup capabilities.
- You can create consistent pages with less code.
- Struts 2 tag markup can be altered by changing an underlying stylesheet.
- Struts 2 tags are more capable and result oriented.
- Both JSP and FreeMarker tags are fully supported.

8. Annotation Support
- Java 5 annotations can be used as an alternative to XML and Java properties configuration.

9. Stateful Checkboxes
- Struts 2 checkboxes do not require special handling for false values.

10. Quick Start
- Many changes can be made on the fly without restarting a web container.

11. Customizable Controller
- Struts 2 lets to customize the request handling per action, if desired.
- Struts 1 lets to customize the request processor per module.

12. Easy Spring Integration
- Struts 2 Actions are Spring-aware.
- You just need to add Spring beans.

13. Easy Plug-in's
- Struts 2 extensions can be added by dropping in a JAR.
- No additional XML or properties files.
- Metadata is expressed through convention and annotation.

14. Ajax Support
- AJAX client side validation
- Remote form submission support (works with the submit tag as well)
- An advanced div template that provides dynamic reloading of partial HTML
- An advanced template that provides the ability to load and evaluate JavaScript remotely
- An AJAX-only tabbed Panel implementation
- A rich pub-sub event model
- Interactive auto complete tag

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

Struts 1 vs. Struts 2

Action Action
ActionForm Action or POJO
ActionForward Result
struts-config.xml struts.xml
ActionServlet FilterDispatcher
RequestProcessor Interceptors
validation.xml Action-validation.xml

--------------------------------------------------------------------------------------
Struts 2 Actions

- Actions are the core of the Struts2 framework, as they are for any MVC (Model View Controller) framework.

- Each URL is mapped to a specific action, which provides the processing logic necessary to service the request from the user.

- First, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result.

- Second, the action must assist the framework in determining which result should render the view that will be returned in the response to the request.


1. Struts2 Action interface

- The struts2 framework provides some classes and interfaces for writing action classes that provides a lots of flexibility.

- The most common which is extended by most of the Action classes is ActionSupport class.

- The default method which in an action class is execute() methods.

- When the action is called this method executed automatically.

The Action interface contains the a single method execute(). The business logic of the action is executed within this method. This method is implemented by the derived class.

Ex:
public String execute() throws Exception {

// Some Bussiness Logic
return SUCCESS;
}


It also contains the fields :

SUCCESS
- This is a string and it is returned when operation is success full.

INPUT
- This field is uses when the application requires default form.

ERROR
- This field is used when application execution is failure. Generally it forwarded to the view which representing the error message.

LOGIN
- When application need login from the user then this field is used. It forwarded to the login view to get login from user.

NONE
- If the execution of action is successful but you do not want to show any view then this field is used.
--------------------------------------------------------------------------------------------------------------
2. Implementing Actions in Struts 2

- Package com.opensymphony.xwork2 contains the many Action classes and interface.

- if you want to make an action class for you then you should implement or extend its classes or interface respectively.

- Actions contains the execute() method.

- All the business logic is present in this method.

- When an action is called the execute method is executed.

- You can make many action classes depending on your application need.

- And these action classes must be mapped into the struts.xml file.

1. ActionClass

Import statements

import com.opensymphony.xwork2.Action;

Class declaration

public class TestAction implements Action

Class code

String control = LOGIN;
String name;

public String getName() {
return name;
}

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

@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
if (name.length() > 0 && name.equalsIgnoreCase("web")) {
control = SUCCESS;
} else {
control = ERROR;
}
return control;
}
------------------------
struts.xml File

DTD File

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

XML Tag

<struts>

<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />

<package name="kites" extends="struts-default">

<action name="testAction"
class="com.kites.TestAction" >
<result name="error">/jsp/login.jsp</result>
<result name="success">/jsp/home.jsp</result>
</action>

</package>

</struts>
----------------------
JSP Pages

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

Form Part

<s:form action="testAction" >
<s:textfield name="name" label="Name" value=""/>
<s:submit />
</s:form>

Result Page

<s:property value="name" />

-----------------------------------------------------------------------------
ActionSupport class

- Struts ActionSupport class provides the default implementation of the most common actions.
- It provides a collection of methods.

Common methods are -

1. execute()
- This method executed automatically when action is called. This is default implemented method. Subclasses should implement this method by proving their business logic.

2. validate()
- This method is default implemented method. Subclasses should override this method to provide validation.

3 clearErrors()
- This method can be used when you want to continue execution, and want to clear the state of the action.

4. pause()
- This method stops/pause the method execution immediately and returns the action to the specific result such as Action.ERORR, Action.SUCCSESS, Action.INPUT. When the next time this action is called it resumes immediately.

5. clearErrorsAndMessages()
- It clears all the error and messages.

6. clearAllErrors()
- It clears all the errors().

7. clearMessages()
- It clears all the messages().

Ex:
Import Statments

import com.opensymphony.xwork2.ActionSupport;

Class Declaration

public class ActionSupportExample extends ActionSupport

Class Body

public String execute() throws Exception {
setMessage(getText(ACTIONMESSAGE));
System.out.println("Some Action Support Messages");
return SUCCESS;
}

public static final String ACTIONMESSAGE =
"ActionSupportExample.message";

private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}


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

Model Driven Interface

- Model driven interface is an Action interface which provides a model object to pushed into the value object in addition to action.
- In order to create a model driven action your class should extend ActionSupport class and also implement the ModelDriven interface.
- The Model driven interface provides a single method getModel() this allows the model to be pushed into the value stack .

Ex:

Import Statments

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

Class Declaration
-----------------
public class StudentAction extends ActionSupport
implements ModelDriven

Class Body
----------
StudentBean student = new StudentBean();

public String execute() throws Exception {
return SUCCESS;
}
public Object getModel() {
return student;
}

---------------------------------------------------------------------------------------------
Chain Action

- Struts2 provides the feature to chain many actions into a defined sequence or work flow.
- This feature can be used in an application by applying Chain Result to a action.
- A Chain Result is an result type which intercepts an interceptor with its own result and stack.
- This allows to forward a request to an another action. While propagating the state.

Ex:

<action name="doLogin" class="com.kites.Login">
<!-- Chain to another namespace -->
<result type="chain">
<param name="actionName">home</param>
<param name="namespace">/secure</param>
</result>
</action>
</package>
<package name="secure" extends="struts-default"
namespace="/secure">
<action name="home">
<result>home.jsp</result>
</action>
</package>

---------------------------------------------------------------------------------------------
Dispatcher Result

- The Dispatcher Result forwarded the action to the different action.
- The Dispatcher does not looses the request data.
- It forwarded the same to the dispatch the request data to the desired action.
- To use dispatcher in result you need to do the following mapping.


Usage :
<action name="dispatcherAction" class=".....">
<result name="success" type="dispatcher">
<param name="location">/jsp/home.jsp</param>
</result>

-------------------------------------------------------------------------------------------------------
Redirect Action Result

To redirect the action to the specified location you need to do mapping in the struts.xml as follows

<action name="redirectAction" class=".....">
<result name="success" type="redirectAction">/jsp/home.jsp</result>
</action>

-------------------------------------------------------------------------------------------------
Stream Result

- Stream Result is very important for allowing users to downloading contents.
- It is a custom result type for sending raw data via InputStream to the HttpServletResponse.

It has the following parameters.

1. contentType
- It is the MIME type which is sent on the browser.

2. inputName
- It is the name of the input stream property.

3. contentLength
- It is the Stream length in byte.

4. bufferSize
- It is the size of the buffer to copy from input to output.

5. allowCaching
- Its default value is true. If allowCaching set to false then it will set the Header "Pragma" and Cache-Control to "No-Catche".

6. contentDisposition
- It is used for specifying file name.

Ex:
struts.xml part
<action name="download" class="com.kites.StreamResultExample">
<result name="success" type="stream">
<param name="contentType">
application/octet-stream</param>
<param name="inputName">
fileInputStream</param>
<param name="contentDisposition">
attachment;filename="testFile.txt"
</param>
<param name="bufferSize">1024</param>
</result>
</action>

Action class part

private InputStream fileInputStream;

public InputStream getFileInputStream() {

return fileInputStream;
}
public String execute() throws Exception {
fileInputStream = new FileInputStream(new File("downloadfile.txt"));

return SUCCESS;
}
-----------------------------------------------------------------------------------------------------------------------------
PlainText Result

- PlainText Result is a result type.
- It Sends out the content to the user as a plain text.
- It can be used when you wish to send out raw content on a HTML or JSP file.

To use the PlainText Result you need to to do the following mapping with the struts.xml file

<action name="rawData" >

<result type="plainText">
<param name="location">/jsp/helloPage.jsp</param>
<param name="charSet">UTF-8</param>
</result>

</action>

----------------------------------------------------------------------------------------------------------------------
Tiles Result

- In Struts Tiles is a view layer which allows separate page to be reusable in single page.
- To use tiles in your application you need to design a base layout which arranges the different views into single page.
- The base layout describes where to arrange the page by using <tiles:insertAttribute name="...." /> tag.

--------------------------------------------------------------------------------------------------------------------------
PreResultListener

- PreResultListener is an interface of com.opensymphony.xwork2.interceptor package.
- It may provide a way to get register with ActionInvocation.
- It is executed after the action execution but before the result.
- It provide a method beforeResult(ActionInvocation invocation, String resultCode).
Ex:
Action Class

public String execute() throws Exception {
ActionContext context=ActionContext.getContext();
ActionInvocation invocation=
context.getActionInvocation();
invocation.addPreResultListener(
new PreResultListener() {
public void beforeResult(
ActionInvocation invocation,
String resultCode){
System.out.println("Executing Action - "+
invocation.getAction());
if(getName().equalsIgnoreCase("kites")){
System.out.println(getName());
invocation.setResultCode(SUCCESS);
}
else{
System.out.println("Going to error page "
+getName());
invocation.setResultCode(ERROR);
}
}
});
return control;

--------------------------------------------------------------------------------------------------------------------
Pagination

- Pagination is a way to divide the data/information into many pages and displaying them one by one in sequence and shorted order.
- It is required when information the pages become so large to display.
- Therefore you can divide the information into a limited size and display them.


------------------------------------------------------------------------------------------------------------------------
Validation Interceptor

- The validation Interceptor is used to validate the input before action is executed.
- The validation Interceptor validates the values against the Class-validator.xml file and show the field level and action level message.
- The validation Interceptor checks for implementation of action and workflow interceptor invoke the validate() method of the Action class.
- The validate() method of Action class validate the input using addFieldError() method.


Ex: struts.xml
<action name="Validation" class="kites.LoginAction">

<interceptor-ref name="params">
<param name="excludeParams">dojo\..*,^struts\..*</param>
</interceptor-ref>

<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>

<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>

<result name="input">/Login.jsp</result>
<result name="success">/success.jsp</result>

</action>

Action Class

public void validate() {

if (getUserName().length() == 0) {

addFieldError("userName", "");

} else if (!getUserName().equals("kites")) {

addFieldError("userName", getText("userName.incorrect"));

}
if (getPassword().length() == 0) {
addFieldError("password", getText("requiredpassword"));
}
else if (!getPassword().equals("kitesnet")) {

addFieldError("password", getText("password.incorrect"));
}

}

Properties file

username.incorrect = UserName is incorrect.
password.incorrect = Password is incorrect.
requiredstring = ${getText(fieldName)} is required.
requiredpassword = ${getText(fieldName)} should be more than 6 character.

---------------------------------------------------------------------------------------------------
Field/Non Field Validators

Struts2 used a xml file for validation called validation.xml.

Struts2 provides two ways for defining validator in XML file.

1. Field validator
2. Non-field validator

Field validator
- It works on single field of form. It define validator per field base.

Ex:
<validators>
<field name="username">
<field-validator type="required">
<message>User name required.</message>
</field-validator>
</field>
</validators>

Non Field Validators
- You can use non-field validators for server side validation in your application as.
Ex:
<validator type="expression">
<param name="fieldName">userName</param>
<message>
You must enter the User Name
</message>
</validator>

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

No comments:

Post a Comment