I am implementing a mechanism for replacing short links.
I need to forwarded request to another controller. I found examples how to do it in spring on models, but I don't understand how to do it in RestControllers
Example what i found (use models)
@Controller
public class ShrotLinkForwardController {
@RequestMapping("/s/*")
public String myMethod(HttpServletRequest request) {
return "forward:/difmethod";
}
}
Or maybe I'm looking in the wrong direction and I need to make a filter?
UPD. I don't know the final endpoint, it is calculated in the forwarded method. So, i cant autowired other controller
CodePudding user response:
There are 2 ways to achieve what you want.
1. Call the method on the target controller directly.
Controllers are just normal Spring beans. You can get it via autowire.
@Controller
public class ShrotLinkForwardController {
@Autowired
OtherController otherController;
@RequestMapping("/s/*")
public String myMethod(Model model) {
otherController.doStuff();
return ...;
}
}
2. Trigger the redirect by returning a string
To trigger the redirect, try returning a String
instead of ModelAndView
.
This is the approach you mentioned in your question. Note that the syntax should be forward:/forwardURL
. The string after forward:
is the URL pointing to another controller, not the method name.
@Controller
public class ShrotLinkForwardController {
@RequestMapping("/s/*")
public String myMethod(Model model) {
return "forward:/forwardURL";
}
}
CodePudding user response:
you could inject the target controller and simply call the method
@Controller
public class ShortLinkForwardController {
@Autowired
private RestController target;
@RequestMapping("/s/*")
public String myMethod(HttpServletRequest request) {
return target.myMethod(request);
}
}
Caveat: Path related request properties will still point to "/s/*"
Or use ResponseEntity and set target location...
public ResponseEntity<Void> myMethod(HttpServletRequest request) {
return ResponseEntity.status(302).location(URI.create(...)).build();
}