简体   繁体   English

Spring MVC更新ModelAttribute值

[英]Spring MVC update ModelAttribute value

When modifying a ModelAttribute that is listed as a SessionAttribute , why doesent it keep its new value? 在修改ModelAttribute被列为SessionAttribute ,为什么doesent它保持它的新价值?

Every time I make a request to the example below, it prints out "Initial value.", which is a correct value for the first request. 每次我向下面的例子发出请求时,它都会打印出“初始值。”,这是第一个请求的正确值。 But after the first request, its value should be "new value". 但是在第一次请求之后,它的值应该是“新值”。

Why doesent ModelAttribute store its value? 为什么不存在ModelAttribute存储它的值?

I have a base class. 我有一个基类。 All servlets extending this: 所有servlet都扩展了这个:

@SessionAttributes(value = {"test_string", "something"})
public abstract class Base<T>
    {
    public abstract T request(
            @ModelAttribute("test_string") String _test_string,
            ModelAndView _mv);

    @ModelAttribute("test_string")
    private String getTest()
    {
        return "Initial value.";
    }
}

I have a specific servlet: 我有一个特定的servlet:

@Controller
public class InterfaceController extends Base<String>
{
    @PostMapping(value = "/interface")
    @ResponseBody
    @Override
    public String request(
        @ModelAttribute("test_string") String _test_string,
        ModelAndView _mv)
    {
        System.out.println(_test_string);
        _test_string = "new value";

        return "whatever content";
    }
}

I'm no Spring MVC expert but your problem seems to be understanding Java pass-by-reference and String inmutability. 我不是Spring MVC专家,但你的问题似乎是理解Java传递引用和String inmutability。 I've made a diagram to help you understand what the problem is but you may need to research more info about it. 我已经制作了一个图表来帮助您了解问题所在,但您可能需要研究更多相关信息。

图

  1. When you invoke sysout, you are printing the value pointed by "_test_string" (method argument), that at this point is the same that ModelAttribute "test_string". 当您调用sysout时,您将打印“_test_string”(方法参数)指向的值,此时与ModelAttribute“test_string”相同。

  2. When you assign "new value" to "_test_string" (method argument), notice that you're NOT changing the value of "test_string" (ModelAttribute) 将“new value”分配给“_test_string”(方法参数)时,请注意您没有更改“test_string”(ModelAttribute)的值

  3. It's what I think you have to do to overwrite the value stored in the Model. 这是我认为你必须要覆盖模型中存储的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM