开发者

Using ajax with Spring MVC

开发者 https://www.devze.com 2023-04-12 14:42 出处:网络
I am cu开发者_StackOverflow中文版rrently using the Spring MVC, and I am trying to do some stuff with ajax. Basically what I want to do now is display the result from a controller dynamically on a webp

I am cu开发者_StackOverflow中文版rrently using the Spring MVC, and I am trying to do some stuff with ajax. Basically what I want to do now is display the result from a controller dynamically on a webpage.

I.E. A user pushes a button it goes to the "whatever.do" controller and gets a list and displays that list without having to reload that page.

Anyway does anyone know any good tutorials or example projects?


It is very simple, I don't even think a special tutorial is needed (apart from a generic spring-mvc one).

  1. Make a @RequestMapping("/foo") method that returns a List<Foo>
  2. Have <mvc:annotation-driven /> in your dispatcher-servlet.xml to activate handler mappings and convertors
  3. Put Jackson (json serializer) on your classpath
  4. Use $.getJSON("/foo", function(data) {..}); (jquery) - you will get a JSON-encoded list of your Foo objects

Spring will detect that the browser requests a json response, and converts your objects using Jackson.


http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

http://krams915.blogspot.com/2011/01/spring-mvc-3-and-jquery-integration.html


your controller must have in following format when you are using with spring along with ajax:

@RequestMapping(value = "/show.ajax", method = RequestMethod.POST)
public @ResponseBody List<your object type> your_method_name() {

     //code logic

return list_of_your_object;
}

also your java script code on jsp page in following format:

<script>
    function your_javascript_fun_name() {
            $.ajax({
                type : 'POST',
                url : 'show.ajax',//this is url mapping for controller
                success : function(response) {
                    alert(response);
                                 //this response is list of object commming from server
                },
                error : function() {
                    alert("opps error occured");
                }
            });
        }
</script>

import jquery library in jsp page

<script src="http://code.jquery.com/jquery-1.8.3.js"></script>


var id = $("#id").val();
                    var resourceURL = $("#contextpath").val()+"/customer/retrivebyid/"+id;
                    $.ajax({
                        url : resourceURL,
                        type : 'GET',
                        dataType : 'json',
                        async : false,
                        success: function(data) {
                            var successflag = data.response.successflag;
                            var errors = data.response.errors;
                            var results = data.response.result;
                            if(successflag == "true"){
                                $.each(results, function (i, result) {
                                    $("#id").val((result.id == undefined || result.id == null || result.id.length <= 0) ? "-" : result.id);
                                    $("#name").val((result.customername == undefined || result.customername == null || result.customername.length <= 0) ? "-" : result.customername);
                                }); 
                            }else{
                                $("#errorMsgContent").html(errors);
                                $.fancybox.open('#errorMsg');
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            $("#errorMsgContent").html(thrownError);
                            $.fancybox.open('#errorMsg');
                        }
                    });


@RequestMapping(value = "/retrivebyid/{id}", method = RequestMethod.GET)
    public @ResponseBody String retriveUser(@PathVariable long id, Model model,HttpServletRequest request) {
        String jsonresp = null;
        try {
            List<CustomerDO> customerList = new CustomerService().retriveById(id);
            jsonresp = CustomerUtil.getCustomerList(customerList).toString();
        } catch (Exception e) {}

        if (jsonresp != null) {
            return jsonresp.toString();
        } else {
            return null;
        }
    }

    public static JSONObject getCustomerList(List<CustomerDO> empList)throws AppException {
        JSONObject responseJSON = new JSONObject();
        JSONObject resultJSON = new JSONObject();
        try {
            resultJSON.put(CommonConstants.SUCCESS_FLAG, CommonConstants.TRUE);
            resultJSON.put(CommonConstants.ERRORS, "");
            JSONArray resultJSONArray = new JSONArray();
            for (CustomerDO customer : empList) {
                resultJSONArray.put(getCustomerDetailObject(customer));
            }
            resultJSON.put(CommonConstants.RESULTS, resultJSONArray);
            responseJSON.put(CommonConstants.RESPONSE, resultJSON);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return responseJSON;
    }

    private static JSONObject getCustomerDetailObject(CustomerDO customer)throws JSONException, AppException {
        JSONObject result = new JSONObject();
        result.put(CommonConstants.ID, String.valueOf(customer.getId()));
        result.put(CommonConstants.CUSTOMER_NAME, String.valueOf(customer.getName()));
        return result;
    }
0

精彩评论

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

关注公众号