Let's assume I have many teams like : "Team A, Team B...Team Z" and each team has at least 5 components. Now I want to create a generic controller that responds to any request of type /team/number
so I can be able to get informations about a team member.
For example my controller must be able to map this request :
@RequestMapping(value = "/Team A/1", method = RequestMethod.GET)
Team class could be :
@Entity
@Table(name = "team")
public class Team {
public Team() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private List<Player> players;
}
And
Player :
@Entity
@Table(name = "player")
public class Player {
public Player() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private int number;
}
Obviously it can either execute GET
and POST
. The point is that I don't want to specify a controller for each team and each number, I just want one that can respond to /String/int
.
I need also to specify which string it can accept and the range of values (max 5 for example).
CodePudding user response:
The @PathVariable spring annotation would help you in this case.
For example:
@RequestMapping(value = "{team}/{component}", method = RequestMethod.GET)
public Team getTeam(@PathVariable String team, @PathVariable int component) {
//Use team and component here
}
You can just add some logic into the controller method to throw some exception if either variable is an unexpected value.
Though depending on what you are trying to achieve, this may be a bad design as this controller method will catch all GET requests that match String/int
. You may want to try something like this to make the request mapping more specific:
@RequestMapping(value = "team/{teamLetter}/{component}", method = RequestMethod.GET)
public Team getTeam(@PathVariable char teamLetter, @PathVariable int component) {
//Use team and component here
}