Ajax with Struts Example

Ajax is a very popular and innovative technique of creating rich user interface for web applications. Some days ago, I was trying to get some new stuff on struts 1 with the new technologies and I think can it be possible to implement a very new practice technology like Ajax with old java frameworks like struts 1. Yes, we can. I find a way to implement Ajax with struts 1 mvc framework.

Here, in this post, we will implement ajax with struts in practical example. Before that we must understand the way of implementation of ajax. Ajax ( Asynchronous JavaScript And Xml) is a practice introduced by Google in which a web page can change it’s content without refreshing itself.

In our example, there will be a input box to accept the name of the visitor and a button that will send the name to the server and also show the response of the server without refreshing the page. The page be like :

Ajax Form

Ajax Form

Following are the implementation structure of our example :

  1. Firstly, we will implement a form bean (AjaxForm.java) with only one attribute as “name”.
  2. After that we will create the action class (AjaxAction.java) which will take care of Ajax request and response to the user.
  3. Then, the jsp page (AjaxExample.jsp) will be created where JQuery will be used for creating Ajax behavior in the page. JQuery is nothing but a java script library that help us to do lots of things in client playground.
  4. And the last but not the least, configuring all the things in struts-config.xml file.

AjaxForm.java

AjaxForm.java does not contain any special implementation for Ajax. It is same as the form beans are used in struts 1 application project. Bellow are the code of AjaxForm.java :


public class AjaxForm extends ActionForm {
    private static final long serialVersionUID = 7403728678369985647L;

    private String name = null;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

The AjaxForm.java has only one property named “name” and its getter and setter.

AjaxAction.java

Our AjaxAction.java contains a lot of pretty good things that enables Ajax to be worked with Struts 1 mvc framework. Here is the execute method of AjaxAction.java :


public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
    AjaxForm ajaxForm = (AjaxForm)form;
    response.setContentType("text/text;charset=utf-8");
    response.setHeader("cache-control", "no-cache");
    PrintWriter out = response.getWriter();
    out.println("Hello " + ajaxForm.getName());
    out.flush();
    return null;
}

Firstly, it typecast the form instance to AjaxForm instance, then set the content type and cache-control value to “text/text;charset=utf-8″ and “no-cache” respectively. “text/text;charset=utf-8″ says to browser that the response is a text as I have send back a text hare.You can set any type ofcontent type but its type must be match with the response body. For Ajax, we can use “text/json” or “text/xml”. “no-cache” will indicate the browser not to cache the output of this response as it is an Ajax response.

Struts 1 does not have any build in capability to handle ajax as Struts 2 does. Struts 1 simply treats an Ajax request as normal request.

So, what will be our option to handle ajax request. As we know execute method of action also contain response and request instances as an argument, we can get PrintWriter object from response and write our response to the PrintWriter instance and flash the instance. so that no farther response get back to browser. Our action just write “Hello ” and then the name of the user and send the output. The execute method returns null as ActionForward instance so that struts also does not take any farther action.

AjaxExample.jsp

The following is the code of AjaxExample.jsp tthat uses JQuery for Ajax call :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<!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">
         <title>Ajax Example in Struts 1e</title>
         <script src="/AjaxWithStruts1/js/jquery.js"></script>
         <script type="text/javascript">
             function doAjaxPost() {
                // get the form values
                var name = $('#name').val();

                $.ajax({
                    type: "POST",
                    url: "/AjaxWithStruts1/AjaxSubmit.do",
                    data: "name=" + name,
                    success: function(response){
                        // we have the response
                        $('#info').html(response);
                    },
                    error: function(e){
                        alert('Error: ' + e);
                    }
                });
            }
        </script>
    </head>
    <body>
        Enter your name please : <input type="text" id="name"><br/>
        <input type="button" value="Say Hello" onclick="doAjaxPost()"><br/>
        <div id="info" style="color: green;"></div>
    </body>
</html>

You may be little bit confused if you are not aware of JQuery. Here is the explanation of the JQuery code :

  1. var name = $(‘#name’).val(); : - here the $ is JQuery selector that uses to select any node in html whose identifier is passed as argument. If the identifier is a prefix with # that means it is a id of the html node. Here, $(‘#name’).val() contains the value of the html node whose is “name’. The text box in which user will enter her/his name is with is as name. so java script variable name will contain the name of the user.
  2. $.ajax() :- It is the method in $ variable of JQuery to call Ajax. It has five arguments here. First of all “type” which indicated the request type of ajax. It can be POST or GET. Then, “url” which indicates the url to be hit of Ajax submission. “data” will contain the raw data to be sent to the server. “success” will contain the function code that has to be call if the request get success and server sends an response to the browser. “error” will contain the function code that has to be call if the request get any error.
  3. $(‘#info’).html(response); :- will set the response of the server in to the div. In this way “Hello” + name will be shown in the div whose id is “info“.

struts-config.xml

AjaxAction is configured in struts-config.xml without any forward as struts does not need any forward in Ajax call. Following is the action configuration :

<struts-config>
    <!-- ========== Form Bean Definitions ================================== -->
    <form-beans>
        <form-bean name="ajaxForm" type="com.raistudies.forms.AjaxForm"/>
    </form-beans>
    <!-- ========== Action Mapping Definitions ============================= -->
    <action-mappings>
        <action name="ajaxForm" path="/AjaxSubmit" input="/AjaxExample.jsp"
        type="com.raistudies.actions.AjaxAction"/>
    </action-mappings>
</struts-config>

When you will submit your name in the input box the form will be like the following :

Filled Form

Filled Form

After that click on “Say Hello” button, following screen will come :

Ajax Result

Ajax Result

The server response is shown in green color. You can download code or war file of the example from bellow links. Please feel free to give feedback on tutorials.

Code : Download

War : Download

Related Posts:

Leave a comment ?

12 Comments.

  1. will u pls share me some functions which show the real advantage of ajax , like how can i implement calender via ajax

  2. I think this is among the most important info for me. And i’m glad reading your article. But should remark on some general things, The site style is ideal, the articles is really nice : D. Good job, cheers

  3. WONDERFUL TUTORIAL. THANK YOU VERY MUCH.

  4. hey….bt where is the jquery file mentioned in the jsp file?

  5. This example is ok for response from the action itself but need to replace the div content from some other page which has its own action…..please help i did search everywhere couldn’t any

    Thanks in advance

    • In such case, you have to call that action url as ajax call and then you will get the response of the view.

  6. can we store duplicate keys in request object?

  7. Wonderful example. Could you please add an example with JSON.

  8. I coulԁn’t resist commenting. Perfectly written!

  9. Sir i do have some errors !!!
    i am new to sturts!
    Can you help me?
    Thank you

Leave a Comment Cancel reply


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>