您好我是servlet中的新手,并尝试使用ajax将对象从javascript发送到servlet。 javascript代码如下所示:
$.ajax({
url:'GetUserServlet',
contentType: "application/json",
data: JSON.stringify(response),
type:'post',
cache:false,
success:function(data){
//alert(data);
$('#somediv').text("user info sent successfully");
},
error:function(){
$('#somediv').text("some error occured");
}
}
);
这里的回复是从facebook api收到的对象。它是:
reponse={ first_name: "Jhon", last_name: "Doe", id: "19862217575855" }
doPost
的{{1}}方法定义为:
GetUserServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
User user = gson.fromJson(request.getParameter(response), User.class);
System.out.println(user);
}
是包含User.class
,first_name
和last_name
但程序没有编译。我使用了很多语法更改但找不到正确的值。如何在servlet中获取id
对象?
答案 0 :(得分:0)
// 1. get received JSON data from request
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String json = "";
if(br != null){
json = br.readLine();
}
// 2. initiate jackson mapper
ObjectMapper mapper = new ObjectMapper();
// 3. Convert received JSON to User
User user = mapper.readValue(json, User.class);
// 4. Set response type to JSON
response.setContentType("application/json");
System.out.println("..user.." + user);