Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Ajax JQuery in Spring Web MVC

Tags:

I am using Spring Web MVC for my application.

I have 1 dropdown list in my JSP View, coming from following request called savegroup.htm

<bean name="/savegroup.htm" class="com.sufalam.mailserver.presentation.web.GroupSaveController">     <property name="sessionForm" value="true"/>     <property name="commandName" value="Group"/>     <property name="commandClass" value="com.sufalam.mailserver.presentation.bean.GroupViewBean"/>     <property name="formView" value="common"/>     <property name="successView" value="managegroup.htm"/>     <property name="userSecurityProcessor" ref="IUserSecurityProcessor"/>     <property name="domainsSecurityProcessor" ref="IDomainsSecurityProcessor"/>     <property name="forwardingsSecurityProcessor" ref="IForwardingsSecurityProcessor"/> </bean> 

JSP page has:

<form:form name="groupSaveForm" action="savegroup.htm" commandName="Group" method="POST">     Group Name :     <form:input path="source"/><br><br>     Domain List :     <form:select id="domains" onchange="javascript:getUser();" path="domainsList" multiple="false" size="1">         <form:option value="-" label="--Select--"/>         <form:options items="${domainsList}" itemValue="domain" itemLabel="domain"/>     </form:select> </form:form> 

Now my requirement is that, on the change event of my drop down list, I want to fetch related users from server and display that list of users in some list box.

For that how can I use jQuery AJAX call?

Where should I handle server side code which receives request and fetch related user?

How to display that coming set of users in my JSP?

like image 340
Nirmal Avatar asked Nov 04 '09 13:11

Nirmal


People also ask

Can we implement AJAX using jQuery in MVC?

Using AJAX In ASP.NET MVC. Implementation of Ajax can be done in two way in ASP.Net Application: using Update Panel and, using jQuery.

Can we use AJAX in MVC?

The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features. To enable the unobtrusive AJAX support in the MVC application, open the Web.


1 Answers

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.):

@Controller public 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.

like image 96
ideasculptor Avatar answered Sep 21 '22 05:09

ideasculptor