Using struts2-jquery for Ajax

Now struts2 is providing support for the most popular client side javascript JQuery using plugin (struts2-jquery-plugin-2.5.1.jar). you can implement ajax based funcationalities into your application without any effort and without writing any other javascript. strut2 was using dojo based support for ajax in pervious version but now they have implemented JQuery based ajax features. you need to download struts2-jquery-plugin-2.5.1.jar and set it in your application's classpath.
To support the JQuery based fucntionality, you need to include extra jsp taglib into you jsp page. Following is the simple exambple using JQuery plugin in JSP page.

Index.jsp

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

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

<html>

 <head>

    <sj:head jqueryui="true" jquerytheme="redmond" />

  </head>

  <body>

    <sj:a id="ajaxlink" 

        href="ServerTime" 

        targets="result" 

        indicator="myDefaultIndicator" 

        button="true" 

        buttonIcon="ui-icon-refresh"

    >

        Run AJAX Action

    </sj:a>

    <div id="result">Result will be here.</div>

    

    <img id="myDefaultIndicator" src="ajax-loader.gif" alt="Loading..." style="display:none"/>

  </body>

</html>




JSP page to be shown for result "ServerTime.jsp"
<%=""+new java.util.Date()%>

Action class "ServerTime.java"
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class ServerTime extends ActionSupport {
    public String execute(){
        System.out.println("Server time checked");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace(System.out);
        }
        return SUCCESS;
    }
}


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" />
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <package name="/" extends="struts-default">
        <action name="ServerTime" class="ServerTime">
            <result>/ServerTime.jsp</result>
        </action>
    </package>
</struts>


5 comments:

Anonymous said...

sorry but your example is wrong you include the right taglib, but you use the old dojo (sx tags) head and div tags.

Hemraj said...

thank you for suggestion. That was by mistake. Actually I tested this program using dojo also.

bootstrap said...

hi how can i display variables from the index page on the result page

javajoseph said...

It was mind blowing thank you for this kind of help by coding.I really appreciate that.

Lijo p said...

How can I use submit button with above example?

Popular Posts