How To Send Json To Struts2?
Solution 1:
I will suppose that you have already added this config to your struts.xml to provide JSON format support :
<actionname="checkGoodsIsEnough"class="ClassOf_CheckGoodsIsEnough"><interceptor-refname="defaultStack"/><interceptor-refname="json"><paramname="enableSMD">true</param></interceptor-ref></action>
If this is the case, dont forget to convert your javascript object to JSON string format by using :
var JsonParams = JSON.stringify(params);
And then try to do the Post call as follow :
$.ajax({
type: 'post',
url: "checkGoodsIsEnough",
data: JsonParams,
dataType:"json",
async: true,
success: alert("success"),
error: function(jqXHR) {
alert(jqXHR.status);
}
});
Hope this help!
Solution 2:
You need the struts2-json-plugin.
It serves two main purposes:
#1 - Converting Java objects to JSON through the
json
result (from Action to JSP);#2 - Converting Javascript objects to JSON through the
json
interceptor (from JSP to Action).
While the first is automatic, for the second (that is what you want) you need to define an interceptor stack containing the json
interceptor, for example:
<packagename="myPackage"extends="json-default">
...
<actionname="myAction"class="foo.bar.MyAction"><interceptor-refname="json" /><!-- #2 is here --><interceptor-refname="defaultStack" /><resultname="success"type="json"><!-- #1 is here --><paramname="root">myJavaObjectThatWillBecomeJson</param></result><resultname="error">error.jsp</result></action>
...
After confirming that it is working, you can (and should) define the interceptor stack once in the configuration, setting it as the default interceptor, instead of rewriting this configuration inside every action.
For the json Interceptor to run properly, the conditions are:
- The "
content-type
" must be "application/json
"- The JSON content must be well formed, see json.org for grammar.
- Action must have a public "setter" method for fields that must be populated.
- Supported types for population are: Primitives (int,long...String), Date, List, Map, Primitive Arrays, Other class (more on this later), and Array of Other class.
- Any object in JSON, that is to be populated inside a list, or a map, will be of type Map (mapping from properties to values), any whole number will be of type Long, any decimal number will be of type Double, and any array of type List.
Post a Comment for "How To Send Json To Struts2?"