问题
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