johnnieb
johnnieb

Reputation: 4522

Simple JSON example using Struts 2.2.x?

I’m having trouble getting JSON results working with Struts 2.2.1.1.

Does anyone have a simple working example that returns a JSON result to a JSP using Struts 2.2.1.1 and is ready to run in Eclipse as a dynamic web project?

Please include the struts.xml, action class and JSP code. Also, note dependencies. Thank you.

Upvotes: 2

Views: 11862

Answers (4)

johnnieb
johnnieb

Reputation: 4522

Here’s how to create a simple JSON example using the Struts 2 jQuery plugin.

  1. Go to Struts2 jQuery Plugin Showcase
  2. Navigate to Ajax Forms > Buttonset / Checkboxes
  3. Review the code for Buttonset that was populated from AJAX JSON Result. This is code I selected to create a simple example.
  4. Create dynamic web project in Eclipse
  5. Create a Java package and name it test.
  6. Download the Struts 2 jQuery plugin showcase source (struts2-jquery-showcase-x.x.x-sources.jar) and extract the JAR file.
  7. Import Echo.java, JsonSample.java, and ListValue.java into the test package and move the code into the package with quick fix.
  8. Change the class annotation in Echo.java and JsonSample.java to @ParentPackage(value = "test")
  9. In addition to the standard Struts 2 libraries, ensure that the struts2-json-plugin-x.x.x.jar, struts2-jquery-plugin-x.x.x.jar, and struts2-convention-plugin-x.x.x.jar files are in your classpath.
  10. Create a struts.xml file and add the following XML:

    <struts>
        <constant name="struts.devMode" value="true" />
        <constant name="struts.convention.action.packages" value="test" />
        <package name="test" extends="json-default” namespace="/">
        </package>
    </struts>
    
  11. Create an index.jsp file and insert the following code:

    <s:form id="form2" action="echo" theme="xhtml">
     <s:url id="remoteurl" action="jsonsample" />
    <sj:checkboxlist href="%{remoteurl}" id=“remoteCheckboxlist” name="echo"  list="languageList" label="Language" />
    <sj:submit targets="formResult" value="AJAX Submit" indicator=“indicator” button="true"/>
    </s:form>
    
  12. Run the example.

Upvotes: 4

Prabhakar Manthena
Prabhakar Manthena

Reputation: 2303

Try this, will help you in Struts 2.0.14 with jsonplugin-0.32.jar.

struts.xml:

<struts>
     <package name="example" extends="json-default">
        <action name="HelloWorld" class="example.HelloWorld"  >
            <result type="json" />
        </action>
              <action name="HelloWorld1" class="example.HelloWorld"  >
            <result name="success" >example/HelloWorld.jsp</result>
        </action>
    </package>
</struts>

action class Helloworld.java:

package prabhakar;

import glb.DB;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Prabhakar
 */
public class HelloWorld  {


    private List<StateMaster> stateList= new ArrayList<StateMaster>();
    private List<RegnMaster> regnList= new ArrayList<StateMaster>();

    private Integer stateId;
    public Integer getStateId()
    {
    return this.stateId;
    }
    public void setStateId(Integer stateId)
    {
    this.stateId=stateId;
    }
    public List<StateMaster> getStateList() {
        return stateList;
    }

    public void setStateList(List<StateMaster> stateList) {
        this.stateList = stateList;
    }
     public void setRegnList(List<RegnMaster> regnList) {
        this.regnList = regnList;
    }
    public List<RegnMaster> getRegnList() {
        return regnList;
    }

    public String execute() throws Exception {

        stateList=DB.getStateData()//
        if(stateId !=null)
          {
         regnList=DB.getRegnByStateId(stateId);
          }

        //setMessage(getText(MESSAGE));
        return "success";
    }

    /**
     * Provide default valuie for Message property.
     */

}

You can directly call HelloWorld.action to view the JSON data or else you can bind the JSON data to a form element below.

JSP page HelloWorld.jsp:

  /*
     Prabhakar
  */

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri="/struts-tags" %>
<script>
<%@include file="../js/jquery-1.7.1.min.js"%>
</script>
    <html>

<!-- JavaScript Plugins -->
  <script>
       function getLoad(){


       var stateId = $('#state').val();

$.getJSON('HelloWorld.action', {'stateId': stateId},
    function(data) {

           var divisionList = (data.regnList);

                var options = $("#regn");
                options.find('option')
    .remove()
    .end();
     options.append($("<option />").val("-1").text("--Select--"));
$.each(divisionList, function() {

    options.append($("<option />").val(this.regnId).text(this.regnName));
});
    }
);}
   </script>

<!-- jQuery-UI Dependent Scripts -->

    <body>
        State List <s:select name="stateId" list="stateList" id="state" listKey="stateId" onchange="getLoad()" listValue="stateName" headerKey="0" headerValue="--select--" />
        Regn List <s:select name="regnId"  list="regnList" listKey="regnId" id="regn" listValue="regnName" headerKey="0" headerValue="--select--" />
    </body>
</html>

Happy coding :)

Upvotes: 0

dbyuvaraj
dbyuvaraj

Reputation: 505

It is very simple to get Json work with struts2.

For this,

  1. you need to add struts-json plugin*(jsonplugin-0.32.jar)* to classpath.

  2. Your struts.xml file should extends json-default

    <package name="base" namespace="/" extends="json-default">
    
  3. Your action result be like this.

    <result type="json"><param name="root">jsonData</param></result>
    
  4. Inside action class, declare json as

private LinkedHashMap<K, V> jsonData new LinkedHashMap<k, V>();

and then add the result list to json like

jsonData.put("result", anyList or object);

Thats all we have to do. Then we can access the result using javascript.

Upvotes: 0

lschin
lschin

Reputation: 6811

Must see : struts2-x.x.x-all.zip /apps/struts2-showcase-2.2.1.war

Struts 2 and JSON example
Struts 2 autocompleter + JSON example

Upvotes: 0

Related Questions