0

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.

Snr
  • 141
  • 4

2 Answers2

0

You can use async JavaScript requests to load a user. Here is a basic example in angular:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        <h1>Angular async example</h1>
        <span ng-if="error">
            {{error}}
        </span>
        <br/>
        <span ng-model="user.name">{{user.name}}</span>
        <!--populate data as you wish -->
    </div>

    <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', ['$scope','$http',function($scope, $http) {
        $scope.user=null;
        $http.get('/user/' + 1) // you can get id from somewhere else
            .success(function(data){
                $scope.user = data; 
            }).error(function(data){
                $scope.error = data;
            });
    }]);
    </script>
</body>
</html>

This example will work with a proper server. It's just a proof of concept, you will need to do more to adapt a JavaScript approach.

mtyurt
  • 3,369
  • 6
  • 38
  • 57
0

The RedirectAttributes parameter in controller methods is just a nice wrapper around the Flash concept of Spring MVC. As it is commonly used there, Spring fellows just wanted it to be simple to use.

But the flash is always available. Simply, you must explicitely require the output flash map with static methods from RequestContextUtils.

@ExceptionHandler(UserNotFoundException.class)
public String handleUserNotFoundException(HttpServletRequest request){
   String uri=request.getHeader("referer");

   // Get the output flash mapp
   Map<String, Object> flash = RequestContextUtils.getOutputFlashMap(request);
   // populate the flash map with attributes you want to pass to redirected controller

   // now i want to redirect that uri
   return "redirect:"+uri;
}

You will find references for that in that other answer of mine

Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252