Struts 2 AJAX jQuery JSON example

Struts 2 AJAX jQuery JSON example

Here you will see how to use AJAX and jQuery to send request to the server and get JSON response back from the server and process it on JSP page.

Steps:

  • Create project name: Struts2AJAXjQuery. Below is final project structure:

Struts 2 AJAX jQuery JSON example

  • pom.xml file:
<dependencies>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.16.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>2.3.16.3</version>
        </dependency>
        <!-- JASON Plug-in -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>2.3.16.3</version>
        </dependency>
        <!-- Google json-simple to convert json -->
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
</dependencies>
  • web.xml:
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>struts.devMode</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>struts.custom.i18n.resources</param-name>
            <param-value>ApplicationResources</param-value>
        </init-param>               
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
</web-app>

  • index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Struts 2 AJAX jQuery JSON example</title>
<link rel="stylesheet"
    href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" />
<script type="text/javascript"
    src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
    
    function makeAjaxCall(){
        
        var firstName = $('#firstName').val(); 
        var lastName = $('#lastName').val(); 
        var location = $('#location').val(); 
        var json = {"firstName" : firstName,"lastName" : lastName,"location" : location}; 
                
        $.ajax({
            url: "jqueryAJAXAction"+"?jsonRequestdata="+JSON.stringify(json),
            type: 'POST',
            dataType: 'json',           
            success:function(response){
                $('#firstName').val(response.firstName);
                $('#lastName').val(response.lastName);
                $('#location').val(response.location);              
            },
            error:function(jqXhr, textStatus, errorThrown){
                alert(textStatus);
            }
        });    
    }

</script>
<s:head />
</head>

<body>
    <h2 style="color: green">
        <s:text name="label.welcome" />
    </h2>
    <s:form action="" namespace="/" method="post"
        name="strutsForm">
        <s:textfield id="firstName" size="30" maxlength="50" label="First Name" value=""/>
        <s:textfield id="lastName" size="30" maxlength="50" label="Last Name" value=""/>
        <s:textfield id="location" size="30" maxlength="50" label="Location" value=""/>
        <s:submit type="button" label="Get Ajax data for server" onclick="makeAjaxCall();return false;"/>           
    </s:form>
</body>
</html>

  • ApplicationResources_en.properties
label.welcome = Struts 2 AJAX jQuery JSON example
  • JqueryAJAXAction.java:
package com.javahonk.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("json-default")
public class JqueryAJAXAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String firstName;
    private String lastName;
    private String location;
    private String jsonRequestdata;
    
    @Override
    @Action(value = "/jqueryAJAXAction", 
        results = { @Result(name = "success", type = "json") })
    public String execute() throws Exception {
        
        //Pull request data
        JSONObject json = (JSONObject)new JSONParser()
                            .parse(jsonRequestdata);
        System.out.println("First Name=" + json.get("firstName"));
        System.out.println("Last Name=" + json.get("lastName"));
        System.out.println("Location=" + json.get("location"));
        
        //Set data in response
        setFirstName("Java");
        setLastName("Honk");
        setLocation("NY");
        return ActionSupport.SUCCESS;
    }   

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getJsonRequestdata() {
        return jsonRequestdata;
    }

    public void setJsonRequestdata(String jsonRequestdata) {
        this.jsonRequestdata = jsonRequestdata;
    }
    
}

  • To run this application please configure tomcat server with eclipse using this tutorial. Right Click on project –> Run As –> Run on Server. You will see below page:

Struts 2 AJAX jQuery JSON example

  • Click “Get Ajax data from server” to get JSON response from server (Please note: If you want to pass data in request to the server just enter value in input fields). You will see below page with data:

22

For more information about Struts 2 AJAX jQuery JSON example please read this tutorial

download Download Project:  Struts2AJAXjQuery

One thought on “Struts 2 AJAX jQuery JSON example

  1. Hi Am getting the below Error with above example

    org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException

Leave a Reply

Your email address will not be published. Required fields are marked *