Forward a POST request with additional params

0x56794E picture 0x56794E · Nov 21, 2013 · Viewed 7.8k times · Source

Is there a way to forward a POST request from one controller to another with additional param(s)?

Let's say I have a form like this:

<form action"${contextPath}/controller1/post">
  <input name="field1" type="text"/>
  <input name="field2" type="text"/>
  <input value="submit" type="submit"/>
</form>

This form will post to controller1.post() method.

But now I have another controller - controller2 also with a post method. I now want to post to controller2.post so I could add some parameters to the request before forwarding to controller1. Is there a way to do this?

Answer

Anton picture Anton · Nov 21, 2013

You can try that if this is what you are looking for

@RequestMapping(value = "/controller1/{id}", method = RequestMethod.Post)
public void doSomething(
        @PathVariable Long id, 
        HttpServletRequest request, 
        HttpServletResponse response) {

     request.setAttribute("id",Id);

     RequestDispatcher rd = request.getRequestDispatcher("your url/controller2");
     rd.forward(request, response);
}

And after in controller2

@RequestMapping(value = "/controller2", method = RequestMethod.Post)
public string doSomething2(Model model,       
        HttpServletRequest request, 
        HttpServletResponse response) {

     model.addAttribute("id", request.getAttribute("id"));

    return "myView";
}