Gábor DANI
Gábor DANI

Reputation: 2135

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

Upvotes: 3

Views: 1700

Answers (1)

RubioRic
RubioRic

Reputation: 2468

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.

Diagram

  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.

Upvotes: 3

Related Questions