Question: I have a REST endpoint implemented with Spring MVC @RestController. Sometime, depends on input parameters in my controller I need to send http redirect on client. 

Is it possible with Spring MVC @RestController and if so, could you please show an example ?

Answer: 
`redirect` means http code `302`, which means `Found` in springMVC. 

Here is an util method, which could be placed in some kind of `BaseController`:

```
protected ResponseEntity found(HttpServletResponse response, String url) throws IOException { // 302, found, redirect,
    response.sendRedirect(url);
    return null;
}

```

---

But sometimes might want to return http code `301` instead, which means `moved permanently`.

In that case, here is the util method:

```
protected ResponseEntity movedPermanently(HttpServletResponse response, String url) { // 301, moved permanently,
    return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).header(HttpHeaders.LOCATION, url).build();
}

```
As the redirections are usually needed in a not-straightforward path, I think throwing an exception and handling it later is my favourite solution.

Using a ControllerAdvice

```
@ControllerAdvice
public class RestResponseEntityExceptionHandler
    extends ResponseEntityExceptionHandler {

  @ExceptionHandler(value = {
      NotLoggedInException.class
  })
  protected ResponseEntity<Object> handleNotLoggedIn(
      final NotLoggedInException ex, final WebRequest request
  ) {
    final String bodyOfResponse = ex.getMessage();

    final HttpHeaders headers = new HttpHeaders();
    headers.add("Location", ex.getRedirectUri());
    return handleExceptionInternal(
        ex, bodyOfResponse,
        headers, HttpStatus.FOUND, request
    );
  }
}

```

The exception class in my case:

```
@Getter
public class NotLoggedInException extends RuntimeException {

  private static final long serialVersionUID = -4900004519786666447L;

  String redirectUri;

  public NotLoggedInException(final String message, final String uri) {
    super(message);
    redirectUri = uri;
  }
}

```

And I trigger it like this:

```
if (null == remoteUser)
  throw new NotLoggedInException("please log in", LOGIN_URL);

```