I’m running Glassfish web server with Strut2 and I would like to pull json data from action class for a page without a page refresh. What I mean by that is that when a user changes a setting I would like to show updated data automatically without page refresh.
Making Ajax call to Strut2 action class seems to be my solution but all of my Google search resulted for the cases where page refresh is needed.
Action class:
...
@Override
public String execute() throws Exception {
result = "\"{\"age\":100,\"name\":\"dude\"}";
return SUCCESS;
}
...
strut.xml:
<package name="default" namespace="/" extends="json-default">
<action name="getData" class="action.getData" method="execute">
<result type="json" />
</action>
</package>
ajax call:
jQuery.ajax(
{
type: 'POST',
url: '/proj/getData',
data: {id: $('#id').val()},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data){
alert(data.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert('Error ' + textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}
});
Above code makes a correct call to correct function in the action class but two problems.
- I’m not sure how to pull the id data set in data section of ajax call in server side
-
I get following error on server side on return.
WARNING: StandardWrapperValve[default]: PWC1406: Servlet.service() for servlet default threw exception java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils at org.apache.struts2.json.SerializationParams.<init>(SerializationParams.java:57) at org.apache.struts2.json.JSONResult.writeToResponse(JSONResult.java:207) at org.apache.struts2.json.JSONResult.execute(JSONResult.java:171)
I’m very new to strut2 and I know I have done similar things with ajax and struts but I just can’t seem to figure this one out, so it would be appreciated if you can help.
You need to add
apache common langpackage to your classpath, or WEB-INF/Lib. You can get it herehttp://commons.apache.org/lang/
or add it as maven dependency if you are using maven.
Second thing is you can access id as a parameter to url
String id= request.getParameter("id");to get request object the Action class must be implementing servletrequestaware .You can pass the id parameter as a GET request as well.