I have a simple jsp/servlet application and I want to add AJAX feature to this app. I use JQuery , but it doesn't matter what javascript framework I use. This is my code:
<script type="text/javascript">
function callbackFunction(data){
$('#content').html(data);
}
$('document').ready(function(){
$('#x').click(function() {
$.post('/ajax_2/servlet',callbackFunction)
});
});
</script>
<body>
<a href="#" id="x">Increase it</a>
<div id="content"></div>
</body>
</html>
Servlet
HttpSession session = request.getSession();
Integer myInteger = (Integer)session.getAttribute("myInteger");
if(myInteger == null)
myInteger = new Integer(0);
else
myInteger = new Integer(myInteger+1);
session.setAttribute("myInteger", myInteger);
response.getWriter().println(myInteger);
The Question:
I use out.print to transfer data from a servlet to javascript code (ajax code) , but If I have a complex structure such as a Vector of Objects or something like this , what is the best way to transfer the data? what about an XML file , JSON ? Is there any special jsp/servlets library to transfer data from a servlet to ajax application ? How can I parse this data in the callbackFunction ?
You can in the servlet distinguish between normal requests and Ajax requests as below: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String foo = request. getParameter("foo"); String bar = request.
get(URL,data,function(data,status,xhr),dataType): this method loads data from the server through HTTP GET request. attributes: URL: mandatory, defines the relative path of the servlet. data: optional, the data to be passed along with the request (although GET filters are recommended to be sent as a query string)
The best way is using JSON. There are several Java libraries which can convert fullworthy Java objects to a JSON string and vice versa. Further JSON can be accessed in Javascript in a fully natural way without converting/massaging the data forth and back in another format.
As to the server side part, I strongly recommend to pick Google Gson as JSON serializer. Gson is the preferred choice since it supports converting complex Javabeans and arrays, collections and maps of them to JSON and vice versa without pains in a single line of code. It even supports generics. Basically all you need to do is the following:
String json = new Gson().toJson(object);
Check the user guide to learn more about the powers of Gson.
All with all, the following in the server side is sufficient:
public static void writeJson(HttpServletResponse response, Object object) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(object));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With