programing

스프링 MVC @RestController 및 리다이렉트

madecode 2023. 3. 14. 22:05
반응형

스프링 MVC @RestController 및 리다이렉트

Spring MVC @RestController에서 구현된 REST 엔드포인트가 있습니다.컨트롤러의 입력 파라미터에 따라 클라이언트 상에서http 리다이렉트를 송신할 필요가 있는 경우가 있습니다.

Spring MVC @RestController로 가능합니까?그렇다면 예를 들어주시겠습니까?

를 추가합니다.HttpServletResponse[ Handler Method ]파라미터와 콜합니다.response.sendRedirect("some-url");

예를 들어 다음과 같습니다.

@RestController
public class FooController {

  @RequestMapping("/foo")
  void handleFoo(HttpServletResponse response) throws IOException {
    response.sendRedirect("some-url");
  }

}

에 대한 직접적인 의존을 피하기 위해HttpServletRequest또는HttpServletResponse다음과 같은 ResponseEntity를 반환하는 "순수한 봄" 구현을 제안합니다.

HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(newUrl));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);

메서드가 항상 리다이렉트를 반환하는 경우ResponseEntity<Void>그 이외의 경우는, 통상의 범용 타입으로 반환됩니다.

이 질문을 받고 아무도 Redirect View에 대해 언급하지 않아 놀랐습니다.방금 테스트한 결과, 다음과 같이 100% 스프링 방식으로 문제를 해결할 수 있습니다.

@RestController
public class FooController {

    @RequestMapping("/foo")
    public RedirectView handleFoo() {
        return new RedirectView("some-url");
    }
}

redirecthttp 코드를 의미합니다.302즉,Found봄MVC에서.

여기 util 메서드가 있습니다.이러한 메서드는 어떤 형태로든 배치될 수 있습니다.BaseController:

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

그러나 때때로 http 코드를 반환하고 싶을 수 있습니다.301대신, 즉moved permanently.

이 경우 util 메서드는 다음과 같습니다.

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

리다이렉트는 보통 간단하지 않은 경로에서 필요하기 때문에 예외를 두고 나중에 처리하는 것이 제가 가장 좋아하는 해결책이라고 생각합니다.

컨트롤러 어드바이스를 사용하는 방법

@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
    );
  }
}

내 경우 예외 클래스:

@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;
  }
}

그리고 나는 이렇게 트리거한다:

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

@RestController가 문자열을 반환하면 다음과 같은 기능을 사용할 수 있습니다.

return "redirect:/other/controller/";

이러한 리다이렉트는 GET 요청 전용으로, 다른 유형의 요청을 사용하려면 Http Servlet Response를 사용합니다.

언급URL : https://stackoverflow.com/questions/29085295/spring-mvc-restcontroller-and-redirect

반응형