-3

I am sending json as a POST to my url via postman.

How do I read this json value in my servlet doPOST()?

input json:

{
    "token":"ABC123"
}

1 Answers1

0

Your JSON document could be parsed to a class such as the one shown below:

@Data
public class Foo {
    private String token;
}

And, well, you could have a HttpServlet and then parse the JSON using Jackson's ObjectMapper:

@WebServlet("/foo")
public class FooServlet extends HttpServlet {

    private ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp) throws IOException {

        Foo foo = mapper.readValue(req.getInputStream(), Foo.class);

        // Do something with foo

        resp.setStatus(HttpServletResponse.SC_OK);
    }
}

But, in most of real-world applications, it's not something you should do. Servlets are a bit too low-level and some frameworks have been created to make things a lot easier. Actually, most of these frameworks build on the top of servlets.

JAX-RS

In JAX-RS, and in its implementations (such as Jersey), you would have the following:

@Path("/foo")
public class FooResource {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response doSomethingWithFoo(Foo foo) {

        // Do something with foo

        return Response.ok().build();
    }
}

Spring Web MVC

In Spring Web MVC, here's what you could have:

@RestController
public class FooController {

    @PostMapping(path = "/foo", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> doSomethingWithFoo(@RequestBody Foo foo) {

        // Do something with foo

        return ResponseEntity.ok();
    }
}

For details on the differences between JAX-RS and Spring Web MVC, refer to this answer.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359