简体   繁体   中英

Spring MVC update ModelAttribute value

When modifying a ModelAttribute that is listed as a SessionAttribute , why doesent it keep its new value?

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?

I have a base class. All servlets extending this:

@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:

@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. 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".

  2. When you assign "new value" to "_test_string" (method argument), notice that you're NOT changing the value of "test_string" (ModelAttribute)

  3. It's what I think you have to do to overwrite the value stored in the Model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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