Access Keys:
Skip to content (Access Key - 0)

Ajax

Labels

dojo dojo Delete
ajax ajax Delete
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

AppFuse ships with a number of Ajax libraries:

DWR is Easy Ajax for Java. It allows you to easily expose Java objects (including Spring beans) as JavaScript objects. It's one of the best available libraries for Ajax development. To learn more about DWR and how it works, see Developing AJAX Applications the Easy Way by Joe Walker.

Prototype and Script.aculo.us are both libraries that simplify Ajax development. By using them, you won't have to worry as much about browser compatibility issues.

For good documentation about Prototype, see:

The best Script.aculo.us documentation is available on the Script.aculo.us Wiki.

In addition to these libraries, Struts 2 and Tapestry both include Dojo. JSF and Spring MVC do not ship with any built-in Ajax libraries.

Here is a dojo example using Struts2. There is a normal action with a method save and a set method for the object EvenSpan which holds an id and a name.

<script type="text/javascript">
	djConfig = { isDebug: false };
</script>
<script type="text/javascript" src="../scripts/dojo/dojo.js"></script>

<script type="text/javascript">
  dojo.require("dojo.event.*");
  dojo.require("dojo.io.*");

   function callback(type, data, evt){
        if (type == 'error'){
          alert('Error when retrieving data from the server!');
        }
     }
  
	function doOnCellEdit(id,value){
	        dojo.io.bind({ url: 'eventSpan.html',
	                       handler: callback,
	                       content: {'method:save':true, 'eventSpan.name':value,'eventSpan.id':id }
                    	});
		return true;
    }
</script>

---------------------------------------------------------------------------------------------------------
this part is an extension on the following fine tutorial:
http://cwiki.apache.org/S2WIKI/struts-2-spring-2-jpa-ajax.html
take care: the tutorial does not do anything apart from demonstrating the working of ajax. the java code is prototype only.

This tutorial misses out on 3 things:
1a) integration it within appfuse setup, taking care of the dojo files
1b) integration it within appfuse setup, taking care of the importing
order of the js files
2) getting it working with the decorator, or better without

1a) the dojo files can't be run from the struts.jar file.

To solve this open the struts2-core-2.0.6.jar
copy the dojo folder into
src/main/webapp/struts/dojo

