如何使用Spring MVC使用POST变量进行重定向


问题内容

我写了以下代码:

@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"; 
      }
    }

我如何能够重定向到请求方法为POST的“ anotherUrl”请求映射?


问题答案:

spring Controller方法可以是POST和GET请求。

在您的情况下:

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

您需要此GET,因为您正在重定向到它。因此,您的解决方案将是

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

注意:这里,如果您的方法接受@requestParam的某些请求参数,则在重定向时必须传递它们。

仅此方法所需的所有属性都必须在重定向时发送…

谢谢。