当contentType为application / json时,Servlet中没有可见的参数

时间:2015-10-29 09:34:55

标签: java jquery json ajax servlets

我正在使用jquery尝试一个简单的程序,该程序向Servlet发出ajax请求

var searchObject = new Object();
searchObject.search1='abc';
searchObject.search2='xyz';
console.log(JSON.stringify(searchObject));
$.ajax({
    url: "SearchServlet",
    type: 'post',
    data: {data:JSON.stringify(searchObject)},
    contentType: 'application/json',
    mimeType: 'application/json',

    success: function (data) {
        console.log("Posted!!");
    }
});

以下是登录控制台的内容。

{"search1":"abc","search2":"xyz"}

在SearchServlet中,以下是方法

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameterMap());
        Enumeration<String> names = request.getParameterNames();
        System.out.println(names.hasMoreElements());
        while(names.hasMoreElements()){
            System.out.println(request.getParameter(names.nextElement()));
        }
    }

打印

{}
false

当ajax请求中指定的 contentType &#39; application / json&#39;

并打印

{data=[Ljava.lang.String;@7eedec92}
true
{"search1":"abc","search2":"xyz"}

从jquery ajax请求代码中注释掉 contentType

我想了解

  1. 为什么参数在contentType为时不可见 application / json?
  2. 如何从请求中访问参数时 contentType是application / json。

1 个答案:

答案 0 :(得分:1)

The parameters cannot be used in this case because the post data is not from an HTML Form. Instead you can parse the Json contained in form Data, for example using Jackson :

protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
PrintWriter out = response.getWriter();

ObjectMapper mapper = new ObjectMapper();

try {
  // read from stream, convert it to generic class
  Map data = mapper.readValue(request.getReader(), Map.class);

} catch (JsonGenerationException e) {
  e.printStackTrace();
} catch (JsonMappingException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}


}

And to use Jackson in a maven project, add this dependency:

    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.5.4</version>
    </dependency>

see also other answers on the same subject: HttpServletRequest get JSON POST data