mardi 9 avril 2013

Spring MVC Ajax Controllers


In this post I will show how to implement Ajax calls via a spring MVC Controller.
Let’s see a simple controller Spring MVC Ajax example. As expected, it’s just a matter of anotating a method inside a @Controller class. Later I will show a simple jsp page which uses JQuery to make an Ajax call to the Spring MVC Controller.
MyController.java – A Simple Controller Class with
  1. @Controller  
  2. public class AjaxController {  
  3.         @RequestMapping(value = "/helloajax", method = RequestMethod.GET)  
  4.         public @ResponseBody  
  5.         void fetchFlowDowns(HttpServletResponse response) throws Exception {  
  6.           
  7.         String helloAjax = "<b>Hello Ajax</b>"  
  8.   
  9.         response.setCharacterEncoding("UTF-8");  
  10.         response.setContentType("text/html");  
  11.         response.getWriter().write(helloAjax);  
  12.   
  13.     }  
  14. }  
In the above controller we simply added an annotation in the singnature of the method: public @responseBody…
We also set the required encoding on the response. This is important when dealing with i18n webapps.
myView.jsp – A Simple jsp file, making an Ajax call to the controller we created above
  1. <script type="text/javascript">  
  2. function helloAjax()  
  3.         $.ajax({  
  4.             url : "/myapp/app/helloajax",  
  5.             data : "message=Hello Ajax!",   
  6.             success : function(result) {  
  7.                 $("#helloDiv").html(result);  
  8.             }  
  9.         });  
  10.     });  
  11. });  
  12. </script>  
  13.   
  14.   
  15.     <a onclick="helloAjax();">Say Hello</a> <div name="helloDiv" id="helloDiv"></div>     
There is nothing special in the code above. I just use JQuery built in function for Ajax call.
Conclusion
Making Ajax call into a Spring MVC Controller is again very easy and work very well as a Controller component. My suggestion is that for Ajax, create a separate Ajax controllers.
Relevant SpringFramework documentation: Spring MVC Controllers – Documentation
Enjoy!



Src ---> commonj.com

0 commentaires:

Enregistrer un commentaire

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More