메모

Spring 컨트롤러에서 외부 URL 호출

일일일코_장민기 2024. 3. 28. 13:24
728x90
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);
   }
}

'메모' 카테고리의 다른 글

POSTMAN 툴  (0) 2024.03.21
int의 기본값은 없다...  (0) 2024.03.21
20240320_익명 게시판의 좋아요와 싫어요  (0) 2024.03.20
팝오버 이벤트  (0) 2024.03.20
스프링부트 팀플) 20240319 익명 게시판의 상태저장 고민  (0) 2024.03.19