为什么Spring MVC GET方法不通过json值设置POJO类



GET方法实现过程中出现的错误

java.io.EOFException: No content to map to Object due to end of input

my controller

   @RequestMapping(value = "/Login.htm", method = RequestMethod.GET,consumes="application/json",produces="application/json")
    public @ResponseBody Map<String, Object> Login(HttpServletRequest request,@RequestBody UserInput user) {
        Map<String, Object> modelMap = new HashMap<String, Object>(1);
        modelMap.put("status",userManagerDAO.LoginUser(user));
        return modelMap;
    }

可以使用post但不能使用get方法

请帮助我使这个方法得到我的输入json。

{
"cusId":1,
"loginId" : "123ASDF",
"password": "test123"
}

Get请求没有正文。为了让get工作,你可以在URL中包含json对象作为参数,使用该参数,然后使用JSON解析器将其解析为对象。

像:
http:///Login.htm?input="{"cusId":1、"loginId":"123年asdf","密码":"test123"}

不要忘记对URL进行编码。然后

public Map<String, Object> Login(HttpServletRequest 
request,@RequestParam(value="input")String userInput) {
    // Convert userInput string to UserInput object, use Jackson.
    Map<String, Object> modelMap = new HashMap<String, Object>(1);
    modelMap.put("status",userManagerDAO.LoginUser(user));
    return modelMap;
}
PS:通过URL发送JSON对象只是为了支持GET是不可取的。POST是正确的方法。因为
1. 安全:如果你使用https,没有人可以看到请求正文中的内容。
2. URL的长度是有限的,如果你的json非常大,那么Get会中断。

这是RestClient和许多XMLHttpRequest实现(如果不是全部的话)的限制。

基本上如果你尝试curl到你的服务

curl -XGET "localhost:8080/myapp/Login.htm" -H"Content-Type: application/json" -d '{
    "cusId":1,
    "loginId" : "123ASDF",
    "password": "test123"
}'

您将看到您的端点工作正常。

问题是,显然XMLHttpRequest实现在Firefox(和Chrome)不支持发送体与GET请求。

所以你留下了POST它,编码你的身体作为请求参数,如@shreyasKN建议或在中间放一个代理,为你翻译请求。

最新更新