How to redirect to the same page when an exception is raised inside the controller method. Here is my code.
This is my UserController class
@Controller
public class UserController{
@Autowired
private UserService userService;
@RequestMapping("/user/{userId}")
public ResponseEntity<UserDto> loadUserById(@PathVariable("userId" int userId){
UserDto user=userService.loadUserByUserId() int userId);
if(user==null){
throw new UserNotFoundException("No user found with this id");
}
return user;
}
@ExceptionHandler(UserNotFoundException.class)
public String handleUserNotFoundException(){
// here i want to redirect to the same page from which the request was coming with some message like "with this id user is not found"
}
}
But somehow i get the url for getting the original request url in the Exception handler method using "referal" header name. Using the "referer" we can identify from where the request was originated. Here is my code for that
@ExceptionHandler(UserNotFoundException.class)
public String handleUserNotFoundException(HttpServletRequest request){
String uri=request.getHeader("referer");
// now i want to redirect that uri
return "redirect:"+uri;
}
But again here i want to send some message to the uri For that i have to use RedirectAttributes like below code sample
@ExceptionHandler(UserNotFoundException.class)
public String handleUserNotFoundException(HttpServletRequest request, RedirectAttributes attributes){
String uri=request.getHeader("referer");
// now i want to redirect that uri
return "redirect:"+uri;
}
Note: Somewhere i heard about the restrictions on the arguments of the Exception handler method. i.e we can't add RedirectAttributes on the Exception Handler method. If we do so, that method will be ignored by the Spring when an exception is raised.
And i don't want to write the redirection code in the request handler method (i.e in loadUserById(int) ). Bcoz if i do so, i have to write the same code in all the controller methods in which the exception is raised. So, what my doubt is that
1) is there any alternative way to set my message information to the redirect process in the Exception handler method
2) can i use the "referal" to get the source of the request ( is always returns the correct uri)
Any ideas, please Thanks.