Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect in controllers spring3

In Spring 3 you map urls as simply as this:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String index(Model model)  {
    return "index";
}

Is it possible to make this kind of method to kinda redirect to another url like:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String index(Model model)  {
    return "second.html";
}

@RequestMapping(value = "/second.html", method = RequestMethod.GET)
public String second(Model model)  {
//put some staff in model
    return "second";
}
like image 667
mjgirl Avatar asked Feb 22 '11 11:02

mjgirl


People also ask

What is the difference between forward and redirect in Spring MVC?

Differences We passed the parameter “name” with a value in both cases. Simply put, forwarded requests still carry this value, but redirected requests don't. This is because, with a redirect, the request object is different from the original one.

How do I redirect in spring boot controller?

We can use a name such as a redirect: http://localhost:8080/spring-redirect-and-forward/redirectedUrl if we need to redirect to an absolute URL.

How do I redirect a page in spring?

Try a URL http://localhost:8080/HelloWeb/index and you should see the following result if everything is fine with your Spring Web Application. Click the "Redirect Page" button to submit the form and to get the final redirected page.

How use redirect attribute in Spring MVC?

You can use RedirectAttributes to store flash attributes and they will be automatically propagated to the "output" FlashMap of the current request. A RedirectAttributes model is empty when the method is called and is never used unless the method returns a redirect view name or a RedirectView.


1 Answers

You don't need to redirect - just call the method:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String index(Model model)  {
    return second(model);
}

@RequestMapping(value = "/second.html", method = RequestMethod.GET)
public String second(Model model)  {
    //put some staff in model
    return "second";
}

This is one of the nice things about the annotation style; you can just chain your methods together.

If you really want a redirect, then you can return that as a view:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public View index(Model model)  {
    return new RedirectView("second.html");
}

@RequestMapping(value = "/second.html", method = RequestMethod.GET)
public String second(Model model)  {
    //put some staff in model
    return "second";
}
like image 53
skaffman Avatar answered Nov 15 '22 10:11

skaffman