Struts 2 and JSON example

In Struts 2 example, you will learn how to convert an object into JSON format via “struts2-json-plugin.jar” library.

1. Get dependency library

Get the struts2-json-plugin.jar library.
pom.xml


    <!-- Struts 2 -->
    <dependency>
          <groupId>org.apache.struts</groupId>
	  <artifactId>struts2-core</artifactId>
	  <version>2.1.8</version>
    </dependency>

    <!-- Struts 2 JSON Plugins -->
    <dependency>
          <groupId>org.apache.struts</groupId>
	  <artifactId>struts2-json-plugin</artifactId>
	  <version>2.1.8</version>
    </dependency>

2. Action (JSON)

This is an Action class which will be converted into JSON format.


package com.mkyong.common.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.Action;

public class JSONDataAction{

	private String string1 = "A";
	private String[] stringarray1 = {"A1","B1"};
	private int number1 = 123456789;
	private int[] numberarray1 = {1,2,3,4,5,6,7,8,9};
	private List<String> lists = new ArrayList<String>();
	private Map<String, String> maps = new HashMap<String, String>();
	
	//no getter method, will not include in the JSON
	private String string2 = "B";
	
	public JSONDataAction(){
		lists.add("list1");
		lists.add("list2");
		lists.add("list3");
		lists.add("list4");
		lists.add("list5");
		
		maps.put("key1", "value1");
		maps.put("key2", "value2");
		maps.put("key3", "value3");
		maps.put("key4", "value4");
		maps.put("key5", "value5");
	}

	public String execute() {
               return Action.SUCCESS;
        }
	
	public String getString1() {
		return string1;
	}

	public void setString1(String string1) {
		this.string1 = string1;
	}

	public String[] getStringarray1() {
		return stringarray1;
	}

	public void setStringarray1(String[] stringarray1) {
		this.stringarray1 = stringarray1;
	}

	public int getNumber1() {
		return number1;
	}

	public void setNumber1(int number1) {
		this.number1 = number1;
	}

	public int[] getNumberarray1() {
		return numberarray1;
	}

	public void setNumberarray1(int[] numberarray1) {
		this.numberarray1 = numberarray1;
	}

	public List<String> getLists() {
		return lists;
	}

	public void setLists(List<String> lists) {
		this.lists = lists;
	}

	public Map<String, String> getMaps() {
		return maps;
	}

	public void setMaps(Map<String, String> maps) {
		this.maps = maps;
	}
	
}

3. struts.xml

To output the JSON data, you need to declared a package which extends the “json-default“, and result type as “json“.


<?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" />
	
   <package name="default" namespace="/" extends="json-default">
      <action name="getJSONResult" 
           class="com.mkyong.common.action.JSONDataAction">
       	   <result type="json" />
      </action>
    </package>
	
</struts>

4. Demo

Access the action URL, the JSONDataAction’s properties will be converted into JSON format.
http://localhost:8080/Struts2Example/getJSONResult.action

Struts 2 JSON example

JSON format…

{
   "lists":["list1","list2","list3","list4","list5"],
   "maps":
   {
     "key4":"value4","key3":"value3","key5":"value5","key2":"value2","key1":"value1"
   },
   "number1":123456789,
   "numberarray1":[1,2,3,4,5,6,7,8,9],
   "string1":"A",
   "stringarray1":["A1","B1"]
}
Hope this super simple example can give you an overall idea of how JSON plugin worked with Struts 2. However, there are still many useful settings are not cover here, make sure you read the Struts 2 JSON plugin documentation for more details.

Download Source Code

Download It – Struts2-JSON-Example.zip

Reference

  1. Struts 2 JSON plugin
  2. JSON official documentation

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
js518
Guest
js518

tkx for your excellent example , now I can use json with struts :)

ab
Guest
ab

Hi, did you have to change anything? because the source file itself does not work.

01sawasblog
Guest
01sawasblog

Hi , thank you

