【发布时间】:2023-04-07 11:53:02
【问题描述】:
我正在开发基于 Spring Web 的项目,我在使用 @ModelAttribute 时遇到问题,它会将模型对象返回给 JSP 文件以进行填充,然后将其传递给控制器函数,然后将数据保存到数据库中。让我给你看一些代码。
这是我的软件工程课程项目,更详细的信息代码可在 github 上找到: https://github.com/IYTECENG316SoftwareEngineering/reddit
@Controller
public class MessageController {
@ModelAttribute("privateMessage")
public PrivateMessage constructPrivateMessage() {
return new PrivateMessage();
}
@RequestMapping(value = "/message/{id}", method = RequestMethod.POST, params = "sendMessage")
public String doSendMessage(Model model, @PathVariable("id") int id,
@Valid @ModelAttribute("privateMessage") PrivateMessage privateMessage, BindingResult result,Principal principal) {
if (result.hasErrors()) {
return showMessage(model,id);
}
User messageOwner = userService.findOne(principal.getName());
//I need to create new instance of PrivateMessage because
//(@ModelAttribute("privateMessage") PrivateMessage privateMessage) this gives always same ID.
PrivateMessage message = new PrivateMessage();
message.setMessage(privateMessage.getMessage());
message.setUser(messageOwner);
PrivateMessageConversation conversation = messageService.findOneWithMessages(id);
message.setPrivateMessageConversation(conversation);
messageService.save(message);
return "redirect:/message/"+message.getID()+".html";
}
}
PrivateMessage 对象发送到 jsp 文件并使用 @ModelAttribute 填充发送回 doSendMessage 函数。对象带有填充(所有输入都完美地写入对象),但唯一的问题是它的 ID 不是自动递增的。我还想展示另外一个代码。我们对主题使用相同的模板,并且效果很好。代码在这里;
@Controller
public class UserController {
@ModelAttribute("topic")
public Topic contructTopic() {
return new Topic();
}
@ModelAttribute("entry")
public Entry contructEntry() {
return new Entry();
}
@RequestMapping(value = "/account", method = RequestMethod.POST)
public String doAddNewTopic(Model model,
@Valid @ModelAttribute("topic") Topic topic,
BindingResult resultTopic, Principal principal,
@Valid @ModelAttribute("entry") Entry entry,
BindingResult resultEntry,
@RequestParam("topic_category") String category_string) {
System.out.println(principal.getName() + " " + category_string + " "
+ topic.getTitle() + " " + entry.getDescription());
if (resultTopic.hasErrors()) {
return account(model, principal);
}
if (resultEntry.hasErrors()) {
return account(model, principal);
}
String name = principal.getName();
Category category = categoryService.findByName(category_string);
topic.setCategory(category);
topicService.save(topic);
entry.setTopic(topic);
entry.setPublishedDate(new LocalDateTime());
entryService.save(entry, name);
return "redirect:/topic/" + topic.getId() + ".html";
}
}
以上代码完美运行。主题和条目对象发送到 jsp,它们填充并发送回控制器,它们的所有属性都很好,ID 是自动递增的。我们无法弄清楚为什么第一个不起作用。
注意:我们使用的是 Hibernate、Spring Data JPA 和 Tiles
【问题讨论】:
标签: spring hibernate modelattribute