Post JSON Object Struts 2 Action

Post JSON Object Struts 2 Action

In this demo you will see how to post JSON object struts 2 action class. Below I will show you sample JSP page and Struts 2 action class and if you want to run this you could download project in the bottom link.

  • Final Project structure:

Post JSON Object Struts 2 Action

  • index.jsp page:
<%@ 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>Post JSON Object Struts 2 Action</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 postJSONData(){
        
        var firstName = $('#firstName').val(); 
        var lastName = $('#lastName').val(); 
        var json = {"firstName" : firstName,"lastName" : lastName}; 
                
        $.ajax({
            url: "postJSONDataAction"+"?jsonRequestdata="+JSON.stringify(json),
            type: 'POST',
            dataType: 'json',           
            success:function(response){
                $('#firstName').val(response.firstName);
                $('#lastName').val(response.lastName);                          
            },
            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:submit type="button" label="Post JSON data" onclick="postJSONData();return false;"/>         
    </s:form>
</body>
</html>

  • PostJSONDataAction.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 PostJSONDataAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String firstName;
    private String lastName;
    private String jsonRequestdata;
    
    @Override
    @Action(value = "/postJSONDataAction", 
        results = { @Result(name = "success", type = "json") })
    public String execute() throws Exception {
        
        //Extract JSON 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"));        
        
        //Return JSON data in response
        setFirstName("Java");
        setLastName("Honk");
        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 getJsonRequestdata() {
        return jsonRequestdata;
    }

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

  • After run application on tomcat server in eclipse output:

Post JSON Object Struts 2 Action

  • After “Post JSON data” button click it will populate input field with response from server as below:

Post JSON Object Struts 2 Action

For more information please read this tutorial

download Download Project:  Struts2AJAXjQuery

Leave a Reply

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