Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to dynamic URL in Spring MVC

I want my Spring MVC application to redirect to a dynamic URL (submitted by the user). So if I have code like this,

@RequestMapping("/redirectToSite") protected ModelAndView redirect(     @RequestParam("redir_url") String redirectUrl,     HttpServletRequest request,      HttpServletResponse response)  {     // redirect to redirectUrl here     return ? } 

what should I write to redirect to the submitted URL? For instance http://mySpringMvcApp/redirectToSite?redir_url=http://www.google.com should redirect to Google.

like image 384
Gruber Avatar asked Feb 16 '12 13:02

Gruber


People also ask

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 do I forward a Spring MVC request?

A request can be basically processed in three ways: a) resolved by Spring in a controller action, b) forwarded to a different controller action, c) redirected to client to fetch another URL. Forward: performed internally by Spring. the browser is completely unaware of forward, so its original URL remains intact.

How we can redirect to another page or controller in Spring MVC?

java. Following is the content of Spring view file index. jsp. This will be a landing page, this page will send a request to the access-redirect service method, which will redirect this request to another service method and finally a final.

What is the use of redirect in Spring MVC?

By using a redirect after processing the form, an application can for the most part prevent the user from hitting refresh and re-submitting the form - as they are now at the newly redirected url.


1 Answers

Try this:

@RequestMapping("/redirectToSite") protected String redirect(@RequestParam("redir_url") String redirectUrl)  {     return "redirect:" + redirectUrl; } 

This is explained in 16.5.3.2 The redirect: prefix of Spring reference documentation. Of course you can always do this manually:

response.sendRedirect(redirectUrl); 
like image 112
Tomasz Nurkiewicz Avatar answered Sep 28 '22 02:09

Tomasz Nurkiewicz