我正在使用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 。
我想了解
答案 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