Url redirection from a spring boot controller

by Jayant Chaudhary   Last Updated September 12, 2019 02:26 AM

I am hitting a controller in spring boot application and from there when i return to browser i want it to redirect to another website or url other than spring boot application templates.

Answers 2

There are more ways to do this. The most straightforward and Spring-alike I find in the usage of RedirectView. Here is some code:

public RedirectView redirectWithUsingRedirectView(RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute("flashAttribute", "redirectWithRedirectView");
    redirectAttributes.addAttribute("attribute", "redirectWithRedirectView");
    return new RedirectView("redirectedUrl");

Explore more at A guide to Spring redirect.

September 11, 2019 19:43 PM

You can do it in many ways

Using RedirectView

public RedirectView localRedirect() {
    RedirectView redirectView = new RedirectView();
    return redirectView;

Using ResponseEntity

public ResponseEntity<Object> redirectToExternalUrl() throws URISyntaxException {
    URI yahoo = new URI("http://www.yahoo.com");
    HttpHeaders httpHeaders = new HttpHeaders();
    return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);

Using HttpServletResponse

@RequestMapping(value = "/", method = RequestMethod.GET)
public void redirectToTwitter(HttpServletResponse httpServletResponse) throws IOException {

Using ModelAndView

@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView method() {
    return new ModelAndView("redirect:" + projectUrl);
September 12, 2019 02:25 AM

Related Questions

Spring Boot Multi-Module maven project repackage failed

Updated September 18, 2019 01:26 AM

Spring Integration Java DSL with H2 adapter

Updated March 10, 2018 02:26 AM

convert xml config to java config for spring social

Updated February 10, 2018 11:26 AM

A simple curl command causes this ridiculousness

Updated May 15, 2018 21:26 PM