how can i remove ‘”maps”:’ before the “{“, i dont need it in my json code

“maps”:
{
“key4″:”value4″,”key3″:”value3″,”key5″:”value5″,”key2″:”value2″,”key1″:”value1”
},

thank you

Mohammed Hasan (Rupam)
Guest
Mohammed Hasan (Rupam)

Very Important (If you want to transfer data from Action Class to JQuery)
Without these 3 jar files you can not pass variable from Action Class to JQuery.

json-simple-1.1.jar
struts2-json-plugin-2.3.1.2.jar
commons-lang-2.6.jar

Struts.xml

jsonData

Pallab Sarkar
Guest
Pallab Sarkar

very nice tutorial. I want to know ,how can we use this json object in jsp?

sankar
Guest
sankar

Is it possible to define method in struts.xml for json-default package.
For struts-default package,we can define the method attribute and route to that method in action class.
How can we do the same in json-default package.
When I tried by writing method attribute in json-default , it throwed me nomethodfound exception

ray jhonson
Guest
ray jhonson

hI, CAN U PLZ HELP I WANT TO SHOW THE SUBSELECT MENU BASED ON SELECTED MENU BY USING JQUERY/JSON . . SUB-SELECT result OPTIONS DYNAMICALLY COME FROM ORACLE

trackback
Tech List | lazzycrazzy
jagnya
Guest
jagnya

When i execute this application it is successfully run . But instead of showing result in browser its shows an option to download the file.

But my requirement is show in browser ..How can i show the result in browser ?

VKey
Guest
VKey

Dear Friends,

I am new to struts2 concept, can any one help me in creating a grid. While displaying the grid it should contain one column which fetches the data from database and another two columns of textfield and dropdown list(dropdown should also populate from database).
Note:The database connectivity is done with the help of Hibernate

Vishal Bhatt
Guest
Vishal Bhatt

I want to use json with tiles result type .How it will do possible.Please tell me.

Martin(Argentina)
Guest
Martin(Argentina)

hello people i am working the example con struts2 version 2.3.1.2 thast ok!

Kathryn Reynolds
Guest
Kathryn Reynolds

I just couldnt leave your site before letting you know that I actually enjoyed the particular useful info you offer to your visitors…

sherry
Guest
sherry
i want in struts.xml request of type interseptor-ref name=”json” and result as type stream in a single action like : <action name="downloadAction" method="download" class="DownloadAction"> <interceptor-ref name="json"> <param name="contentType">application/json</param> </interceptor-ref> <result name="SUCCESS" type="stream"> <param name="contentType">${contentType}</param> <param name="inputName">inputStream</param> <param name="contentDisposition">attachment; filename="${fileName}"</param> </result> <result name="ERROR" type="tiles">/jsp/export.jsp</result> </action> for me input is going as JSON but data i am not able to download as stream type. how can i combine the interceptor json and result type stream together if this is not the correct way?
smile
Guest
smile

Hi sherry
Did you check this problem? I want to write two result like yours.

personData

true

true

/NewFile.html

But result ok doesn’work. Can you help me ?

sherry
Guest
sherry

Hi

i want the ajax input to be sent as JSON and response should be a download file as in result type = stream

application/json

${contentType}
inputStream
attachment; filename=”${fileName}”

/download.jsp

this is not downloading file though byte stream data i can see in firebug…
can somebody help me in understanding what the problem is with the code!!

Sanjay M
Guest
Sanjay M

mykong, thanks as always for your valuable posts!

With this example, I access the URL http://localhost:8080/Struts2Example/getJSONResult.action I get the JSON data. But I need to get a parameter (and eventually from Javascript) so when I access the same URL with
http://localhost:8080/Struts2Example/getJSONResult.action?field1=test

where the action class has a setter/getter for String field1,

but I get no response from the server at all. Please let me know if there’s any additional configuration I should be looking into. Thanks

nikhil
Guest
nikhil

Hi Sanjay, did you figure out how can we get a request parameter? If so can you please let me know.. Thanks in advance!

julian a.
Guest
julian a.

excellent, but as I can make it with annotations?

thanks for reply

:)

mahmoud
Guest
mahmoud

hi , can u put your example how to make it with annotation, and how can we use annotation to make an usual strust2 action return an jason object via an jason action via annotation

Sandeep Pandey
Guest
Sandeep Pandey

great Post :) was very helpful

