Friday, July 27, 2012

Struts2 Programs 006 Stream Result

struts.xml
-----------------
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

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

<package name="kites" extends="struts-default">
<action name="resultStream">
<result name="success">/jsp/page.jsp</result>
</action>

<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>
</package>

</struts>
----------------------------------------------------------------------------------------------------------------------------------------
web.xml
--------------
<?xml version="1.0" encoding="UTF-8"?>

<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Struts 2</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
--------------------------------------------------------------------------------------------------------------------------------------
StreamResultExample.java
-------------------------------------------
package com.kites;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import com.opensymphony.xwork2.ActionSupport;

public class StreamResultExample extends ActionSupport{

private InputStream fileInputStream;

public InputStream getFileInputStream() {

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

return SUCCESS;

}

}
----------------------------------------------------------------------------------------------------------------------------------
page.jsp
------------------
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Chain Result Example</title>



</head>
<body>
<font color="megenta" size="6" face="Comic Sans MS">Stream Result example</font><br clear="all"/><br clear="all"/>

<s:url action="download" id="copy"></s:url>

<strong><font color="green" size="5" face="arier">Click on <s:a href="%{copy}">file</s:a> to Download</font></strong>

</body>
</html>

--------------------------------------------------------------------------------------------------------------------------------
downloadfile.txt
------------------------------

Struts2 is popular and mature web application framework based on the MVC design pattern. Struts2 is not just the next version of Struts 1, but it is a complete rewrite of the Struts architecture.

The WebWork framework started off with Struts framework as the basis and its goal was to offer an enhanced and improved framework built on Struts to make web development easier for the developers.

After some time, the Webwork framework and the Struts community joined hands to create the famous Struts2 framework.

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

Struts2 Programs 005 Redirect Action Result

struts.xml
-----------------------
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

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

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

<action name="login">
<result>/jsp/login.jsp</result>
</action>

<action name="doLogin" class="com.kites.Login">
<!-- Redirect to another namespace -->
<result name="success" type="redirectAction">
<param name="actionName">homePage</param>
<param name="namespace">/secure</param>
</result>

<result name="error" type="redirectAction">
<param name="actionName">errorPage</param>
<param name="namespace">/error</param>
</result>

</action>
</package>

<package name="secure" extends="struts-default" namespace="/secure">
<!-- Redirect to an action in the same namespace -->
<action name="homePage">
<result >/home.jsp</result>
</action>
</package>

<package name="error" extends="struts-default" namespace="/error">
<!-- Redirect to an action in the same namespace -->
<action name="errorPage">
<result >/error.jsp</result>
</action>
</package>

</struts>
--------------------------------------------------------------------------------------------------------------------------------
web.xml
----------------

<?xml version="1.0" encoding="UTF-8"?>

<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Struts 2</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
---------------------------------------------------------------------------------------------------------------------------------
Login.java
--------------------
package com.kites;

import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport {

public String execute() throws Exception {
System.out.println("Login Action Called");

if(getUsername().equalsIgnoreCase("")|| getPassword().equalsIgnoreCase("")){

return ERROR;
}
else if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){

return ERROR;
}else{

return SUCCESS;
}
}

private String username = null;

public String getUsername() {

return username;
}

public void setUsername(String value) {

username = value;
}

private String password = null;

public String getPassword() {

return password;
}

public void setPassword(String value) {

password = value;
}

}

---------------------------------------------------------------------------------------------------------------------
login.jsp
-------------

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Chain Result Example</title>



</head>
<body>
<s:form action="doLogin" method="POST">
<tr>
<td colspan="2">
Login
</td>
</tr>
<tr>
<td colspan="2">
<s:actionerror />
<s:fielderror />
</td>
</tr>
<s:textfield name="username" label="Login name"/>
<s:password name="password" label="Password"/>
<s:submit value="Login" align="center"/>
</s:form>
</body>
</html>
---------------------------------------------------------------------------------------------------------------------
home.jsp
-----------------
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body >
<center>
<h1> Home Page</h1>
<font color=green size=15 face=modern> Welcome </font>
</center>
</body>
</html>

-------------------------------------------------------------------------------------------------------------------------
error.jsp
-----------------
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body >
<center>
<h1> Error Page</h1>
</center>
</body>
</html>
------------------------------------------------------------------------------------------------------------------------------


Struts2 Programs 004 Dispatcher Result

struts.xml
-----------------
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

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

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

<action name="login">
<result>/login.jsp</result>
</action>

<!-- Redirect to another namespace -->

<action name="doLogin" class="com.kites.Login">
<result name="success" type="dispatcher">
<param name="location">/home.jsp</param>
</result>

<result name="error" type="dispatcher">
<param name="location">/error.jsp</param>
</result>

</action>

</package>

</struts>
-------------------------------------------------------------------------------------------------------------------------------

Login.java
-----------------

package com.kites;
import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport {

public String execute() throws Exception {

System.out.println("Login Action Called");
if(getUsername().equalsIgnoreCase("")|| getPassword().equalsIgnoreCase("")){

return ERROR;
}
else if(!getPassword().equals("Admin")){

return ERROR;
}else{

return SUCCESS;
}
}

private String username = null;

public String getUsername() {

return username;
}

public void setUsername(String value) {

username = value;
}

private String password = null;

public String getPassword() {

return password;
}

public void setPassword(String value) {

password = value;
}

}

