开发者

spring mvc how to change form command object with javascript or ajax call

I am using spring mvc 3.0 to build an web application.

User can get customers by writing their id or just sends empty form and i turn back all customers开发者_如何学C that user can traverse between customers by using buttons. Question is how to do it via ajax or javascript without postbacking.

I add customer object to modelAttribute and in my jsp file using :

 <form:form modelAttribute="Customer" method="POST">
           <form:input path="name"/>

@RequestMapping(value = "/customer", method = RequestMethod.GET)
    public String handleCustomer(Model md,HttpSession session) {

       Customer customer= (Customer ) session.getAttribute("customer");

        if( customer== null)
        {
            customer=  new Customer ();
        }
        md.addAttribute("Customer ",customer);
        return "customer";
    }

Here is the question how to change this model attribute without postback. Now according to this get method when I set Customer object all fields are set since I am using "path" to bind fields. I tried to change via ajax callback but it does not work. I don't want to get all fields and assign one by one with jQuery.

Here is my JS function:

    $("#Customer").submit(function() {
//                var customer= $(this).serializeObject();
//                $.postJSON("Customer", customer, function(data) {
//                  
//                });

                $.getJSON("customer/query.htm",{ id: $('#id').val() }, function(result) {                           

                    $('#testdiv').val(result);

            });
                return false;               
            });

I have tried both getJSON and postJSON functions. Can you link some sort of book, tutorial or documentation it will be helpful.


Submit your query with standard jQuery AJAX calls using such as .getJSON.

In your Spring handler:

  1. Add a @ModelAttribute to the handler method signature so that Spring will map name-value pairs from the AJAX call to the form-backing command object.
  2. Change the return type for the handler method to @ResponseBody Map<String, ? extends Object>, and add your objects to the map instead of to the Model.
  3. Add the Jackson JAR to your app so Spring auto-magically serializes the response object to JSON.

jQuery calls submit the AJAX request, Spring handles it, automatically binding the name-value pairs to the command object, and then returns JSON back to the jQuery method.

@RequestMapping(value = "/customer", method = RequestMethod.GET)
public @ResponseBody List<Customer> handleCustomer(
      @ModelAttribute("Customer") Customer form,
      HttpSession session) {
    List<Customer> customers = new ArrayList<Customer>();
    if(form.getId() > 0) {
       // call your data access service to get that one customer
       Customer c = myCustomerService.getCustomer(form.getId());
       customers.add(c);
    } else {
       // call your data access service to return all customers
       customers = myCustomerService.getAllCustomers();
    }
    return customers;
}


Here is the answer of my question i could not find a way to refresh my form with json response.

But with ajax webrequest.

Here is the ajax Utils class.

import org.springframework.web.context.request.WebRequest;

public class AjaxUtils {

    public static boolean isAjaxRequest(WebRequest webRequest) {
        String requestedWith = webRequest.getHeader("X-Requested-With");
        return requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false;
    }

    public static boolean isAjaxUploadRequest(WebRequest webRequest) {
        return webRequest.getParameter("ajaxUpload") != null;
    }

    private AjaxUtils() {}
}

in controller we add

 @RequestMapping(value = "/customer.htm", method = RequestMethod.GET)
    public String handleCustomer(Model md, HttpSession session,WebRequest webRequest) {

          Customer customer= (  Customer ) session.getAttribute("customer");

        if (customer== null) {
            customer= new   Customer();
        }
        md.addAttribute("Customer", customer);
        md.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(webRequest));
        return "customer";
    }

    @RequestMapping(value = "/customer.htm", method = RequestMethod.POST)
        public String processSubmit(  Customer  customer, BindingResult result, WebRequest webRequest, HttpSession session, Model model) {
            customer= dataService.getCustomer(customer.getId());

            session.setAttribute("customer", customer);
            if (AjaxUtils.isAjaxRequest(webRequest)) {
                // prepare model for rendering success message in this request
                model.addAttribute("ajaxRequest", true);
                            model.addAttribute("Customer",customer);
                return null;
            }


            return "customer";
        }

functions so in jsp or view side we post page with :

$("#Customer").submit(function() {  
                    $.post($(this).attr("action"), $(this).serialize(), function(html) {
                        $("#customerdiv").replaceWith(html);

                    });
                    return false;  
                });

To summarize with the help of the ajax utils class we set the type of the request full postback or ajaxrequest in our post handler function we made our changes and this changes directly affects the page and form. No need to handle response or set all fields one by one with jquery hope this helps someone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