如何在Spring MVC中重定向到POST

Vir*_*mal 5 spring-mvc

I have written code as given below-


@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"; 
  }
}
Run Code Online (Sandbox Code Playgroud)

我想重定向到请求方法为POST的"anotherUrl"请求映射.

Oom*_*ity 12

在Spring中,Controller方法可以是Both.这意味着它可以是GET以及POST ...在你的场景中,

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

你想要这个GET,因为你正在重定向到它...因此你的解决方案将是

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

注意:这里如果你的方法接受@ requestParam的一些请求参数,那么在重定向时你必须传递它们这个方法所需的所有属性必须在重定向时发送...

谢谢

  • 从技术角度来看,这是行得通的,但是,如果您正在编写RESTful应用程序,则这将违反GET的“无副作用”期望-因此,追求该解决方案的任何人都请注意常规上的中断。我建议您找到另一种方法,或者确实非常好地记录下来(至少) (3认同)