本文介绍了为什么ModelAtribute传递为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开发了下一个目标类
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;
}
}
下一个控制器:
@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";
}
}
和下一次测试:
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));
}
}
启用调试模式
此行:
mockMvc.perform(post("/path").sessionAttr("person", person));
我看到了
当我转到控制器方法时:
when I go to controller method to:
model.addAttribute("name",person.getName());
我看到了
它是什么原因?
如何解决?
推荐答案
这是因为你的mockMvc请求中的sessionAttr(person,person)
将 person
设置为会话属性,而 @ModelAttribute
注释模型属性。
This is because sessionAttr("person", person)
in your mockMvc request sets person
as a session attribute, while @ModelAttribute
annotates model attributes.
将会话变量放入模型中(因此修复你的问题),使用 @SessionAttributes
注释:
To put session variable into the model (and therefore fix you problem), use @SessionAttributes
annotation:
@Controller
@SessionAttributes("person")
private static class SampleController {
...
}
了解更多。
顺便说一句,你的控制器应为 public
,而非 private static
。
By the way, your Controller should be public
, not private static
.
这篇关于为什么ModelAtribute传递为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!