Open your web.xml and make sure the staticFIlter is including the right
folder:

    <filter>
        <filter-name>staticFilter</filter-name>
        <filter-class>org.appfuse.webapp.filter.StaticFilter</filter-class>
        <init-param>
            <param-name>includes</param-name>
            <param-value>/struts/dojo/*</param-value>
        </init-param>
    </filter>

1b) make sure the dojo files are imported first.
To do this open your /src/main/webapp/decoraters/default.jsp file and add this line above! all other js imports:
<s:head theme="ajax" debug="true"/>

(otherwise it will conflict with at least the scriptaculous.js)

2) make sure your ajax return string will not be decorated.
There are many option but i like to do this:

open your decorators.xml file:

<decorators defaultdir="/decorators">
    <excludes>
        <pattern>/*ajax=true*</pattern>
        <pattern>/*decorate=false*</pattern>
        <pattern>/struts/dojo/*</pattern> <!-- OK to remove if you're
not using Struts -->
        <pattern>/resources/*</pattern>
    </excludes>
    <decorator name="default" page="default.jsp">
        <pattern>/*</pattern>
    </decorator>
</decorators>

I added the decorate=false part. URLs with this parameter will not be
decorated.

So an example would be nice right?

Below an ajaxTest.jsp page which will be the caller.
Then an ajaxReturn.jsp page which will be the returned data.
I expect you can make an AjaxAction with the methods String ajax(),
getPersons() etc..by your self.

This is connected by struts like this:

        <action name="ajax" class="ajaxTest">
            <result>/WEB-INF/pages/employee/ajaxTest.jsp</result>
            <result
name="ajax">/WEB-INF/pages/employee/ajaxReturn.jsp</result>
        </action>

The ajaxTest.jsp:

<%@ taglib prefix="s" uri="/struts-tags"%>
    <head>
        <script type="text/javascript">
            dojo.event.topic.subscribe("/edit", function(data, type,
request) {
            alert("type: "+type);
            alert("data: "+data);
            if(type="load"){
                document.getElementById("result").innerHTML=data;
            }
           
            });
        </script>
    </head>

<!-- URL link to struts action-->
<s:url id="ajaxText" action="ajax" method="ajax" >
<s:param name="decorate" value="false" />
</s:url> 

<!-- Div where content will be displayed -->
<s:div theme="ajax" id="weather" href="${ajaxText}">
    loading content... from the ajax action the ajax method is called.
than the ajaxReturn.jsp is rendered here.
</s:div>


<p>Persons</p>
<s:if test="persons.size > 0">
    <table>
        <s:iterator value="persons">
            <tr id="row_<s:property value="id"/>">
                <td>
                    <s:property value="firstName" />
                </td>
                <td>
                    <s:property value="lastName" />
                </td>
                <td>
                <!-- call the remove method on the ajax action no return-->
                    <s:url id="removeUrl" action="ajax" method="remove">
                        <s:param name="id" value="id" />
                        <s:param name="decorate" value="false" />
                    </s:url>
                    <s:a href="%{removeUrl}" theme="ajax" >Remove</s:a>
                   
                    <!-- call the edit method an the ajax action. the
result (ajaxResult.jps)
                    will be handed to the edit javascript mothed
attached to dojo (above) -->
                    <s:url id="editUrl" action="ajax" method="ajax">
                        <s:param name="id" value="id" />
                        <s:param name="decorate" value="false" />
                    </s:url>
                    <s:a href="%{editUrl}" id="a_%{id}" theme="ajax"
notifyTopics="/edit">Edit</s:a>
                </td>
                <td>
                <a href=ajax!remove.html?id=2>remove me no ajax</a>
                </td>
            </tr>
        </s:iterator>
    </table>
</s:if>

<hr>
<div id=result></div>

The ajaxResult.jsp:

<%@ taglib prefix="s" uri="/struts-tags"%>
Make some nice form here. Now show all persons.
<s:iterator value="persons">
<table><tr><td><s:property value="firstName" /></td>
<td><s:property value="lastName" /></td>
</tr>
</table>
    </s:iterator>

OK here is my action to:

package nl.incipio.match.webapp.action;

import java.util.List;

import org.appfuse.model.User;

import com.opensymphony.xwork2.Preparable;

import nl.incipio.match.util.MyBaseAction;

public class AjaxTestAction extends MyBaseAction implements Preparable {
    private static final long serialVersionUID = 378605805550104346L;

    private List<User>        persons;

    private Long              id;

    @Override
    public String execute() throws Exception {
        log.debug("just getting the stuf");
        persons = (List<User>) getRequest().getAttribute("persons");
        if (persons == null) {
            log.debug("just ones please");
            persons = userManager.getUsers(null);
            getRequest().setAttribute("persons", persons);
        } else {
            log.debug("persons" + persons.size());
        }
        return SUCCESS;
    }

    public List<User> getPersons() {
        return persons;
    }

    public void setPersons(List<User> persons) {
        this.persons = persons;
    }

    public String remove() throws Exception {
        log.debug("do some removing here when i feel like it id:" + id);
        if (persons != null) {
            log.debug("before persons" + persons.size());
            persons.remove((id.intValue() - 1));
            log.debug("after persons" + persons.size());
        }
        return SUCCESS;
    }

    public String save() throws Exception {
        log.debug("do some saving here when i feel like it");
        return execute();
    }

    public String ajax() {
        log.debug("ajax is doing something id:"+id);
        return "ajax";
    }

    public String edit() throws Exception {
        log.debug("do some editing here when i feel like it");
        return execute();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void prepare() throws Exception {
        log.debug("i'm getting prepared!!!");

    }
}

spring config in applicationContext.xml:

     <bean id="ajaxTest"
class="nl.incipio.match.webapp.action.AjaxTestAction">
        <property name="userManager" ref="userManager"/>
    </bean>
Adaptavist Theme Builder (4.0.0-M8) Powered by Atlassian Confluence 3.1, the Enterprise Wiki.