简体   繁体   中英

send json data from ajax and parse in servlet

Hi I am a newbie in servlet and trying to send object from javascript to servlet using ajax. javascript code looks like this:

$.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"); 
      }
   }

);

Here response is object received from facebook api. It is:

reponse={ first_name: "Jhon", last_name: "Doe", id: "19862217575855" }

The doPost method of GetUserServlet is defined as:

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 is another class containing getter and setter for first_name , last_name and id

But the program is not getting compiled. I have used many syntax changes but cannot find the correct value. How can i get the response object inside servlet?

        // 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM