Digesting Struts 2 and Dojo

Digesting Struts 2 and Dojo

I was playing around with Struts 2 and Ajax mainly Dojo. Now how would one wire a struts action to return Dojo – JavaScript object? We will examine this below and setup a sample app that will use Struts and Dojo. We offer this as an alternative to JSON. The advantage of this over JSON is that an exist Struts 2 application could still generate JavaScript Objects without interfering with the Java classes. So where as when JSON is used your program must return a JSON object here your program can return normal data to pages and from these JavaScript objects can be constructed and used.

We will load a user’s information on selection of the user and dynamically append the user’s details.


Once the user is selected we will have his information dynamically appended to the screen as below:


The way this application will function is that struts will on success return a result to a JSP that will then dynamically have the XML created. The dojo.io.bind will then read in this XML and generate a JavaScript object with which we can use to update the page. We will start by creating the project for the application in Eclipse (Similar process for Netbeans)


The classes look like:


package struts2dojoexample.action;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.apache.struts2.ServletActionContext;

import org.apache.struts2.interceptor.ServletRequestAware;

import org.apache.struts2.interceptor.ServletResponseAware;


import struts2dojoexample.pojo.User;


import com.opensymphony.xwork2.ActionSupport;


public class LoadUserAction extends ActionSupport implements ServletRequestAware,

ServletResponseAware {


private String user;

private String username;

private String password;

private HttpServletRequest request;

private HttpServletResponse response;


public String execute() {

User user1 = new User();




user1.setStreetAddress(“On Earth”);


// Put the DTO in request so we can use it to render XML in the JSP.

getServletRequest().setAttribute(“user”, user1);

return SUCCESS;



public void setUsername(String username) {

this.username = username;



public String getUsername() {

return username;



public void setPassword(String password) {

this.password = password;



public String getPassword() {

return password;



public void setUser(String user) {

this.user = user;



public String getUser() {

return user;




public void setServletRequest(HttpServletRequest request){

this.request = request;



public HttpServletRequest getServletRequest(){

return request;



public void setServletResponse(HttpServletResponse response){

this.response = response;



public HttpServletResponse getServletResponse(){

return response;






As you can see in Struts 2 you can implement ServletRequestAware and ServletResponseAware

When these are implemented we now have access to our session.


package struts2dojoexample.pojo;


import java.lang.reflect.Field;


public class User {


private String username;

private String password;

private String surname;

private String emailAddress;

private String streetAddress;


public void setUsername(String username) {

this.username = username;



public String getUsername() {

return username;



public void setPassword(String password) {

this.password = password;



public String getPassword() {

return password;



public void setSurname(String surname) {

this.surname = surname;



public String getSurname() {

return surname;



public void setEmailAddress(String emailAddress) {

this.emailAddress = emailAddress;



public String getEmailAddress() {

return emailAddress;



public void setStreetAddress(String streetAddress) {

this.streetAddress = streetAddress;



public String getStreetAddress() {

return streetAddress;



public String getAsXML(){

StringBuffer sb = new StringBuffer(512);

sb.append(“<user username=\”” + username + “\” “);

sb.append(“surname=\”” + surname + “\” “);

sb.append(“emailAddress=\”” + emailAddress + “\” “);

sb.append(“streetAddress=\”” + streetAddress + “\”>\n”);


return sb.toString();



* Overriden toString method.


* @return A reflexivelybuilt string representation of this bean.


public String toString() {


String str = null;

StringBuffer sb = new StringBuffer(1000);

sb.append(“[“ + super.toString() + “]={“);

boolean firstPropertyDisplayed = false;

try {

Field[] fields = this.getClass().getDeclaredFields();

for (int i = 0; i < fields.length; i++) {

if (firstPropertyDisplayed) {

sb.append(“, “);

} else {

firstPropertyDisplayed = true;


sb.append(fields[i].getName() + “=” + fields[i].get(this));



str = sb.toString().trim();

} catch (IllegalAccessException iae) {



return str;


} // End toString().



Next we have the web.xml:





<?xml version=“1.0” encoding=“UTF-8”?>


<web-app version=“2.4” xmlns=http://java.sun.com/xml/ns/j2ee&#8221; xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&#8221;>















<!– Session timeout config. –>





<!– Welcome file config. –>






The struts.xml

<?xml version=“1.0” encoding=“UTF-8” ?>


“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”





<constant name=“struts.devMode” value=“true” />


<package name=“default” namespace=“/” extends=“struts-default”>

<action name=“LoadUserAction” class=“struts2dojoexample.action.LoadUserAction”>

<result name=“success”>/User.jsp</result>





The javascript files are list below:


We have the ControlEvents.js this is where we control the events the user creates like the select list drop down menu.

Dojo.js is the dojo toolkit downloadable from http://www.dojotoolkit.org/

User.js is the script file container the user object in JavaScript. In the ControlEvents.js we use the JSDigester that is provided by the JavaWebparts tags. This enables us to generated JavaScript objects.

ControlEvents.js looks like this:


var user = null;

var aconsole = null;

// This function is called when the User dropdown selection changes.

function loadUser() {

// If an operation is in progress, usually involving the server, don’t do it.

//if (processing) { return false; }

// Get name of selected collection.

var username =document.getElementById(“userslist”).value;

// Ignore the first item, our “dummy” collection.

if (username == “none”) {

return false;


// Make AJAX call.


url: “LoadUserAction.action”,

content: {user: username},

error: function(type, errObj) { alert(“Error”); },

load: function(type, data, evt) {

// Now that we have received back the XML describing the collection,

// we’ll use JSDigester to parse it.

var jsDigester = new JSDigester();

jsDigester.addObjectCreate(“user”, “User”);


user = jsDigester.parse(data);


if (aconsole != null ) {

removeAllChildren ( aconsole );


var div = document.createElement(“p”);

var txt=document.createTextNode(“Name: “ +user.username );

div.appendChild ( txt );

txt=document.createTextNode(“Surname: “ +user.surname );

var div1 = document.createElement(“p”);

div1.appendChild ( txt );

txt=document.createTextNode(“Email Address: “ +user.emailAddress );

var div2 = document.createElement(“p”);

div2.appendChild ( txt );

txt=document.createTextNode(“Street Address: “ +user.streetAddress );

var div3 = document.createElement(“p”);

div3.appendChild ( txt );






mimetype: “text/plain”,

transport: “XMLHTTPTransport”




function removeAllChildren( node ){

var childCount = node.childNodes.length;

for ( var count = 1; count <= childCount; count++) {

node.removeChild ( node.childNodes[0] );




User.js :

// User object.

function User() {

this.username = null;

this.surname = null;

this.emailAddress = null;

this.streetAddress = null;


User.prototype.setUsername = function(inName) {

this.username = inName;


User.prototype.getUsername = function() {

return this.username;


User.prototype.setSurname = function(inSurname) {

this.surname = inSurname;


User.prototype.getSurname = function() {

return this.surname;


User.prototype.setEmailAddress = function(inEmailAddress) {

this.emailAddress = inEmailAddress;


User.prototype.getEmailAddress = function() {

return this.emailAddress;


User.prototype.setStreetAddress = function(inStreetAddress) {

this.streetAddress = inStreetAddress;


User.prototype.getStreetAddress = function() {

return this.streetAddress;


User.prototype.toString = function() {

return “User=[username=” + this.username +

“,surname=” + this.surname +

“,emailAddress=” + this.emailAddress + “,streetAddress=” + this.streetAddress + “]”;



The libraries:



There some additional libraries for expansion of this application like the MySQL driver for Database connectivity to MySQL.

There you are it runs. So we managed to dynamically update a page and translate our Java in to JavaScript. This example could be extended and enhanced to embrace the vast functionality of the Dojo Toolkit.