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.
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
- @Controller
- public class AjaxController {
- @RequestMapping(value = "/helloajax", method = RequestMethod.GET)
- public @ResponseBody
- void fetchFlowDowns(HttpServletResponse response) throws Exception {
- String helloAjax = "<b>Hello Ajax</b>"
- response.setCharacterEncoding("UTF-8");
- response.setContentType("text/html");
- response.getWriter().write(helloAjax);
- }
- }
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.
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
- <script type="text/javascript">
- function helloAjax()
- $.ajax({
- url : "/myapp/app/helloajax",
- data : "message=Hello Ajax!",
- success : function(result) {
- $("#helloDiv").html(result);
- }
- });
- });
- });
- </script>
- <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.
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