将 ajax 与 Spring MVC 结合使用

发布于 2024-12-09 06:01:50 字数 167 浏览 0 评论 0原文

我目前正在使用 Spring MVC,并且我正在尝试使用 ajax 做一些事情。基本上我现在想做的就是在网页上动态显示控制器的结果。

IE 用户按下按钮,它会转到“whatever.do”控制器并获取列表并显示该列表,而无需重新加载该页面。

无论如何,有人知道任何好的教程或示例项目吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

薄荷港 2024-12-16 06:01:50

它非常简单,我什至认为不需要专门的教程(除了通用的 spring-mvc 教程)。

  1. 创建一个返回 List@RequestMapping("/foo") 方法,
  2. 具有 在您的 dispatcher-servlet.xml 中激活处理程序映射和转换器
  3. 将 Jackson(json 序列化程序)放在您的类路径上
  4. 使用 $.getJSON("/foo", function(data) {..}); (jquery) - 您将获得 Foo 对象的 JSON 编码列表

Spring 将检测浏览器请求 json 响应,并使用 Jackson 转换您的对象。

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.

我们的影子 2024-12-16 06:01:50

当您与 spring 和 ajax 一起使用时,您的控制器必须采用以下格式:

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

     //code logic

return list_of_your_object;
}

jsp 页面上的 java 脚本代码也采用以下格式:

<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>

在 jsp 页面中导入 jquery 库

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

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>
是伱的 2024-12-16 06:01:50
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');
                        }
                    });
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');
                        }
                    });
面犯桃花 2024-12-16 06:01:50
@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;
    }
@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;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文