Backporting Struts 2 to JDK1.4 or JDK 1.3 using Retrotranslator

Struts 2 framework and its dependencies available currently are compiled using JDK 1.5 and if you want to use same framework on JDK1.4 then you will require to backport these jars. Struts 2 framework core jars and its plugin jars can be translated to JDK 1.4 or 1.3 using Retrotranslator utility.

How can you set devMode to dynamically load struts.xml file in Struts 2?

The constant element has a name attribute and a value attribute. The struts.devMode setting determines whether or not the Struts application is in development mode. By default, the value is false, meaning the application is not in development mode.

AJAX Example code showing XML response in a DIV tag

This is an example code which demonstrates how we can show the response from a XML file to the DIV tag.

<html>
<head>
<title>Using responseText with innerHTML</title>
 
<script type="text/javascript">
var xmlHttp;
 
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}
 
function startRequest() {
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", "response.xml", true);
    xmlHttp.send(null);
}
 
function handleStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            document.getElementById("results").innerHTML = xmlHttp.responseText;
        }
    }
}
</script>
</head>
 
<body>
    <form action="#">
        <input type="button" value="Search"
                onclick="startRequest();"/>
    </form>
    <div id="results"></div>
</body>
</html>


Notice the line in Javascript.

document.getElementById("results").innerHTML = xmlHttp.responseText;

This is doing all the magic for you.

Below are the contents of reponse.xml

<table border="1">
    <tbody>
        <tr>
            <th>My Name</th>
            <th>Location</th>
            <th>Age</th>
        </tr>
        <tr>
            <td>John</td>
            <td>NH</td>
            <td>20</td>
        </tr>
        <tr>
            <td>Peter</td>
            <td>CA</td>
            <td>25</td>
        </tr>
        <tr>
            <td>Hary</td>
            <td>NC</td>
            <td>33</td>
        </tr>
    </tbody>
</table>


Keep both the files in the same directory on server and run it.

Hello World example - AJAX

Here is example code which demonstrates AJAX interaction displaying "Hello World" along with the server response which is stored at server side in the file serverResponse.xml
 
Contents of HelloWorld.html
 
<html>
<head>
<title>Simple XMLHttpRequest</title>
<script type="text/javascript">
var xmlHttp;
 
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}
 
function startRequest() {
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", "serverResponse.xml", true);
    xmlHttp.send(null);
}
 
function handleStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            alert("Hello World: Response from server is - " + xmlHttp.responseText);
        }
    }
}
</script>
</head>
 
<body>
    <form action="#">
        <input type="button" value="Say Hello"
                onclick="startRequest();"/>
    </form>
</body>
</html>
 
Contents of serverResponse.xml
 
Hello from Server!



AJAX Hello world example, AJAX Hello world, Hello world AJAX, AJAX simple example, easy steps for AJAX, beginners AJAX, AJAX Example for beginners, AJAX from scratch, AJAX in Action, Simple AJAX examples

What are the status values you need to deal with when working with AJAX

The XMLHttpRequest object has few properties
 
onreadystatechange: The event handler that fires at every state change, typically a call to a JavaScript function.
 
readyState: The state of the request. The five possible values are 0 = uninitialized, 1 = loading, 2 = loaded, 3 = interactive, and 4 = complete.
 
responseText: The response from the server as a string.
 
responseXML: The response from the server as XML. This object can be parsed and examined as a DOM object.
 
status: The HTTP status code from the server (that is, 200 for OK, 404 for Not Found, and so on).
 
statusText: The text version of the HTTP status code (that is, OK or Not Found, and so on).
 
 
Here is a example code which demonstrates how these atributes can be used
 
 
function doSomething() {
 //..do something here, like adding parameter values etc...
 xmlHttp.open("GET", url);
 xmlHttp.onreadystatechange = callback;
 xmlHttp.send(null);
}
function callback() {
  if (xmlHttp.readyState == 4) {
    if (xmlHttp.status == 200) {
        //do you required work here
    }
  }
}
 
Notice the line 
xmlHttp.onreadystatechange = callback;
 
in doSomething method which is assigning a value as "callback" to the onreadystatechange attribute. 
The value is name of a method which called every time readystate of XMLHttpRequest object is changed.
 



AJAX request status, AJAX code example, AJAX code for checking status values of http request object, AJAX programming check of http request, working with request status in AJAX

How to Create an Instance of the XMLHttpRequest Object - AJAX

XMLHttpRequest is backbone of AJAX framework. We have to first create an XMLHttpRequest object using JavaScript before we can use the object to send request. You can use JavaScript in a couple of ways to create an instance of XMLHttpRequest. Internet Explorer implements XMLHttpRequest as an ActiveX object, and other browsers such as Firefox, Safari, and Opera implement it as a native JavaScript object. Because of these differences, the JavaScript code must contain logic to create an instance of XMLHttpRequest using the ActiveX technique or using the native JavaScript object technique.
 
var xmlHttp;
 
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

Struts 2 Integer Validation Example


integer validation example struts 2, struts 2 integer validation, number validating struts 2, regular expression validation struts 2, struts 2 validator

The validator type "int" in struts 2 is a range validator. It does not validate if the input is a valid integer. Therefore we would require to use regular expression to validate the integer. This example considers zip Code field which should be a valid integer.

This example uses AJAX for displaying the result on the same page. The contents of output.jsp are shown if the input validation passes.

MyAction.java
  
public class MyAction extends ActionSupport {

private String zipCode;

public String execute() throws Exception {

return SUCCESS;

}

public String getZipCode() {

return zipCode;

}

public void setZipCode(String zipCode) {

this.zipCode=zipCode;

}
}


MyAction-validation.xml
  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">





zipCode

Zip code should be a valid number






input.jsp

  
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<s:head theme="ajax" />

<title>Integer Validation Test</title>

</head>

<body>

<s:actionerror />

<s:fielderror />

<s:div id="showResult" theme="ajax" loadingText="Loading..." />

<s:form id="myAction" action="myAction" method="post"

validate="true">

<s:textfield key="addressLine1" label="Address Line 1" labelposition="left" cssStyle="size: 15"></s:textfield>

<s:textfield key="addressLine2" label="Address Line 2" labelposition="left" cssStyle="size: 15"></s:textfield>

<s:textfield key="city" label="City" labelposition="left" cssStyle="size: 15"></s:textfield>

<s:textfield key="state" label="State" labelposition="left" cssStyle="size: 15"></s:textfield>

<s:textfield key="zipCode" label="Zip Code" labelposition="left" cssStyle="size: 15" required="true"></s:textfield>

<s:textfield key="country" label="Country" labelposition="left" cssStyle="size: 15"></s:textfield>

<s:submit theme="ajax" targets="showResult" />

</s:form>

</body>
</html>


output.jsp

  
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

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



<html>

<head></head>

<body>

Valid Data Entered !!

</body>

</html>


struts.xml
  

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



/output.jsp
/input.jsp




Struts 1 vs Struts 2

Here are few comparison of Jakarta Struts framework version 1.X and 2.X
The entire approach has been changed in Struts 2 by introduction of dependency injection and interceptors. Here are few key differences...


1. Servlet Dependency:


Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse objects are passed to the execute method when an Action is invoked.

In case of Struts 2, Actions are not container dependent because they are made simple POJOs. In struts 2, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2 Actions can access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.

2. Action classes

Struts 1 requires Action classes to extend an abstract base class. Extending an abstract class instead of interface is one of design issues of struts 1.x framework that has been resolved in the struts 2 framework.
In case of Struts 2 Action class may or may not implement interfaces to enable optional and custom services. In case of Struts 2 , Actions are not container dependent because they are made simple POJOs. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with an execute signature can be used as an Struts 2 Action object. Struts 2 also provides a way to maintain action objects using spring container.

3. Validation


Struts1 and Struts 2 both supports the manual validation via a validate method.
Struts1 uses validate method on the ActionForm, or validates through an extension to the Commons Validator. However, Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

4. Threading Model

In Struts1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts1 Actions and requires extra care to develop. However in case of Struts 2, Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)

5. Testability

Testing Struts1 applications are a bit complex. A major hurdle to test Struts1 Actions is that the execute method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts1. But the Struts 2 Actions can be tested by instantiating the Action, setting properties and invoking methods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent, hence testability is quite easy in struts2.

6. Harvesting Input

Struts1 uses an ActionForm object to capture input. And all ActionForms needs to extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input.
However Struts 2 uses Action properties (as input properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in struts2, Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.

7. Expression Language

Struts1 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can also use JSTL, however it supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

8. Binding values into views

In the view section, Struts1 uses the standard JSP mechanism to bind objects (processed from the model section) into the page context to access. However Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows the reuse of views across a range of types which may have the same property name but different property types.

9. Type Conversion

Usually, Struts1 ActionForm properties are all Strings. Struts1 uses Commons-Beanutils for type conversion. These type converters are per-class and not configurable per instance. However Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.

10. Control Of Action Execution

Struts1 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle. However Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions as needed.


Comparison of struts 2 with struts 1, comparing struts 1 and Struts 2, struts 1 or struts 2 which one to use, struts 2 vs struts 1

Search Web......