Dnyaneshwar
Guest
Dnyaneshwar
Hi i can u plz check following problem i want to get values back from server to client in json format JSP function doAjaxPost() { // get the form values var name = $(‘#name’).val(); $.ajax({ type: “POST”, url: “chkName.action”, //dataType: “json”, data: {“userNameLine1” : name}, success: function(response){ // we have the response $(‘#info’).html(response); }, error: function(e){ alert(‘Error: ‘ + e); } }); } Enter your name please : ——————————– Struts2-Action class public class Test extends ActionSupport{ public String chkName() throws Exception{ HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType(“text/plain”);//”text/text;charset=utf-8″); response.setHeader(“cache-control”, “no-cache”); PrintWriter out = response.getWriter(); out.println(“Hello ” ); out.flush(); return SUCCESS; } }… Read more »
Martin
Guest
Martin

How to set the json result encoding to utf-8
I set

 <result type="json">
     <param name="root">jsonret</param>
     <param name="defaultEncoding">utf-8</param>			
 </result>	 

in action
but not work!!
Please help , Thanks a lot

trackback
Struts 2 autocompleter + JSON example

[…] Struts 2 JSON example […]

Utsav
Guest
Utsav

Thank You !!!!!!!!!!!! keep Posting…………..

ramesh
Guest
ramesh

Can u post the strtus entry for the action mapping?

Siregar
Guest
Siregar

sorry for asking again,
if every variable that has getters will be displayed? What if I want only some variables are shown, although these variables have getters

Erick Benites
Guest
Erick Benites

You can to use this:

user,
message,
^entries\[\d+\]\.createUserId

See:
https://cwiki.apache.org/confluence/display/WW/JSON%20Plugin

Good look!

Erick Benites
Guest
Erick Benites

You can to use this:

user,
message,
^entries\[\d+\]\.createUserId

See:
https://cwiki.apache.org/confluence/display/WW/JSON%20Plugin

Good look!

Erick Benites
Guest
Erick Benites

it’s code:
<result type="json">
<param name="includeProperties">
user,
message,
^entries\[\d+\]\.createUserId
</param>
</result>

roshan
Guest
roshan

HI,
Thanks for your works…
i got the json result on my browser….
can u tell me how can i use this json data now using jquery?

sarabeshwar
Guest
sarabeshwar
0 down vote favorite I just started using struts 2 last week so this question may be obvious. I have an opening form with a submit that uses an action and execute method to get the data. Then, the only way I could get jquery to work was to put an action and execute method that just returns ‘success’ and then I go onto my jquery grid with a 3rd action. whenever i am try to execute my program on browser The only problem i have is, that the json string returns as a file. So when i call the… Read more »
Gerenne
Guest
Gerenne
Hi, first of all thanks for your example, it’s great!! I have got a problem with json and struts2, I’m try to use json and in my action I have the following code: @Action(value = “view-new-graf”, results = { @Result(name = “success”, type=”json”) } ) public String obtainData(){ return “success”; } And my app launch this error: java.lang.NullPointerException at org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupport.java:49) at org.apache.jsp.WEB_002dINF.jsp.errores.error500_jsp._jspx_meth_s_005ftext_005f0(error500_jsp.java:104) at org.apache.jsp.WEB_002dINF.jsp.errores.error500_jsp._jspService(error500_jsp.java:70) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:473) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329) at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:453) at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:324) at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:415) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:191) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)… Read more »
Prakash
Guest
Prakash

Hi,

Worked like a charm on my dev machine…Tomcat 7.0, Struts 2.3.4 and struts2-json-plugin-2.3.4.jar

Thanks a lot for this example, keep posting more… :-)

Martin(Argentina)
Guest
Martin(Argentina)

hi i am working with

2.3.1.2

is very well the example!!

Kalai
Guest
Kalai

Hi
This code works fine. But when integrating it with Spring. When the objects are instantiated using Spring , the list returned from action is getting empty.

Shashank
Guest
Shashank

after i added struts2-Json plugin dependency

am getting java.lang.ClassNotFoundException: org.apache.commons.lang.xwork.StringUtils

I would be very glad if somebody could help me

Thanks
G.shashank

EderM2
Guest
EderM2

I have the same error, Can anyone help with this problem?

Reefat
Guest
Reefat

keep your struts version and struts-json-plugin version same.
i have used (struts2-json-plugin-2.3.4.jar) for (struts 2.3.4).

edgar pinó
Guest
edgar pinó

For all those who had the same problem.

I was getting the java.lang.ClassNotFoundException: org.apache.commons.lang.xwork.StringUtils using struts-2.3.4.1 compilation.

I solved the error just adding xwork-core-2.2.1.jar to my /lib folder and it worked.

Both files where co-exinting together (xwork-core-2.2.1.jar and xwork-core-2.3.4.1.jar), It worked for my JSon/Ajax test project. I dont know if they can cause any kind of conflict on a serious project.

Good luck!

Reefat
Guest
Reefat

keep your struts version and struts-json-plugin version same.
i have used (struts2-json-plugin-2.3.4.jar) for (struts 2.3.4).

Rup
Guest
Rup

Hi,
I’m facing this exception
org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException at org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:243)

what can be the root cause for this..?