@ResponseBody not producing XML in Java 6

2019-08-11 10:03发布

I have a Spring MVC 3/J2EE Project. The jsp rendering controllers are working fine, but the one controller that renders XML for Ajax is not working. I am using JDK 1.6 in RAD 7.5 so JAXB should be on the classpath, and I've even tried adding the latest JAXB jars to the lib file to make sure. I still get a 406 error when I make the call. My DOJO call has handleAs: "xml", and I've confirmed that application/xml is on the Accept header via FireBug. I have the <mvc:annotation-driven /> line in my spring servlet xml file. I can see the method being invoked and returning without error. I'm not sure what I should try next to debug.

//Country is a class with only primative types which implements Serializable.
public @ResponseBody List<Country> getCountries(){
    return addressService.getCountries();
}

function loadData(){
    console.log("Before get ...");
    dojo.xhrGet({
        url:"http://localhost:9080/sample/shared/getCountries.htm",
        handleAs:"xml",
        load: function(data){
            console.log("In load function ...");
            try {
                for(var i in data){
                   console.log("key", i, "value", data[i]);
                }
            }catch (ex){
                console.error("Failure in load function: " + ex);
            }
            console.log("Exiting load function ...");
        },
        error: function(x){
            console.error("Error in ajax ...");
            console.error(x);
        },
        failOk: false
    });
    console.log("After get ...");
}

2条回答
叼着烟拽天下
2楼-- · 2019-08-11 10:34

Try creating the following wrapper class:

@XmlRootElement
class Countries {
    private List<Country> countries = new ArrayList<Country>()

    //getters/setters
}

And return it from the controller instead of a raw list:

public @ResponseBody Countries getCountries()

Most likely your problem is caused by JAXB that is unable to marshal Java list (it does not know how to name the root tag of the XML document). Note that your problem probably does not occur when requesting data in JSON (if Jackson is available on your CLASSPATH).

See also (similar problems):

查看更多
3楼-- · 2019-08-11 10:39

Hard to say without seeing how you have configured your views / view resolvers. However, the client-side URL containing a .htm is suspect to me, especially if you are using a ContentNegotiatingViewResolver. I recommend dropping the file extension. Browsers automatically use an Accept header for HTML so no need to use an extension.

查看更多
登录 后发表回答