Read HttpServletRequest object from Spring Boot controller method

We Are Going To Discuss About Read HttpServletRequest object from Spring Boot controller method. So lets Start this Java Article.

Read HttpServletRequest object from Spring Boot controller method

Advertisements
  1. Read HttpServletRequest object from Spring Boot controller method

    First, remove the @Autowired field. It's wrong and you're not using it anyway.
    Now you have two choices:
    Let Spring process the request body for you, by using the @RequestBody annotation:
    @PostMapping(path = "/abc") public String createAbc(@RequestBody String requestBody) throws IOException

  2. Read HttpServletRequest object from Spring Boot controller method

    First, remove the @Autowired field. It's wrong and you're not using it anyway.
    Now you have two choices:
    Let Spring process the request body for you, by using the @RequestBody annotation:
    @PostMapping(path = "/abc") public String createAbc(@RequestBody String requestBody) throws IOException

Solution 1

Advertisements

First, remove the @Autowired field. It’s wrong and you’re not using it anyway.

Now you have two choices:

  1. Let Spring process the request body for you, by using the @RequestBody annotation:

    @PostMapping(path = "/abc")
    public String createAbc(@RequestBody String requestBody) throws IOException {
        logger.info("Request body: " + requestBody);
        return "abc";
    }
    
  2. Process it yourself, i.e. don’t use the @RequestBody annotation:

    @PostMapping(path = "/abc")
    public String createAbc(HttpServletRequest request) throws IOException {
        StringBuilder builder = new StringBuilder();
        try (BufferedReader in = request.getReader()) {
            char[] buf = new char[4096];
            for (int len; (len = in.read(buf)) > 0; )
                builder.append(buf, 0, len);
        }
        String requestBody = builder.toString();
        logger.info("Request body: " + requestBody);
        return "abc";
    }
    

Don’t know why you’d use option 2, but you can if you want.

Original Author Andreas Of This Content

Solution 2

Advertisements

if you want to take it out easily:

private ObjectMapper objectMapper;

byte[] bytes = request.getInputStream().readAllBytes();

User u = objectMapper.readValue(bytes, User.class);

Original Author aniran mohammadpour Of This Content

Conclusion

Advertisements

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Advertisements
Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment