Why ModelAtribute passed as null?

北城余情 提交于 2019-12-21 23:09:21

问题


I developed next target class

class Person{
    public Person(){}
    public Person(String name) {
        super();
        this.name = name;
    }

    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

next controller:

@Controller
        private static class SampleController {


                @RequestMapping(value="/path", method=RequestMethod.POST)
                public String path(@Valid @ModelAttribute("person") Person person, BindingResult result, Model model) {
                    model.addAttribute("name",person.getName()); 
                    System.out.println(person.getName());
                    return "view";
                }
        }

and next test:

public class ModelAssertionTests {

        private MockMvc mockMvc;

        @Before
        public void setup() {

                SampleController controller = new SampleController("a string value", 3, new Person("a name"));

                this.mockMvc = standaloneSetup(controller)
                                .defaultRequest(get("/"))
                                .alwaysExpect(status().isOk())
                                .build();
        }
        @Test
        public void testTest() throws Exception {
                Person person = new Person("name");
                mockMvc.perform(post("/path").sessionAttr("person", person));
        }
}

Switch on debug mode

at this line:

 mockMvc.perform(post("/path").sessionAttr("person", person));

I see that

when I go to controller method to:

 model.addAttribute("name",person.getName()); 

I see that

What the reason of it?

How to fix it?


回答1:


This is because sessionAttr("person", person) in your mockMvc request sets person as a session attribute, while @ModelAttribute annotates model attributes.

To put session variable into the model (and therefore fix you problem), use @SessionAttributes annotation:

@Controller
@SessionAttributes("person")
private static class SampleController {
    ...
}

Read more here.

By the way, your Controller should be public, not private static.



来源:https://stackoverflow.com/questions/19427341/why-modelatribute-passed-as-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!