티스토리 뷰

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을 호출하는 예제가 잘 정리된 글이 있어서 가지고 왔다. 

 

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30