java SpringMVC 使用 JSON 返回对象列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15679879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:29:26  来源:igfitidea点击:

SpringMVC Returning a List Of Objects With JSON

javajqueryjsonspringspring-mvc

提问by devdar

I have two select options and i would like when the user selects one option that other is populated with data from the database. However i am having issues in getting the object list returned to the view.

我有两个选择选项,我希望当用户选择一个选项时,另一个选项填充了数据库中的数据。但是,我在将对象列表返回到视图时遇到了问题。

Controller

控制器

@RequestMapping(value="getCrimeTypeList.htm", method = RequestMethod.GET)
 public @ResponseBody List<CrimeType> getCrimeTypeList(@RequestParam(value="crimeCatId") Integer crimeCatId) throws Exception{              

        try {
            List<CrimeType> crimeTypeList = this.crimeTypeManager.getCrimeTypeList(crimeCatId);

             return crimeTypeList;
        } catch (Exception e) {

            logger.error(e.getMessage());
            return null;
        }
}

JQuery

查询

 $("select#offenceCatId").change(function(){

       $.ajax({
           type:'GET',
           url:'getCrimeTypeList.htm',
           data:{crimeCatId: $(this).val()},

            headers: {
             Accept: 'application/json'
            },
           dataType: 'json',

           success:function(data){

            alert('it worked');

           }

       });
     });

HTML

HTML

<li>
 <label>Offence Type</label>
 <form:select path="offenceTypeId" id="offenceTypeId" title="Offence Type">
 <form:options items="${crimeType.crimeTypeList}" itemValue="crimeTypeId" itemLabel="crimeTypeDesc"/>
 </form:select>
 <form:errors path="offenceTypeId" class="errors" />
</li>

Error

错误

"NetworkError: 400 Bad Request - http://localhost:8084/crimeTrack/getCrimeTypeList.htm?[object%20Object]"

EDITEDI did some experimentation and found if the Controller is returning a String it works however once its returning an Object i am having the issues stated.

编辑我做了一些实验,发现如果控制器返回一个字符串,它可以工作,但是一旦它返回一个对象,我就会遇到问题。

FireBug

火虫

GET http://localhost:8084/crimeTrack/getCrimeTypeList.htm?crimeCatId=6 406 Not Acceptable

Response Headers
Content-Length  1067
Content-Type    text/html;charset=utf-8
Date    Fri, 29 Mar 2013 00:58:17 GMT
Server  Apache-Coyote/1.1

Request Headers
Accept  application/json
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Host    localhost:8084
Referer http://localhost:8084/crimeTrack/crime_registration.htm
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0
X-Requested-With    XMLHttpRequest

回答by OQJF

Firstly please make sure your Spring version is 3.1.1 release and you have added Hymanson.jar in you lib, then try using below code, your code has something reduntant.

首先请确保你的 Spring 版本是 3.1.1 版本并且你已经在你的 lib 中添加了 Hymanson.jar,然后尝试使用下面的代码,你的代码有一些冗余。

@RequestMapping(value="/getCrimeTypeList.htm", method = RequestMethod.GET)
public @ResponseBody List<CrimeType> getCrimeTypeList(@RequestParam(value="crimeCatId") Integer crimeCatId) throws Exception{    
            try {
                return this.crimeTypeManager.getCrimeTypeList(crimeCatId);
                //return "true";
            } catch (Exception e) {
                logger.error(e.getMessage());
                return null;
            }
}
$("select#offenceCatId").change(function(){
        var param={crimeCatId:$(this).val()};
        $.ajax({
            type:'GET',
            url:'getCrimeTypeList.htm',
            data:param,
            success:function(data){
                //append options to list
            }
        });
});

回答by Arun P Johny

Your controller is expecting an request header Accept=application/json, in your case you are not setting it.

您的控制器需要一个请求标头Accept=application/json,在您的情况下您没有设置它。

Try setting the Acceptheader

尝试设置Accept标题

jQuery.ajax({
        type:'GET',
        url:'getCrimeTypeList.htm',
        data:{crimeCatId:$(this).val()},
        processData:false,
        headers: {
            Accept: 'application/json'
        },
        dataType: 'json',
        success:function(data){


            //append options to list


        }

    });