Viraj Dhamal
Viraj Dhamal

Reputation: 5325

How to redirect with POST variables with Spring MVC

I have written the following code:

@Controller
    @RequestMapping("something")
    public class somethingController {
       @RequestMapping(value="/someUrl",method=RequestMethod.POST)
       public String myFunc(HttpServletRequest request,HttpServletResponse response,Map model){
        //do sume stuffs
         return "redirect:/anotherUrl"; //gets redirected to the url '/anotherUrl'
       }

      @RequestMapping(value="/anotherUrl",method=RequestMethod.POST)
      public String myAnotherFunc(HttpServletRequest request,HttpServletResponse response){
        //do sume stuffs
         return "someView"; 
      }
    }

How would i be able to redirect to "anotherUrl" request mapping whose request method is POST?

Upvotes: 5

Views: 37345

Answers (1)

Oomph Fortuity
Oomph Fortuity

Reputation: 6118

A spring Controller methods can be both POST and GET requests.

In your scenario:

@RequestMapping(value="/anotherUrl",method=RequestMethod.POST)
  public String myAnotherFunc(HttpServletRequest request,HttpServletResponse response){
    //do sume stuffs
     return "someView"; 
  }

You want this GET because you are redirecting to it. Hence your solution will be

  @RequestMapping(value="/anotherUrl", method = { RequestMethod.POST, RequestMethod.GET })
      public String myAnotherFunc(HttpServletRequest request,HttpServletResponse response){
        //do sume stuffs
         return "someView"; 
      }

Caution : here, if your method accepts some request parameters by @requestParam,then while redirecting you must pass them.

Simply all attributes required by this method must send while redirecting...

Thank You.

Upvotes: 12

Related Questions