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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: Blue Coaster33()

  • Pingback: Tech List | lazzycrazzy()

  • 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

    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

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

  • Martin(Argentina)

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

  • http://www.youtube.com/watch?v=K6tU1bD080Q 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…

  • http://[email protected] sherry

    i want in struts.xml request of type interseptor-ref name=”json” and result as type stream in a single action like :

     &lt;action name=&quot;downloadAction&quot; method=&quot;download&quot; class=&quot;DownloadAction&quot;&gt;
        &lt;interceptor-ref name=&quot;json&quot;&gt;
            &lt;param name=&quot;contentType&quot;&gt;application/json&lt;/param&gt;
        &lt;/interceptor-ref&gt;
        &lt;result name=&quot;SUCCESS&quot; type=&quot;stream&quot;&gt;
            &lt;param name=&quot;contentType&quot;&gt;${contentType}&lt;/param&gt;
            &lt;param name=&quot;inputName&quot;&gt;inputStream&lt;/param&gt;
            &lt;param name=&quot;contentDisposition&quot;&gt;attachment; filename=&quot;${fileName}&quot;&lt;/param&gt;
        &lt;/result&gt;
        &lt;result name=&quot;ERROR&quot; type=&quot;tiles&quot;&gt;/jsp/export.jsp&lt;/result&gt;
        &lt;/action&gt;

    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?

  • http://[email protected] 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!!

  • http://work.msanjay.in 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

  • julian a.

    excellent, but as I can make it with annotations?

    thanks for reply

    :)

    • 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

  • js518

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

    • ab

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

  • Sandeep Pandey

    great Post :) was very helpful

  • 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;
    }

    }

    ——————————–
    XML

    /login.jsp

    ——————————–
    Plug-ins
    struts2-json-plugin-2.3.4.jar

    ——————————–
    Problme
    Stacktraces
    org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException

    org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:238)
    org.apache.struts2.json.JSONWriter.processCustom(JSONWriter.java:171)
    org.apache.struts2.json.JSONWriter.process(JSONWriter.java:161)
    org.apache.struts2.json.JSONWriter.value(JSONWriter.java:127)
    org.apache.struts2.json.JSONWriter.write(JSONWriter.java:95)
    org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:116)
    org.apache.struts2.json.JSONResult.createJSONString(JSONResult.java:196)
    org.apache.struts2.json.JSONResult.execute(JSONResult.java:170)
    com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:374)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:278)
    org.apache.struts2.json.JSONInterceptor.intercept(JSONInterceptor.java:172)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:510)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:434)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:265)
    org.acegisecurity.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:107)
    org.acegisecurity.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:72)
    org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    org.acegisecurity.ui.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:166)
    org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    org.acegisecurity.wrapper.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:81)
    org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    org.acegisecurity.ui.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    org.acegisecurity.concurrent.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:95)
    org.acegisecurity.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:275)
    org.acegisecurity.util.FilterChainProxy.doFilter(FilterChainProxy.java:149)
    org.acegisecurity.util.FilterToBeanProxy.doFilter(FilterToBeanProxy.java:98)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    java.lang.Thread.run(Unknown Source)

  • Martin

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

     &lt;result type=&quot;json&quot;&gt;
         &lt;param name=&quot;root&quot;&gt;jsonret&lt;/param&gt;
         &lt;param name=&quot;defaultEncoding&quot;&gt;utf-8&lt;/param&gt;			
     &lt;/result&gt;

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

  • Pingback: Struts 2 autocompleter + JSON example()

  • Utsav

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

  • ramesh

    Can u post the strtus entry for the action mapping?

    • http://www.mkyong.com mkyong

      You can download the the entire tutorial at the end of the section “Download Source Code”

  • 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

  • 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

    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 getJSONResult action it will give me a file with the json string in it, which i can open or download . .

    . Example : http://www.google.co.in/imgres?q=JSON+download+as+file&um=1&hl=en&client=firefox-a&sa=N&rls=org.mozilla:en-US:official&biw=1366&bih=575&tbm=isch&tbnid=KmaETq1pqGWqJM:&imgrefurl=http://www.mkyong.com/webservices/jax-rs/download-json-from-jax-rs-with-jaxb-resteasy/&docid=A9pzMEPWONMK7M&imgurl=http://www.mkyong.com/wp-content/uploads/2011/07/jaxb-json-resteasy.png

    http://www.google.co.in/imgres?q=JSON+download+as+file&um=1&hl=en&client=firefox-a&sa=N&rls=org.mozilla:en-US:official&biw=1366&bih=575&tbm=isch&tbnid=6dCGCGeSa7di_M:&imgrefurl=http://www.dotnetcurry.com/ShowArticle.aspx%3FID%3D596&docid=ecziYCCdZg_cPM&imgurl=http://www.dotnetcurry.com/images/silverlight/26102010image_1.jpg

    So i think it’s a configuration problem, but i can’t find it. I would be very glad if somebody could help me, thanks guys!

  • 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)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    17-jul-2012 20:13:12 org.apache.catalina.core.StandardHostValve custom
    GRAVE: Exception Processing ErrorPage[errorCode=500, location=/WEB-INF/jsp/errores/error500.jsp]
    org.apache.jasper.JasperException: java.lang.NullPointerException
    at org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
    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)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Caused by: 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)
    … 23 more

    Any suggestion?

    Thanks in advance!!

  • 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)

      hi i am working with

      2.3.1.2

      is very well the example!!

  • 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

    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

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

      • 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ó

      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

      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

    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..?

  • mahmoud

    hi my problem is , i have 2 autocomplet , i generte the autcolmplet via json into my actions , i use tiles for disply my pages web, every thnk it s ok when i dsplu one eutocomplet in the page, bu when i disply 2 autocolpete int same page nothhing happen int the autocolmplet ???

  • paolo

    Hi mkyong,

    Can you please help me? After getting the JSON output/data, how can I manipulate it(e.g. display it on my HTML page, pass the JSON data to a javascript/jquery variable, etc.)? Thanks!

  • http://www.asistech.in Ravindra

    Hello i am try to run my first JSON with struts but i am facing one problem, whenever i am try to execute my program on browser url ex: http://localhost:8080/getJSONDATAResult after pressing enter i am getting one popup to save or open dialog.so please do help me in this matter.

  • Mahadi Siregar

    can we limiting the variable which should displaying? Because, if i put 3 variables with getter of it, all of it will be displaying/passing. whereas, i just want to display one variable

    Thank you Mkyong

  • Chris

    Hey guys,

    I have a problem with struts2 and json configuration, i hope you can help me… As it didn’t work at my application i tried this example but i’ve got the same results.

    The request is sent, and json is generated well. The only problem i have is, that the json string returns as a file. So when i call the getJSONResult action it will give me a file with the json string in it, which i can open or download…

    I tried out to set a mine-type in tomcats web.xml:

     
            json
            application/json

    Same effects…
    So i think it’s a configuration problem, but i can’t find it. I would be very glad if somebody could help me, thanks guys!

  • John Boyer

    Do you have ZIP archive of this project ready to import into Eclipse as a dynamic web project?

    We’re an Ant shop, we don’t know Maven and I get it working in Eclipse.

    Thank you!

  • miguel

    Hi. Thanks for your post, I have a cuestion, when I put in my package (inside the struts.xml) this ‘extend=”hibernate-default, json-default”‘ my sessionTarget return me NULL, how I can do for that work?

    • http://www.mkyong.com mkyong

      did you include the struts2-json-plugin.jar dependency?

      • miguel

        yes, inside the pom.xml. like this:

        org.apache.struts
        struts2-json-plugin
        2.2.1.1

        com.google.code
        struts2-fullhibernatecore-plugin
        2.2.1

        • http://www.mkyong.com mkyong

          Download this project and run to verify if this project working?

          Then compare with yours to spot the different.

          • miguel

            Hi, thanks for your answers. yes, this example is runing. aaamm When i delete the “json-default” the sessionTarget is working, and when I delete the “hibernate-default” the json too working, but when I put the two is not working, why?

          • miguel

            Hi, I change the order for this

            extends = “json-default, hibernate-default”

            and apparently is working!

            do you think that is the problem?

  • http://www.mkyong.com/spring-mvc/spring-mvc-hello-world-example/ Kamal

    Hi,

    When I run this web application I got :

    There is no Action mapped for namespace / and action name . – [unknown location]
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:178)
    org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
    com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:861)
    org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
    org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1584)
    java.lang.Thread.run(Thread.java:619)

    Can you please help me.

    Thanks

    • http://www.mkyong.com mkyong
      • kamal

        My friend Mkyoung,

        I changed the devMode from true to false, but still nothing, did you notice that in the output of the error there is no name of the action, there is only a dot (.) :

        HTTP Status 404 – There is no Action mapped for namespace / and action name .

        type Status report

        message There is no Action mapped for namespace / and action name .

        description The requested resource (There is no Action mapped for namespace / and action name .) is not available.
        Apache Tomcat/6.0.28

        Thanks, your help is appreciated

        • http://www.mkyong.com mkyong

          then, Zip your project and send to me.

          • Bill

            how did you fix this. i have the same problem. thanks!

          • VIGNESWARAN S

            Hi Mkyong,

            Can you please post this application in .war file

            Thanks
            Vignesh

  • tutti

    I am seeing the action being called twice,
    I see in your example, most of your business logic resides in your constructor
    and:
    public String execute() {
    return Action.SUCCESS;
    }

    and method execute is being empty, if you experiment, the execute method will be called twice, Do you you know wny ?

    Thanks

  • http://anyulled.blogspot.com anyulled

    where can i download the file?

  • rn

    hi

    i am generating json by the above method and i am using jquery to retrieve the json data
    everything is working fine the only problem is that execute function is getting called twice. Is this a bug or something ?

    • tutti

      did you figure this one yet? why it is called twice?

      Thanks

  • Sheela

    My Action class has references to other class (which also implements serializable). i am getting the below. error .. any ideas?
    org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
    org.apache.struts2.json.JSONWriter.bean(JSONWriter.java:243) org.apache.struts2.json.JSONWriter.process(JSONWriter.java:165) org.apache.struts2.json.JSONWriter.value(JSONWriter.java:131) org.apache.struts2.json.JSONWriter.write(JSONWriter.java:99) org.apache.struts2.json.JSONUtil.serialize(JSONUtil.java:112) org.apache.struts2.json.JSONResult.execute(JSONResult.java:198) com…hony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)

    • http://www.mkyong.com mkyong

      when you are viewing Java error messages, you should focus on the “caused by” error message.

      Please paste your “caused by” error message.

      • Rch

        I dont have any “caused by”
        just Messages::

        Positioned Update not supported.
        java.lang.reflect.InvocationTargetException
        org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
        org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
        org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: java.lang.reflect.InvocationTargetException
        org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException: org.apache.struts2.json.JSONException:
        • http://www.mkyong.com mkyong

          weird case, Positioned Update not supported? Mind to send me your source code?

  • Dipak

    how can i skip particular variable from action, not to be serialize in json object?

  • http://siriwardana.blogspot.com semika loku kaluge

    Thanks for the post. It was helpful for me.