Framework/Spring
Spring Controller에서 외부 URL 호출하기
호형
2021. 7. 15. 17:26
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
@Controller
public class ExRedirectController {
// return string
@GetMapping("/ex_redirect1")
public String exRedirect1() {
return "redirect:http://www.naver.com";
}
// return ModelAndView
@GetMapping("/ex_redirect2")
public ModelAndView exRedirect2() {
String projectUrl = "http://www.naver.com";
return new ModelAndView("redirect:" + projectUrl);
}
// httpServletResponse.sendRedirect
@GetMapping("/ex_redirect3")
public void exRedirect3(HttpServletResponse httpServletResponse) throws IOException {
httpServletResponse.sendRedirect("https://naver.com");
}
// RedirectView
@RequestMapping("/ex_redirect4")
public RedirectView exRedirect4() {
RedirectView redirectView = new RedirectView();
redirectView.setUrl("http://www.naver.com");
return redirectView;
}
// httpHeaders
@RequestMapping("/ex_redirect5")
public ResponseEntity<Object> exRedirect5() throws URISyntaxException {
URI redirectUri = new URI("http://www.naver.com");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(redirectUri);
return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
}
}
출처 : http://jmlim.github.io/spring/2019/09/30/spring-redirect-to-an-external-url/
Spring Controller에서 외부 URL을 호출하는 예제가 잘 정리된 글이 있어서 가지고 왔다.