---------------------------------------------------------------------------------------------------------------------
login.jsp
------------------
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Chain Result Example</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"
type="text/css"/>

</head>
<body>
<s:form action="doLogin" method="POST">
<tr>
<td colspan="2">
Login
</td>
</tr>
<tr>
<td colspan="2">
<s:actionerror />
<s:fielderror />
</td>
</tr>
<s:textfield name="username" label="Login name"/>
<s:password name="password" label="Password"/>
<s:submit value="Login" align="center"/>
</s:form>
</body>
</html>

-----------------------------------------------------------------------------------------------------------------------
home.jsp
---------------

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body >
<center>
<h1> Home Page</h1>
<font color=green size=15 face=modern> Welcome :<s:property value="username"/> </font><br>
</center>
</body>
</html>

--------------------------------------------------------------------------------------------------------------------------
error.jsp
-----------------
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body >
<center>
<h1> Error Page</h1>
</center>
</body>
</html>
---------------------------------------------------------------------------------------------------------------------------
web.xml
----------------
<?xml version="1.0" encoding="UTF-8"?>

<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Struts 2</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
----------------------------------------------------------------------------------------------------------------------

Wednesday, July 25, 2012

STRUTS2 Programs 003 Chain Action

struts.xml
-----------------
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

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

<package name="public" extends="struts-default">
<!-- Chain creatAccount to login, using the default parameter -->

<action name="showLogin">
<result>login.jsp</result>
</action>

<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>

</struts>
-----------------------------------------------------------------------------------------------------------------------------------
Login.java
-----------------

package com.kites;

import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport {

public String execute() throws Exception {

System.out.println("Login Action Called");

if(getUsername().equalsIgnoreCase("")|| getPassword().equalsIgnoreCase("")){

return ERROR;
}
else if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){

return ERROR;
}else{

return SUCCESS;
}
}

private String username = null;

public String getUsername() {

return username;
}

public void setUsername(String value) {

username = value;
}

private String password = null;

public String getPassword() {

return password;
}

public void setPassword(String value) {

password = value;
}

}
----------------------------------------------------------------------------------------------------------------------------------
login.jsp
-------------
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Chain Result Example</title>


</head>
<body>
<s:form action="doLogin" method="POST">
<tr>
<td colspan="2">
Login
</td>
</tr>
<tr>
<td colspan="2">
<s:actionerror />
<s:fielderror />
</td>
</tr>
<s:textfield name="username" label="Login name"/>
<s:password name="password" label="Password"/>
<s:submit value="Login" align="center"/>
</s:form>
</body>
</html>
---------------------------------------------------------------------------------------------------------------------------------
home.jsp
---------------
<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Home Page </TITLE>
</HEAD>

<BODY bgcolor="lightgreen">
<center><font face="Arier" size="16">This is Home page</font>
<font face="arier" size="14"><br>Welcome : <s:property value="username"/></font>
</center>
</BODY>
</HTML>
-------------------------------------------------------------------------------------------------------------------------------
web.xml
-------------------

<?xml version="1.0" encoding="UTF-8"?>

<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Struts 2</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
-----------------------------------------------------------------------------------------------------------------------------------

Struts2 002 ActionSupport class

struts.xml
-----------------
<?xml version="1.0" encoding="UTF-8"?>

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

<struts>

<constant name="struts.devMode" value="true" />

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

<action name="actionSupport" class="com.kites.ActionSupportExample">
<result>actionsupport.jsp</result>
</action>

</package>

</struts>
--------------------------------------------------------------------------------------------------------------------------
ActionSupportExample.java
-------------------------------------------

package com.kites;

import com.opensymphony.xwork2.ActionSupport;

public class ActionSupportExample extends ActionSupport {

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;
}
}
----------------------------------------------------------------------------------------------------------------------------
actionsupport.jsp
--------------------------

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title><s:text name="ActionSupportExample.message"/></title>
</head>

<body>
<h2><s:property value="message"/></h2>
<a href="#">Back to Index page</a>
</body>
</html
-------------------------------------------------------------------------------------------------------------------------
web.xml
--------------
<?xml version="1.0" encoding="UTF-8"?>

<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Struts 2</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
----------------------------------------------------------------------------------------

Struts2 Programs 001 model driven interface

I'll continue posting programs on this topic in the coming days . These programs are not my creation i have got these codes from the new so courtesy to all who has posted this code in the net

web.xml
---------------------
<?xml version="1.0" encoding="UTF-8"?>

<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Struts 2</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

------------------------------------------------------------------------------------
struts.xml
-----------------

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

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

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


<action name="addStudent"
class="com.kites.StudentAction" >
<result name="success">/addStudent.jsp</result>
</action>

<action name="studentAction"
class="com.kites.StudentAction" >
<result name="success">/studentInfo.jsp</result>
</action>

</package>

</struts>

-----------------------------------------------------------------------------------------------------------
StudentBean.java
--------------------------

