【问题标题】:How to share information between Spring controller methods from GET and POST requests?如何在来自 GET 和 POST 请求的 Spring 控制器方法之间共享信息?
【发布时间】:2016-11-18 15:55:37
【问题描述】:

我是 Spring 新手,我想:

1) 当用户访问 localhost/admin/users 我希望应用预定义的选项

2) 在 localhost/admin/users 我有一些按钮可以执行带有四个参数的POST,因为我的老板不希望我使用 get(我认为最好使用POST,也是)

3) 我有一个控制器方法adminUsersPost 来管理POST 请求,并且我希望该方法能够使我的浏览器使用adminUsersGet 方法重新加载,但在@ 中发送信息987654327@ 请求。

我现在在我的浏览器中得到的是一个带有某种奇怪编码的网页内容的警报,我希望它是正确的,但我不知道。

@RequestMapping(value = "/admin/users", method = RequestMethod.GET)
public ModelAndView adminUsersGet(
    Integer page,
    Integer items,
    String sorting,
    String sortingDirection)
{
  // predefined options
  Integer pagina = 1;
  Integer itemsPorPagina = 10;
  String ordenacion = "idUsuario";
  String dirOrdenacion = "asc";
  // end of predefined options

  // Code that I want for it to use POST params from the other method


  ModelAndView mv = new ModelAndView("adminUsers");
  return mv;
}

@RequestMapping(value = "/admin/users", method = RequestMethod.POST)
public ModelAndView adminUsersPost(
    @RequestParam(value = "pagina") Integer pagina,
    @RequestParam(value = "itemsPorPagina") Integer itemsPorPagina,
    @RequestParam(value = "ordenacion") String ordenacion,
    @RequestParam(value = "dirOrdenacion") String dirOrdenacion)
{
  // Here I try to pass the POST parameters to the GET method for reloading
  // the webpage with the new content
  return adminUsersGet(pagina, itemsPorPagina, ordenacion, dirOrdenacion);
}

【问题讨论】:

  • 要重定向,您可以使用文档中关于重定向的内容:docs.spring.io/spring/docs/current/spring-framework-reference/…。但是 POST 方法的意义何在。如果它所做的只是重定向到 GET,为什么还要使用 POST?为什么要使用 POST 进行看似搜索但不会创建任何资源的搜索?这就是 GET 的用途。
  • @JBNizet 我对 Spring 很陌生,我只希望网页重新加载新选项但没有查询字符串,只是在 Spring 控制器方法之间共享信息或从 POST 管理器方法本身重定向。如何实现这一点并不重要,但我想要一个没有查询字符串的 URL。
  • 然后使用 POST,而不是 GET。但它违反了所有网络标准。查询字符串有什么问题?谷歌使用查询字符串进行搜索,这并不妨碍他们成功(相反)。网络是由聪明人设计的。为什么要违背它的设计?

标签: java spring post controller get


【解决方案1】:

模式 POST params-->GET 相同的参数是一种常见的模式。您需要的是 RedirectAttributes,它将您的参数存储到会话中并重定向到您的 GET 方法。一旦 GET 被触发,spring 将自动从会话中删除所有属性,因此 GET 方法中的浏览器 url 中不会显示任何 POST 参数。查看here 的完整示例并根据您的需要进行调整。

【讨论】:

  • 谢谢,现在我的 GET 管理器方法中有 POST 参数,但我收到的是 javascript 警报,而不是重新加载页面。更新了pastebin.com/8gSC4e6G 上的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 2013-08-01
  • 2011-06-10
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
相关资源
最近更新 更多