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
- 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
- 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
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 { logger.info("Request body: " + requestBody); return "abc"; }
-
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
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
So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.