package com.kites;

public class StudentBean{

String studentName;
int studentAge;

public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}

}
----------------------------------------------------------------------------------
StudentAction.java
-----------------------------

package com.kites;

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

public class StudentAction extends ActionSupport
implements ModelDriven{

StudentBean student = new StudentBean();

public String execute() throws Exception {

return SUCCESS;

}

public Object getModel() {

return student;
}
}
-------------------------------------------------------------------------------------------------
addStudent.jsp
------------------------

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body>
<h1>ModelDriven Interface Example</h1>

<h2>Add Student</h2>
<s:form action="studentAction" >
<s:textfield name="studentName" label="Name" value=""/>
<s:textfield name="studentAge" label="Age" value=""/>
<s:submit />
</s:form>

</body>
</html>

---------------------------------------------------------------------------------------------------
studentInfo.jsp
-----------------------

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
<body>
<h1>ModelDriven Interface Example</h1>

<h2>Student Details</h2>
Name : <s:property value="studentName" /><br>
Age : <s:property value="studentAge" /><br>

</body>
</html>
--------------------------------------------------------------------------------------

Struts2 Notes(custom interceptors) part4

Understanding Interceptors

- Interceptors can execute code before and after an Action is invoked.

- Most of the framework's core functionality is implemented as Interceptors.

- Features like double-submit guards, type conversion, object population, validation, file upload, page preparation, and more, are all implemented with the help of Interceptors.

- Each and every Interceptor is pluggable, so you can decide exactly which features an Action needs to support.

- Interceptors can be configured on a per-action basis.

- Your own custom Interceptors can be mixed-and-matched with the Interceptors bundled with the framework.

- Interceptors can also change the state of an Action before it executes.

---------------------------------------------------------------------------------------------------------------
Configuring Interceptors

<package name="default" extends="struts-default">
<interceptors>
<interceptor name="timer" class=".."/>
<interceptor name="logger" class=".."/>
</interceptors>

<action name="login"
class="tutorial.Login">
<interceptor-ref name="timer"/>
<interceptor-ref name="logger"/>
<result name="input">login.jsp</result>
<result name="success"
type="redirectAction">/secure/home</result>
</action></package>

---------------------------------------------------------------------------------------------------------------
Stacking Interceptors

<package name="default" extends="struts-default">
<interceptors>
<interceptor name="timer" class=".."/>
<interceptor name="logger" class=".."/>
<interceptor-stack name="myStack">
<interceptor-ref name="timer"/>
<interceptor-ref name="logger"/>
</interceptor-stack>
</interceptors>

<action name="login"
class="tutuorial.Login">
<interceptor-ref name="myStack"/>
<result name="input">login.jsp</result>
<result name="success"
type="redirectAction">/secure/home</result>
</action>
</package>

---------------------------------------------------------------------------------------------------------------
Writing Interceptors

Interceptor interface

- Interceptors must implement the com.opensymphony.xwork2.interceptor.Interceptor interface.

public interface Interceptor extends Serializable {

void destroy();
void init();
String intercept(ActionInvocation invocation) throws Exception;
}

- The init method is called the after interceptor is instantiated and before calling intercept.
- This is the place to allocate any resources used by the interceptor.

- The intercept method is where the interceptor code is written.
- Just like an action method, intercept returns a result used by Struts to forward the request to another web resource.

AbstractInterceptor

- The AbstractInterceptor class provides an empty implementation of init and destroy, and can be used if these methods are not going to be implemented.

Mapping

- Interceptors are declared using the interceptor element, nested inside the interceptors element. Example from struts-default.xml:

struts.xml
----------

<struts>
...

<package name="struts-default">
<interceptors>
<interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>
<interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
...
</interceptors>
</package>

...
</struts>

SimpleInterceptor

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SimpleInterceptor extends AbstractInterceptor {

public String intercept(ActionInvocation invocation) throws Exception {
MyAction action = (MyAction)invocation.getAction();
action.setDate(new Date());
String result =invocation.invoke();
//after execute interceptor code
return result;
}
}

Struts2 Notes(OGNL) Part3

The Value Stack:
----------------
The value stack is a set of several objects which keeps the following objects in the provided order:

Objects & Description
---------------------
1. Temporary Objects
-There are various temporary objects which are created during execution of a page. For example the current iteration value for a collection being looped over in a JSP tag.

2. The Model Object
If you are using model objects in your struts application, the current model object is placed before the action on the value stack

3. The Action Object
This will be the current action object which is being executed.

4. Named Objects
These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes

You can get valueStack object inside your action as follows:

ActionContext.getContext().getValueStack()


Once you have a ValueStack object, you can use following methods to manipulate that object:

ValueStack Methods & Description
-------------------------------

1. Object findValue(String expr)
Find a value by evaluating the given expression against the stack in the default search order.

2. CompoundRoot getRoot()
Get the CompoundRoot which holds the objects pushed onto the stack.

3. Object peek()
Get the object on the top of the stack without changing the stack.

4. Object pop()
Get the object on the top of the stack and remove it from the stack.

5. void push(Object o)
Put this object onto the top of the stack.

6. void set(String key, Object o)
Sets an object on the stack with the given key so it is retrievable by findValue(key,...)

7. void setDefaultType(Class defaultType)
Sets the default type to convert to if no type is provided when getting a value.

8. void setValue(String expr, Object value)
Attempts to set a property on a bean in the stack with the given expression using the default search order.

9. int size()
Get the number of objects in the stack.

Ex:

Java Part
---------

ValueStack stack =
ActionContext.getContext().getValueStack();
Map<String, Object> context =
new HashMap<String, Object>();
context.put("key1", new String("This is key1"));
context.put("key2", new String("This is key2"));
stack.push(context);

JSP Part
-------
<body>
Value of key 1 : <s:property value="key1" /><br/>
Value of key 2 : <s:property value="key2" /> <br/>
</body>

------------------------------------------------------------------------------------------------------------------------
OGNL in struts
---------------

- Object Graph Navigation Language is a expression language.

- It is used for getting and setting the properties of java object.

- It is very useful binding language for manipulating and retrieving different properties of java object.

- It has own syntax, which is very simple.

- It make code more readable.

- It acts as a binding language between GUI elements and model objects.

- The Struts framework used a standard naming context for evaluating an OGNL expression.

- It sets OGNL context to be the ActionContext, and ValueStack to be the OGNL root object.

The ActionContext map consists of the following:

1. application - application scoped variables

2. session - session scoped variables

3. root / value stack - all your action variables are stored here

4. request - request scoped variables

5. parameters - request parameters

6. atributes - the attributes stored in page, request, session and application scope

Objects in the ActionContext are referred using the pound symbol, however, the objects in the value stack can be directly referenced,

Syntax of OGNL :

The chain contain following parts :

1. Property Names - Property names, such as name and text.
2. Methods calls - Method calls, such as the hashcode(), which returns hash code of current object.
3. Array Indices - For example, array[0], which returns first element of current object.

For example.
name.toCharArray()[0].numericValue.toString()

Description :

1. The name is the property of the initial or root object. This root object provided to the OGNL through the OGNL context.
2. Then it calls the toCharArray() of the resulting string , After calling toCharArray() method, this first character at 0 index is extracted from the resulting array.
3. It then gets the numericValue property from that character.
4. Finally the String is returned after calling the toString() on resulting Integer object.

-------------------------------------------------------------------------------------------------------------------
Access value of array using OGNL

JSP Part:

<body><h1>OGNL_Example</h1><hr>
Size of list : <s:property value="name.size"/><br/>
<p> access data of list.</p><br/>
name[3] : <s:property value="name[3]"/><br/>
name[2] : <s:property value="name[2]"/><br/>
name[1] : <s:property value="name[1]"/><br/>
name[0] : <s:property value="name[0]"/><br/>
Value array list : <s:property value="name"/>
</body>

Action Class

public class OGNLAction extends ActionSupport{
private List<String> name=
new ArrayList<String>();
{
name.add("User1");
name.add("User2");
name.add("User3");
name.add("User4");
}
public String execute() throws Exception {
return SUCCESS;
}
public List<String> getName() {
return name;
}
public void setName(List<String> name) {
this.name = name;
}
}

-----------------------------------------------------------------------------------------------------------
Access session value using OGNL

JSP Part
--------
<s:iterator id="beans" value="#session['beans']">
<tr>
<td><s:property value="empName"/></td>
<td><s:property value="lang"/></td>
</tr>
</s:iterator>

Java Bean Class
---------------

public class EmployeeBean {

private String lang;
private String empName;

public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}

Action Class
------------

public class OGNLOnsessionObject extends ActionSupport {

private List langName;
private String lang;
private String empName;

ActionContext context =
ActionContext.getContext();
Map session = context.getSession();
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public List getLangName() {
return langName;
}
public void setLangName(List langName) {
this.langName = langName;
}
public OGNLOnsessionObject() {
langName = new ArrayList();
langName.add("C");
langName.add("c++");
langName.add("JAVA");
langName.add("PHP");
}
public String show() {
return INPUT;
}
public String execute() {
if (lang.equals("none")) {
this.addActionError("Please select any language.");
return ERROR;
}
ArrayList beans = null;
EmployeeBean bean = new EmployeeBean();
bean.setEmpName(empName);
bean.setLang(lang);
beans = (ArrayList) session.get("beans");
if (beans == null)
beans = new ArrayList();
beans.add(bean);
session.put("beans", beans);
return SUCCESS;
}

}

-----------------------------------------------------------------------------------------------------------
Access properties of bean from request object using OGNL

JSP Part
--------

|Accessing Request |

<table cellpadding="2" cellspacing="0" width="200">
<tr bgcolor="#CC66FF">
<td>Student Name</td> <td>Age</td>
</tr>
<tr>
<td>
<s:property
value="#request['bean'].studentname"/>
</td>
<td>
<s:property value="#request['bean'].age"/>
</td>
</tr>
</table>

Bean Part
---------

public class StudentDetails {

private String studentname;
private int age;
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

Action Class
------------

public class OGNLAction extends ActionSupport implements ServletRequestAware {

private HttpServletRequest request;
private String studentname;
private int age;

public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletRequest getServletRequest() {
return request;
}
public String execute() throws Exception {
if (studentname.equals("none")) {
this.addActionError("Please Select name...");
return ERROR;
}
StudentDetails bean = new StudentDetails();
bean.setStudentname(studentname);
bean.setAge(age);
request.setAttribute("bean", bean);
return SUCCESS;
}
}
-------------------------------------------------------------------------------------------

Struts2 Notes (Tags) Part2

Struts2 Tags


1. Generic Tags - Generic Tag Reference

1.1) Control Tags

if
elseIf
else
append
generator
iterator
merge
sort
subset

1.2) Data Tags

a
action
bean
date
debug
include
param
property
push
set
text
url

2. UI Tags - UI Tag Reference

2.1) Form Tags

checkbox
checkboxlist
combobox
doubleselect
head
file
form
hidden
label
optiontransferselect
optgroup
password
radio
reset
select
submit
textarea
textfield
token
updownselect

2.2) Non-Form UI Tags

actionerror
actionmessage
component
div
fielderror

3 Ajax Tags

a
autocompleter
bind
datetimepicker
div
head
submit
tabbedpanel
textarea
tree
treenode

---------------------------------------------------------------------------------------------------------------------------
If/Elseif/else Tag

- The If tag is used for decision making on the basis of condition specified in the tag.
- If tag could be used by itself or with Else If ,Else, or multiple Else tags. only one tag is evaluated at a time based on the condition which one is evaluated.

Ex:
<s:set name="Name" value="%{'Kites'}" />
<s:if test="%{#Name=='Softwares'}">
You Working with--<div>
<s:property value="%{#Name}" /></div>
<div>Your Name is Kites</div>
</s:if>

<s:elseif test="%{#Name=='Kites'}">
You Working with--<div>
<s:property value="%{#Name}" /></div>
<div>My Name is Kites</div>
</s:elseif>
<s:else>
for false condition <div>Your Name is Not
Specified</div>
</s:else>

---------------------------------------------------------------------------------------------------------------
Append Tag

- Append tag is used to Append an iterator based on the ?id? attribute provided in the page.
- Struts2 append tag is used to combine few Iterators (created by List or Map) into a single Iterator.
- Append Iterator Tag is used to append iterators to form an appended iterator

Ex:
<body>
<h1>Struts 2 Append tag example</h1>
Combine ArrayList1 and ArrayList2
into a single iterator.
<s:append id="AppendList">
<s:param value="%{list1}" />
<s:param value="%{list2}" />
</s:append>

<s:iterator value="%{#AppendList}">
<li><s:property /></li>
</s:iterator>
</body>

----------------------------------------------------------------------------------------
Generator Tag

- Struts 2 generator tag is used to generate an iterator based on the ?val? attribute provided in the page.
- The generator tag is a generic tag that is used to generate iterators based on different attributes passed.

Ex:
<body>

<s:generator separator=","
val="%{'User1,User2,User3,User4'}" >
<s:iterator >
<s:property/><br/>
</s:iterator>
</s:generator>
</body>

------------------------------------------------------------------------------------------------
Iterator tag

- Iterator tag is used to iterate over a value.
- An iterable value can be either of: java.util.Collection, java.util.Iterator.

Ex:
<body>

<h2>Iterator tag of Struts2</h2>
Elements of ArrayList Collection.....
<s:iterator value="obList">
<s:property />
<br />
</s:iterator>
</body>

---------------------------------------------------------------------------------------------
Merge Tag

- The merge tag is a generic tag that is used to merge iterators.

Ex:

<body>
<h1>Struts 2 Merge tag example</h1>
Merge List1 and List2 into a single iterator.
<s:merge id="MergeList">
<s:param value="%{list1}" />
<s:param value="%{list2}" />
</s:merge>
<s:iterator value="%{#MergeList}">
<li><s:property /></li>
</s:iterator>
</body>

----------------------------------------------------------------------------------
sort Tag

The sort tag is used to sort a List using a java.util.Comparator. List and Comparator both passed in as the tag attribute.

Ex:

<body>
The UnSorted Values.<br>
<ol> <s:iterator value="list">
<LI><s:property value="id" /> ,
<s:property value="name" /> ,
<s:property value="age" /></LI>
</s:iterator> </ol>
<table>
<tr>
<td bgcolor="#ffffcc">The Values Sorted by ID.<br>
<s:bean name="kites.IdComparator" var="MyId" />
<s:sort comparator="#MyId" source="list">

<ol> <s:iterator>
<LI><s:property value="id" /> ,
<s:property value="name" /> ,
<s:property value="age" />
</LI>
</s:iterator> </ol>
</s:sort></td>
<td></td>
<td bgcolor="pink">
The Values Sorted by Name.<br>
<s:bean name="kites.NameComparator"
var="MyName" />
<s:sort comparator="#MyName"
source="list">
<ol> <s:iterator>
<LI><s:property value="id" /> ,
<s:property value="name" /> ,
<s:property value="age" /></LI>
</s:iterator></ol>

</s:sort></td>

</tr> </table>
</body>

---------------------------------------------------------------------------------------------------------
subset Tag

