我有一个像这样写的GET方法的控制器:
@Controller
public class ThingController {
@RequestMapping( value = "/Thing.html", method = RequestMethod.GET )
public String editThing(@RequestParam( "thingId" ) String thingId, @ModelAttribute ThingBean thing, BindingResult result) {
thing = <some service call using thingId>
logger.debug("The thing to edit is {}", thingBean);
return "thing/edit";
}
}
Run Code Online (Sandbox Code Playgroud)
bean是正确的(getter和setter),服务调用使用thingId返回正确的ThingBean,并且在thing/edit.jsp上的JSP页面显示出来.
JSP是:
<html>
<body>
<h1 id="title" class="title">Edit Thing</h1>
<form:form id="thing" modelAttribute="thing">
<form:input path="subject" id="subject" tabindex="1" />
<form:textarea path="message" />
</form:form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
然而,JSP显示主题和消息的空白值.是的,这些房产上有吸气剂/固定剂.
我有一个非常相似的控制器工作正常,除了在那里的GET映射方法的签名中没有@RequestParam.
我没有在Spring WebMVC文档中看到任何地方说我不能这样做 - 为什么它不起作用?为什么更新后的ModelAttribute对象没有绑定到JSP表单中?
编辑:
这个控制器和GET调用的相同模式已经工作了很多不同的地方 - 用@ModelAttribute注释的变量由方法填充,然后可供JSP页面显示.为什么,通过添加@RequestParam注释,它会停止吗?
@RequestMapping( value = "/Things.html", method = RequestMethod.GET )
public String getThings(@ModelAttribute ThingForm thingForm, BindingResult result) {
try {
// need to get list of Things
List<Thing> Things = <service call that gets list of Things>;
thingForm.setThings(Things);
logger.debug("Things are {}", Things);
}
catch (ResourceNotFoundException e) {
return "error";
}
logger.debug("Thing list loading - end");
// Go to jsp
return "thing/list";
}
Run Code Online (Sandbox Code Playgroud)
问题是你只是为事物分配一个新的引用,它永远不会在Java中工作.您必须将它放在模型中,否则您的视图将无法识别.
@RequestMapping( value = "/Thing.html", method = RequestMethod.GET )
public String editThing(@RequestParam( "thingId" ) String thingId, @ModelAttribute ThingBean thing, BindingResult result) {
thing = <some service call using thingId> // This is only assigning a new reference not updating
logger.debug("The thing to edit is {}", thingBean);
return "thing/edit";
}
Run Code Online (Sandbox Code Playgroud)
所以相反,这样做
@RequestMapping( value = "/Thing.html", method = RequestMethod.GET )
public String editThing(@RequestParam( "thingId" ) String thingId, @ModelAttribute ThingBean thing, BindingResult result, Model model) {
thing = <some service call using thingId>
model.addAttribute("thing", thing);
logger.debug("The thing to edit is {}", thingBean);
return "thing/edit";
}
Run Code Online (Sandbox Code Playgroud)
这让我想知道为什么你在这个方法中甚至有一个模型属性?它基本上没用.
而不是上面我会做这样的事情
@ModelAttribute("thing")
public Thing prepareModel(@RequestParam("thingId") String thingId) {
return thingSergice.findById(thingId);
}
Run Code Online (Sandbox Code Playgroud)
现在,在每个请求处理方法之前调用此方法.您可以在其中简单地引用它而不必每次都查找它.(从您的代码判断您的方法中的Thingbean模型属性是非常无用的我会将其重写为以下内容)
@RequestMapping( value = "/Thing.html", method = RequestMethod.GET )
public String editThing() {
return "thing/edit";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21713 次 |
| 最近记录: |