I am using Struts class which implements ModelDriven
. I am able to pass the data from jQuery and save the data on the database.
When I try to retrieve the data back and pass it back to jQuery, I am not sure why it's not available in jQuery. I am sure I am missing something with the basic flow..
Here is my action class.
public HttpHeaders index() {
model = projectService.getProjectDetails(project.getUserID());
return new DefaultHttpHeaders("success").setLocationId("");
}
@Override
public Object getModel() {
return project;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
Here is my jQuery
function getProjectDetails() {
var userID = localStorage.getItem('userID');
var request = $.ajax({
url : '/SUH/project.json',
data : {
userID : userID
},
dataType : 'json',
type : 'GET',
async : true
});
request.done(function(data) {
console.log(JSON.stringify(data));
$.each(data, function(index, element) {
console.log('element project--->' + index + ":" + element);
});
});
request.fail(function(jqXHR, textStatus) {
console.log('faik');
});
}
The model object in the Action class has all the data available but I tried to return model or project objects but both didn't work.
By default Struts2 REST plugin is using json-lib for serialization your beans. If you are using
ModelDriven
then it accesses your model directly when it processes a result. Since you are using the extension.json
in the request URL the content type handler is selected by extension. It should beJsonLibHandler
.This handler is using
JSONArray.fromObject(obj)
ifobj
is an array or list orJSONObject.fromObject(obj)
otherwise to getJSONObejct
that could be serialized and written to the response.The
obj
is the value returned bygetModel()
, in your case it will beproject
.Because
JsonLibHandler
is using defaultJsonConfig
you can't exclude properties from the bean to be serialized unless they arepublic
fields.The following features of json-lib could be powered with
JsonConfig
:You can find this code snippets that allows you to exclude some properties.
But you have an option to use your own
ContentTypeHandler
to override defaults.The alternative is to use Jackson library to handle request. As described in the docs page: Use Jackson framework as JSON
ContentTypeHandler
.After that you can use
@JsonIgnore
annotation.