Issue
I'm making calls to my API for different kind of custom events like:
const eventTypes = [
'cards.addCard'
'cards.updateCard',
'lanes.addLane',
'lanes.updateLane'
];
fetch(`http://localhost:8080/app/${roomId}/${eventType}`, {
method: 'POST'
body: JSON.stringify(data)
...
});
The eventType
path variable should define which one of these controller methods will be called:
@RestController
@RequestMapping(value = "/cards")
public class CardController {
@PostMapping("/{roomId}/createCard")
public void createCard(@PathVariable Long roomId, @RequestBody MyEventData eventData) {
...
}
@PostMapping("/{roomId}/updateCard")
public void updateCard(@PathVariable Long roomId, @RequestBody MyEventData eventData) {
...
}
}
@RestController
@RequestMapping(value = "/lanes")
public class LaneController {
@PostMapping("/{roomId}/addLane")
public void addLane(@PathVariable Long roomId, @RequestBody MyEventData eventData) {
...
}
@PostMapping("/{roomId}/updateLane")
public void updateLane(@PathVariable Long roomId, @RequestBody MyEventData eventData) {
...
}
}
I prefer to use eventType
from the path variable of the request but I can also put it inside the request body.
So how is it possible to forward a request in the same API to the right Controller's method by using its parameter (eventType
)? For example:
http://localhost:8080/app/2/cards.addCard
should call CardController.createCard()
http://localhost:8080/app/2/lanes.updateLane
should call LaneController.updateLane()
Solution
you can just switch the roomId with the eventType in the path attribute, like this :
@PostMapping("/createCard/{roomId}")
@PostMapping("/updateCard/{roomId}")
...
If you want to do a redirect, you can create a Filter that do a redirect based on the eventTyp, here is an example of doFilter implementation :
@Override
public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String path = req.getRequestURI();
if (path.equals("/a")) {
req = new HttpServletRequestWrapper((HttpServletRequest) request) {
@Override
public String getRequestURI() {
return "/b";
}
};
}
chain.doFilter (req, res);
}
Ref : SpringBoot possible filter issue with redirection
Answered By - Zouhair Dre