java - 在 Get 和 Post Controller 之间传递属性,但不在 URL 中传递属性

标签 java spring spring-boot

我有一个 POST Controller ,它采用一个表单并根据给定的输入执行一些计算。 IE 如果表单提交两个变量 a 和 b ,则 POST 方法将采用这两个变量并创建整数 c=a+b。 现在我想将此 Integer C 传递给我的 GET Controller ,因为当我从 get Controller 返回模型和 View 时,我需要将 C 作为对象传递,以便能够在我的 Thymeleaf 模板中使用它。

实现这一目标的最佳方法是什么? 我使用来自 POST 方法的 return new ModelAndView("redirect:/path") ,然后 GET 方法映射该链接。 我不想在 URL 中传递变量。 我尝试使用像 addFlashAttributes 这样的重定向属性,但刷新后我丢失了该值,并且我需要保留该值显示在页面中。

示例代码

@RequestMapping(value = "/user", method = RequestMethod.POST )
public ModelAndView sumValue(@Valid Sum sum, BindingResult bindingResult,RedirectAttributes redir) {
    long firstClient=compare.getId();
    long varA= compare.getA();
    long varB= compare.getB();

    Long c= varA+ varB.;

    ModelAndView modelAndView = new ModelAndView(
            "redirect:/user?firstId=" + firstClient);

    return modelAndView;
}


@RequestMapping(value = "/user", method = RequestMethod.GET, params = { "firstId" })
public ModelAndView comparison(@RequestParam(value = "firstId", required = true) String firstI) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("firstClient", firstId);
    //here i want to add as an Object varC from the Post controller so I can use it in my thymeleaf
    return modelAndView;
}

感谢任何帮助!

最佳答案

这里有多种选择:

  1. 您可以转发该页面。
  2. 您可以使用 setAttribute 将值存储在 session 中并使用 getAttribute 在 Get-controller 中获取它.
  3. 您可以通过创建静态 Map<Long, Long> 来混淆结果-classfield 将时间存储为 Key,将计算结果存储为 Value。如果 key 太旧,请将其取下。在运输 firstClient 时运输 key .

出于安全原因,我建议仅使用第二种方法,而不是第三种。

关于java - 在 Get 和 Post Controller 之间传递属性,但不在 URL 中传递属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46879158/

相关文章:

java - 为什么 java 命令在使用 java -cp 命令时将类路径识别为命令?

java - Spring MVC 和 @RequestParam 与 x-www-form-urlencoded

java - 在 Jhipster 微服务模型上开发面向客户端的 UI 的最佳方法/实践?

java - PHP 的 md5(str, true) 等价于什么?

java - 无法远程连接 VisualVM 到 CentOS

java:如何将变量从一种类型动态转换为另一种类型?

java - Spring Boot 错误没有可用的 'javax.persistence.EntityManagerFactory' 类型的合格 bean

spring - 排除 hibernate 创建的特定表?

java - 升级到 Spring 4.2 后 ContentNegotiatingViewResolver MediaTypes 错误

mysql - 使用 Spring Boot 将文件(pdf、doc、ppt)从 MySQL 显示到 Thymeleaf