简体   繁体   中英

Create restController method post for service method with two objects

I have a method in service where i add person to team :

@Transactional
    public void addPersonsToTeams(Long teamId, Long personId) {
        Assert.notNull(personId, "Object can't be null!");
        Assert.notNull(teamId, "Object can't be null!");
        try {
            Person person = personRepository.getOne(personId);
            Team team = teamRepository.getOne(teamId);
            person.getTeams().add(team);
            personRepository.save(person);
        } catch (Exception e) {
            throw new CreateEntityException();
        }

    }

Now in my rest controller class i want to create a post method to test it in postman. But this my first time with two arguments method and i don't know how to create it. Actually i have only this:

@PostMapping("/addPeopleToTeams")
    public ResponseEntity<?> addPeopleToTeam(@RequestBody Long teamId, Long personId){

    }

This is good way? Maybe somebody have some exaple?

You can get entire post body into a POJO. Following is something similar

@RequestMapping(value = { "/api/pojo/edit" }, method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public Boolean addPeopleToTeam( @RequestBody Pojo pojo) { return false; }

Where each field in Pojo (Including getter/setters) should match the Json request object that the controller receives.

Reference

Maybe put teamId as a @PathVariable . This way, you will call /addPeopleToTeams/{teamId} with personId in @RequestBody . Or, you could also sent a json formed like this :

{ 
   "personId" : "xx",
   "teamId" : "xx"
}

Then, you can call it the way you do it with a /addPeopleToTeams with this object in @RequestBody . You can pretty much do it a lot of differents ways. Just do it the way it make the most sense in the rest of your code.

@RequestMapping(value = { "/addPeopleToTeams/{teamId}/{personId}" }, method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public Boolean addPeopleToTeam( @PathVariable("teamId") Long teamId, @PathVariable("personId")  Long personId)

But you need to invoke your method like that /addPeopleToTeams/1/2

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