Skip to main content
 首页 » 编程设计

spring-mvc之如何使用 Spring MVC 使用 POST 变量重定向

2025年02月15日20lyj

我编写了以下代码:

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

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

请您参考如下方法:

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 接受一些请求参数,那么在重定向时你必须传递它们。

只需在重定向时发送此方法所需的所有属性...

谢谢你。