- The subset tag is a generic tag is used to output a subset or portion of an iterator elements.

Ex:
<body>
The Subset of first 4 values :<br>

<s:subset source="list1" count="4">
<s:iterator><s:property /><br></s:iterator>
</s:subset>

<br>The Subset of 4 values starting from 5th index :<br>

<s:subset source="list1" start="4" count="4">
<s:iterator><s:property /><br></s:iterator>
</s:subset>

</body>

----------------------------------------------------------------------------------------------------------
Anchor Tag

- It provides a hyperlink from current page to another page.
- It works as anchor tag of html, but syntax is different .
- In HTML - <a>, struts - <s:a>.

Ex:

<body>
<h1>Struts2 a(Anchor)Tag Example</h1>
<ul>
<li>
<s:url var="StrutsExample"
value="http://www.kitesnet.com" />
<s:a href="%{StrutsExample}">
Struts Tags Examples........</s:a>
</li>
<li><s:url value="welcome.jsp"
var="welcome" />
<s:a href="%{welcome}" >
Go to welcome page </s:a>
</li>
</ul>
</body>

---------------------------------------------------------------------------------------------------------
Action Tag

- The Action tag is used to call action class directly from a JSP page.
- We can call action directly by specifying the action name and an optional namespace.
- The body content of the tag is used to render the results from the Action.

Ex:

<body>
<s:action name="ActionTag" >This is The Action.<br>
<b>Hello Dear!</b>
</s:action>
</body>

------------------------------------------------------------------------------------------------------
Bean Tag

The Bean tag is a generic tag that is used to instantiates a class that confirms to the JavaBeans specification.

Ex:
<body>
<h1>Value of paisa into rupee </h1>
<s:bean name="kites.javabean.ConvetPaisaIntoRupees">
<s:param name="paisa" value="100" />
100 Paisa = <s:property value="rupees" /> Rupees
</s:bean>
</body>
-----------------------------------------------------------------------------------------------------
Date Tag

- Date tag is used to output the date object into the required format.

Ex:
<body>
<h2>Struts2_Date_Tag_Example.</h2><hr>
Current Date :
<s:date name="currentDate" format="yyyy-MM-dd"></s:date>
</body>
-------------------------------------------------------------------------------------------------------
Debug Tag

- The debug tag is a very useful debugging tag to output the content of the 'Value Stack' and also the 'Stack Context' details in the web page.
- The <s:debug /> will generate a text link named 'debug', you need to click on the text link to expand the debugging details.

Ex:
<body>
<s:debug/>
</body>

-------------------------------------------------------------------------------------------------------
include tag

- It is a generic tag that is used to include the output of html or jsp pages directly into current page.
- We can include output of another web resource into current page.

Ex:

<body><h2>Struts2_Include_tag_Example</h2>
<hr><h3>Value of include.jsp page</h3>
<s:include value="/include.jsp"></s:include>
</body>

-----------------------------------------------------------------------------------------------------------
param Tag

- This tag can be used to parameterize other tags.
- The parameters can be added with or without a name as key.
- When we declare the param tag, the value can be defined in either a value attribute or as text between the start and end tag.
- This tag has the following two paramters.
name (String) - the name of the parameter
value (Object) - the value of the parameter

Ex:
<body>
<s:bean name="kites.ParamTag" var="paramTag">
<s:param name="name">Person1</s:param>
<s:param name="age">25</s:param>
<s:param name="status">Single</s:param>
<s:param name="birthday">1st March</s:param>
</s:bean>
<ol>
<li>Name :
<s:property value="#paramTag.name" /></li>
<li>Age :
<s:property value="#paramTag.age" /></li>
<li>Status :
<s:property value="#paramTag.status" /></li>
<li>Birthday :
<s:property value="#paramTag.birthday" />
</li>
</ol>
</body>

-----------------------------------------------------------------------------------------------------------------------------
property Tag

- The property tag is a generic tag that is used to get the property of a value, which will default to the top of the stack if none is specified.

Ex:
<body>
First Name: <s:property value="fname" />
<br>
Last Name: <s:property value="lname" />
</body>

-----------------------------------------------------------------------------------------------------------------------------
push tag

- The push tag push a value onto the top of stack.
- So it can access easily by using first-level of OGNL expression language.

Ex:

<body><h2>struts2_push_tag_Example</h2>
<hr/>
<b>Simple </b><br/><br/>
<s:bean name="kites.bean.EmployeeBean"
var="empBean">
Name :
<s:property value="#empBean.emp_name"/><br/>
Address : <s:property value="#empBean.address"/>
</s:bean>

<hr/><b>Using push tag</b><br/><br/>
<s:push value="#empBean">
Name : <s:property value="emp_name"/><br/>
Address : <s:property value="address"/>
</s:push>
</body>

--------------------------------------------------------------------------------------------------------------------
Set Tag

- The set tag is a generic (Data) tag that is used to assign a value of property to another name in a specified scope.

Ex:
<body>
<h2>Struts _ SetTag_Example</h2>
<hr><s:bean name="kites.action.StudentInfoBean" var="infoBean">
</s:bean>
<h4>Simple use of set tag </h4><br/>
<s:set name="name" value="#infoBean.name" />
<s:set name="age" value="#infoBean.age" />
Student Name :<s:property value="name"/>
<br/><br/>
Student Age :
<s:property value="age"/><br/><br/><hr/>
<h4>
Set value of property in session by set tag
</h4><br/>
<s:set name="name" value="#infoBean.name"
scope="session"/>
<s:set name="age" value="#infoBean.age"
scope="session" />
Student Name :<s:property
value="#session['name']"/>
<br/><br/>
Student Age :
<s:property value="#session['age']"/><br/><br/>
</body>

------------------------------------------------------------------------------------------------------------------------
url Tag
This tag is used.to to create an URL and output it as a text format

Ex:
<s:url action="URLtag.action" var="URLtag">
<s:param name="name">Kites Softwares</s:param>
</s:url>
<s:a href="%{URLtag}">URL Tag Action (via %)</s:a>
------------------------------------------------------------------------------------------------------------------------
UI Tags

Form Tags

checkbox tag

- The checkbox tag is a UI tag that is used to render an HTML input element of type checkbox.

Ex:

<s:checkbox name="hello" label="Hello" value="true"> </s:checkbox>
<s:checkbox name="hi" label="Hi"> </s:checkbox>
<s:checkbox name="gm" label="GoodMorning">
</s:checkbox>

--------------------------------------------------------------------------------------------------------------
checkboxlist tag

- The checkboxlist tag is a UI tag that creates a series of checkboxes from a list.

Ex:
<s:checkboxlist label="Select Cities" list="cities" name="mycity" />

-------------------------------------------------------------------------------------------------------------
combobox tag

- The combobox is basically an HTML INPUT of type text and HTML SELECT grouped together to give you a combo box functionality.

Ex:

<body><h1>Struts2_Combobox_Tag_Example</h1><hr/>
<b>Select Date of birth.... </b>
<s:form action="comboBoxResult.action" namespace="/">
<h4>
<s:combobox label="Date"
headerKey="-1" headerValue="--- Select ---"
list="dates"
name="yourDate" />
</h4>
<h4>
<s:combobox label="Month"
headerKey="-1" headerValue="--- Select ---"
list="months" name="yourMonth" />
</h4>
<h4>
<s:combobox label="Year"
headerKey="-1" headerValue="--- Select ---"
list="years" name="yourYear" />
</h4>
<s:submit value="submit" name="submit" />
</s:form>
</body>

-------------------------------------------------------------------------------------------------------------------------
doubleselect tag

- The <s:doubleselect> tag is used to create two HTML drop down boxes, once the first drop down list is selected, the second drop down list will be change accordingly.

Ex:
<s:doubleselect label="Qualification" name="list1"
doubleList="top == 'Degree' ? {'MCA', 'MBA','MTech','BTech','MSc(IT)'} :
{'PGDCA', 'PGDM','PGDBM','PGDSM'}"
list="{'Degree','Diploma'}" doubleName="list2" />


------------------------------------------------------------------------------------------------------------------------
head Tag

- The <s:head> tag is used to renders parts of the HEAD section for an HTML file.

Ex:
1)
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
<body>

2)
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>My page</title>
<s:head theme="ajax" calendarcss="calendar-green"/>
</head>
<body>

------------------------------------------------------------------------------------------------------------------------
file upload
- We use a struts2 file tag for uploading a file.

Ex:

JSP Part
--------
<body>
<h1>Struts2_file_Tag_Example</h1><hr/>
<s:form action="fileUploadAction.action" method="post"
enctype="multipart/form-data" namespace="/">
<s:file name="Uploadfile" label="Upload file : "> </s:file>
<s:submit label="Submit"></s:submit></s:form>
</body>

struts.xml part
---------------

<action name="fileUploadAction" class="kites.action.FileUploadAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">text/html</param>
<param name="maximumSize">200</param>
</interceptor-ref>
<interceptor-ref name="params">
<param name="excludeParams">
dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="validation" >
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">
input,back,cancel,browse
</param>
</interceptor-ref>
<result name="success">jsp/fileUploadSuccess.jsp
</result>
<result name="input">jsp/fileupload.jsp</result>
</action>

-------------------------------------------------------------------------------------
Form/Hidden/TextField Tags

Ex:
<s:form action="Information.action">
<s:label name="formName"
value="Student Registration Form........"/>
<s:textfield name="name" label="Name"></s:textfield>
<s:textarea name="address"
label="Address" cssClass="bh"></s:textarea>
<s:password label="Password" name="password">
</s:password>
<s:radio list="{'Male','Female'}"
name="gender" label="Gender" ></s:radio>
<s:select list="course"
name="courseName" headerKey="0"
headerValue="Select Course" label="Course Name">
</s:select>
<s:hidden name="message"
value="Hello friends....." >
</s:hidden>
<s:reset></s:reset> <br><s:submit></s:submit>
</s:form>

---------------------------------------------------------------------------------------------------
label Tag

- The label tag is used to renders an HTML LABEL that allow to output <s: label name=? ? value=? ? /> combination

