3

I am currently 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?

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
0

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>

Comments

0
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');
                        }
                    });

1 Comment

Please try to include some explanation of your solution. Code-only answers are not as useful as those that explain what's going on.
0
@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;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.