在我的应用程序中,实际上有3个几乎完全相同的thymeleaf控制器函数,其中只有1个不能正常工作。它们都使用“redirect:”作为数据库更改后的返回值。这些更改应该显示在重定向所指示的请求页面上,因此它们应该是“刷新”视图。这两个函数正好可以做到这一点,但这一个不行。因为它们在结构上是一样的,我不知道这里发生了什么。唯一的区别是,这两个执行“保存”和另一个“删除”操作。我粘贴我的3个函数和重定向到这里。谢谢你,如果你能帮忙的话!
过帐功能(工程):
@PostMapping("/posting/{user_id}")
public ModelAndView posting(@ModelAttribute Post post, @PathVariable("user_id") long user_id) {
User u = userRepo.findById(user_id);
Date date = new Date(currentTimeMillis());
String dateToString = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.SHORT).format(date);
post.setDate(dateToString);
post.setUser(u);
postRepo.save(post);
return new ModelAndView("redirect:/newsfeed/" + u.getId());
}
“喜欢”功能(作品)
@GetMapping("/like/{postId}/{userId}")
public ModelAndView like(@PathVariable("postId") long postId, @PathVariable("userId") long userId) {
Post p = (Post) postRepo.findById(postId);
long[] likes = p.getLikes();
boolean isLiked = false;
for (int x = 0; x < likes.length; x++) {
if (likes[x] == userId) isLiked = true;
}
if (isLiked == false) {
p.addLike(userId);
postRepo.save(p);
}
return new ModelAndView("redirect:/newsfeed/" + userId);
}
delete函数(这个函数不起作用-即执行重定向,但显示未更改的视图)
@GetMapping("/deletePost/{post_id}")
public ModelAndView deletePost(@PathVariable("post_id") long post_id) throws InterruptedException {
Post post = postRepo.findById(post_id);
long userId = post.getUser().getId();
System.out.println(userId);
postRepo.delete(post);
TimeUnit.SECONDS.sleep(3);
return new ModelAndView("redirect:/newsfeed/" + userId);
}
在这个函数中,我重定向了上面的内容:
@GetMapping("/newsfeed/{id}")
public String newsfeed(Model model, @PathVariable("id") long id) {
ArrayList<Post> posts = (ArrayList) postRepo.findAll();
ArrayList<User> users = (ArrayList) userRepo.findAll();
User[] onlineUsers = users.stream().filter(u -> u.isOnline() == true).toArray(User[]::new);
Post[] orderedPosts = new Post[posts.size()];
if (!posts.isEmpty()) {
long maxOrdinal = 0;
for (int x = 0; x < posts.size(); x++) {
if (maxOrdinal < posts.get(x).getId()) maxOrdinal = posts.get(x).getId();
}
long missing = maxOrdinal - posts.size();
for (int x = 0; x < posts.size(); x++) {
long ordinal = posts.get(x).getId();
if (ordinal > missing) ordinal -= missing;
orderedPosts[(int) ((long) posts.size() - ordinal)] = posts.get(x);
}
}
User user = userRepo.findById(id);
Post post = new Post();
model.addAttribute("posts", orderedPosts);
model.addAttribute("user", user);
model.addAttribute("post", post);
model.addAttribute("users", onlineUsers);
return "newsfeed";
}
暂无答案!
目前还没有任何答案,快来回答吧!