How to use Ajax JQuery in Spring Web MVC How to use Ajax JQuery in Spring Web MVC ajax ajax

How to use Ajax JQuery in Spring Web MVC


There are a number of ways to solve this. I need a few answers to questions before I can give you solid guidance.

Do you have a preference for XML vs JSON for ajax requests?

One thing to note - there is nothing jquery specific about what I am going to tell you to do. You need to send back a response to the jquery async request in a form that is useful to jquery (XML or json, ideally), but on the server side, it just looks like a normal request which happens to use a view that renders XML or json instead of html. My personal preference is to use JSON, especially since the spring-json package works very well and is easy to use once you understand how it works. I recommend the spring-json package available from http://spring-json.sourceforge.net/ Read through all of the documentation and you should have a very good idea how it works.

In the most basic form, your solution needs to do the following:

Configure a view which uses noe of the spring-json views. I prefer sojoView for most cases.

make an async request to the server, which will return the list of users. If the only info needed to deliver the set of users is the selected value of the drop down, it would be pretty simple to just issue a GET request with the selected domain in the query string. On the server side, you need a controller that will be mapped to the incoming request and which will send back json or xml to be processed by jquery. Basically you can write a totally normal controller, whether accessed by GET or POST method, and add your list of users to the model before returning ther name of your json view. The 3 types of json view that are provided by spring-json will render the beans in your list into a json structure and send that to the client. You can use all of the standard DataBinder functionality for parsing/converting incoming parameters and any validation errors will generate field or global error messages in the json response which your client side code can present to the user.

In the simplest case, my code would look something like this (this is all spring 2.5. It uses annotations but you can do the same things with xml configuration in your app context.):

@Controllerpublic class AjaxController {    @RequestMapping("/some/path/selectDomain.json", method=RequestMethod.GET)    public ModelAndView processDomainSelection(@RequestParam(value="domain", required="true") String selectedDomain) {        List<User> users = service.loadUsersForDomain(selectedDomain);        ModelAndView mv = new ModelAndView("sojoView", "users", users);        return mv;    }}

If I want to process via a POST request, and I wish to load an actual Domain object from the domainValue that is submitted, I can do somethign like this

@Controller@RequestMapping("/some/path/selectDomain.json")public class SelectDomainController {    public class FormBean {        protected Domain domain;        public Domain getDomain() {            return domain;        }        public void setDomain(Domain domain) {            this.domain = domain;        }    }    @ModelAttribute("command")    public FormBean getCommand() {        return new FormBean();    }    @InitBinder    public void initBinder(WebDataBinder binder, WebRequest request) {        // this custom editor knows how to load a Domain object from the domainValue string        // if it fails to convert, it can throw an exception, which will result in         // an error being logged against the "domain" field        binder.registerCustomEditor(Domain.class, "domain", new DomainLookupEditor(domainService));    }    @RequestMapping(method=RequestMethod.POST)    public String selectedDomain(@ModelAttribute("command") FormBean command,                                       BindingResult result,                                       Model model,                                       HttpServletRequest request) {        if (result.hasErrors()) {            return "sojoView";        }        Domain domain = command.getDomain();        List<User> users = domain.getUsers();        model.addAttribute("users", users);        return "sojoView";    }}

For issuing the ajax request, you can use jquery ajaxForm module. Assuming you have a form with id "selectDomainForm" you need js that looks something like this:

function selectDomainSuccessHandler(json) {    // it is possible to send back a 200 response after failing to process the request,    // in which case, the sojoView will have set success=false in the json    if (json.success == true) {        // parse json here and render it into html in your document    } else {        // get field error and global error from json and present to user    }}function(selectDomainErrorHandler(xhr, returnCode) {    // do something based on the return code}var options = {    success: selectDomainSuccessHandler,    error: selectDomainErrorHandler,    dataType: 'json'};$('selectDomainForm').ajaxForm(options);

You can google up the documentation for the ajaxForm module in order to learn how to post instead of get and to send grab only certain fields and send them to a URL that is not the intended url of the form.

To display the list of users in the page, you will have a div in your code with an id like "userList" and you can iterate over the users in the returned json, creating html for each user. Simply add that html to the "userList" div and it will appear in the browser.


Define the controller for the URL

If you want to use POST method:

content.load('URL(.)or(#)sectionToLoad', {}, function(event) {...});

or, if you want to use GET method:

content.load('URL(.)or(#)sectionToLoad', function(event) {...});

Call it with a function like .click or .submit

and that´s it