Ex:
<body>
label1:<s:label value="Kites" /><br>
label2:<s:label value="Softwares" />
<br>
<s:textfield label="Kites"/><br>
<s:textfield label="Softwares"/>
</body>

-----------------------------------------------------------------------------------------------------
optiontransferselect tag

- The Optiontransferselect tag is a generic UI tag that creates an option transfer select component.
- There are two <select ...> tags with buttons in the middle of them.
- With the help of these button tag, you can transfer selected data form one select box to another select box.

Ex:
<body><h2>Struts2_Optiontransferselect_Example1
</h2><hr>
<s:form action="resultAction.action">
<s:optiontransferselect
leftTitle="List of indian cities.. "
headerKey="0"
headerValue="----Select Indian city-----"
name="IndiaCity"
list= "indianCityName"
doubleHeaderKey="0"
doubleHeaderValue="----Select American
city-----"
rightTitle="List of American cities... "
doubleList="americanCityName"
doubleName="americanCity">
</s:optiontransferselect>
<s:submit> </s:submit>
</s:form></body>

------------------------------------------------------------------------------------------------------
optgroup tag

- The optgroup tag is a generic Form_UI tag that creates an optgroup component which needs to reside within a select tag <s:select>.

Ex:
<body><h1>StrutsOptGroup_Tag_Example</h1><hr>
<s:form action="ResultOptGroup.action">
<s:select label="Select City"
name="Cites"
list="nameofCity">
<s:optgroup label="City_of_UP"
list=" upCitiesName" />
<s:optgroup label="City_Of_UttraKhand"
list="%{#{'Rudrapur':'Rudrapur','RamNagar':'RamNagar','Doon':'Doon'}}" />
</s:select>
<s:submit></s:submit>
</s:form>
</body>

------------------------------------------------------------------------------------------------------
password tag

- It is a UI tag in struts framework. It display a input tag of type password.

Ex:
<s:password name="password" key="Password:"></s:password>


----------------------------------------------------------------------------------------------
radio Tag

The radio tag is a UI tag that render a radio button input field.

Ex:
<body>
<s:form action="ResultRadioTag.action">
<h2>Fill Your Details.</h2>
<s:textfield name="username" key="Name">
</s:textfield>
<s:radio list="#{'Male':'Male','Female':'Female'}"
value="Gender" name="list1">
</s:radio>
<s:radio
list="#{'Single':'Single','Married':'Married'}"
value="Status"
name="list2"></s:radio>
<s:radio
list="#{'UnEmployed':'UnEmployed','Employed':'Employed',
'Self Employed':'Self Employed'}"
value="Employement" name="list3"></s:radio>
<s:submit></s:submit>
</s:form>
</body>
-----------------------------------------------------------------------------------------------
token tag

- The s:token tag merely places a hidden element that contains the unique token.

Ex:
<body><h1>Struts_Token_Example</h1><hr/>
<s:form action="tokenAction">
<s:textfield label="Name" name="name"></s:textfield>
<s:textfield name="age" label="Age"></s:textfield>
<s:token name="token"></s:token>
<s:submit></s:submit>
</s:form></body>

--------------------------------------------------------------------------------------------------------
updownselect Tag

- The updownselect tag is a UI tag that creates a HTML select component with buttons to move up and down the elements in the select component.

Ex:
<body>
UpdownSelect Tag Example
<s:form action="ResultUpDownSelect">
<s:updownselect
list="#{'Fun Cinema':'Fun Cinema','PVR':'PVR','WAVE':'WAVE'
,'INOX':'INOX','EROSE':'EROSE'}"
name="favMultiplex" headerKey="-1" headerValue="--- Please Select ---"
size="4" />
<s:submit></s:submit>
</s:form>
</body>
-------------------------------------------------------------------------------------------------------
actionerror and actionmessage tag

- It is a non-form UI tag in struts framework.

Ex:
<body><h1>Actionerror_Tag_Example</h1><hr>
<font color="Red" ><s:actionerror/></font>
<s:form action="LoginValidation">
<s:textfield name="loginID" label="LoginID">
</s:textfield>
<s:submit label="Login"></s:submit>
</s:form></body>
<td >
<font color="green"><s:actionmessage/></font></td>

Action Class

public String execute(){
if (getLoginID().equals("kites")) {
addActionMessage("You are a valid user.");
return SUCCESS;
}
else {
addActionError(
"Please enter valid login id");
return ERROR;
}
}

-------------------------------------------------------------------------------------------------------
fielderror Tag

- The fielderror tag is a UI tag that render field errors if they exists.

Ex:
<body>
<s:actionmessage />
<s:form action="ResultFieldErrorTag.action">
<s:textfield name="userName" key="Username">
</s:textfield>
<s:password name="password" key="Password:">
</s:password>
<s:submit></s:submit>
</s:form>
</body>

Action Class
public String execute() {

if (getUserName().equals("Kites")
&& getPassword().equals("Kites")) {
addActionMessage(
"You are a valid user.");
return SUCCESS;
}
if (!(getUserName().equals("Kites")))
addFieldError(
"userName", "Invalid username!");

if (!(getPassword().equals("Kites")))
addFieldError(
"password", "Invalid password!");
return ERROR;
}

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

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>

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