4

I am trying to test my @PostMapping in on of my @RestController. That controller looks like this:

@RestController
public class MyTestController
{
    private static final Logger logger = LogManager.getLogger();

    @PostMapping(path = "/foo")
    public String add(@Valid Boo boo, HttpServletRequest request)
    {
        if (LoadManager.insert(request.getRemoteAddr()) < 3)
            try
            {
                BooManager.persist(boo);
                return "1";
            }
            catch (Exception e)
            {
                logger.error(ExceptionUtils.getStackTrace(e));
            }
        return "0";
    }
}

However boo fields are all null when I make a post request and look at boo object during debug in that add method.

Request body:

{
    "officialName" : "test",
    "phone" : "test",
    "email" : "test",
    "churchArea" : "test",
    "deanery" : "test",
    "town" : "test",
    "pass" : "test152S56"
}

Request header Content-Type is set to application/json

Boo class:

@Data
public class Boo
{
    @Size(max = 1000)
    @NotBlank
    private String officialName;

    @Size(max = 100)
    @NotBlank
    private String phone;

    @Size(max = 100)
    @NotBlank
    private String email;

    @Size(max = 100)
    @NotBlank
    private String churchArea;

    @Size(max = 100)
    @NotBlank
    private String deanery;

    @Size(max = 100)
    @NotBlank
    private String town;

    @Size(max = 1000)
    @NotBlank
    private String pass;
}

@Data annotation is from lombok, which generates, among other things, public getters and setter for that class.

4
  • Can you post your @GetMapping method? Commented Mar 30, 2022 at 11:02
  • private static final Logger logger = LogManager.getLogger(); remove static from it Commented Mar 30, 2022 at 11:04
  • 1
    Your method param Boo is missing @RequestBody Commented Mar 30, 2022 at 11:05
  • @Sar Why should I? Commented Mar 30, 2022 at 11:15

1 Answer 1

5

When you need to bound a request body to method parameter you should use @RequestBody annotation. That's why your Boo object attributes are null.

@PostMapping(path = "/foo")
public String add(@RequestBody Boo boo, HttpServletRequest request)

Docs: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.