Spring Boot应用Controller路由跳转异常问题求助
看起来你遇到了Spring Boot路由跳转的典型问题,我来帮你分析下可能的原因和解决办法:
问题核心场景回顾
你在访问首页http://localhost:8080/时点击博客进入详情页http://localhost:8080/posts/6,但此时点击导航栏返回首页时,URL变成了http://localhost:8080/posts/index并报错,这明显是路径拼接错误导致的。
具体解决步骤
1. 修复导航栏的链接路径问题
这是最直接的原因:你的导航栏返回首页的链接应该用了相对路径(比如href="index"),当你处于/posts/6这个子路径下时,相对路径会自动拼接成/posts/index,而你的Controller并没有映射这个路径,所以报错。
解决办法:把导航链接改成绝对路径,比如:
<!-- 正确写法 --> <a href="/">首页</a> <!-- 或者 --> <a href="/index">首页</a>
这样不管当前在哪个路径下,都会跳转到根路径的首页。
2. 清理重复的Controller路由映射
我注意到你有两个Controller(HomeController和PostsController)都映射了/和/index路径,这会让Spring无法确定哪个Controller来处理请求,可能导致路由冲突,间接引发跳转问题。
建议保留一个Controller的首页映射即可,比如删掉PostsController里的这段重复代码:
@RequestMapping(value= { "/" }, method = RequestMethod.GET) public String indexView(Model model) { List<Post> pt = new ArrayList<Post>(); model.addAttribute("posts", postRepository.findTop5ByOrderByCreatedAtDesc().get(pt.size())); model.addAttribute("posts5", postRepository.findTop5ByOrderByCreatedAtDesc().stream().limit(3).collect(Collectors.toList())); return "index"; }
如果PostsController有其他专属功能,只保留和posts相关的路由就好。
3. 检查视图返回路径的规范(可选)
另外,你的HomeController里的showPost方法返回的是"/view",如果用的是Thymeleaf这类模板引擎,通常不需要加开头的斜杠,直接写"view"即可,虽然这不是当前跳转问题的直接原因,但规范写法可以避免后续其他视图加载问题。
附上你提供的代码片段(方便参考)
HomeController代码:
@Controller public class HomeController { private static final String IMAGES_DIRECTORY = "/RDD-GHS/io.blog-master/images"; @Autowired private PostRepository postRepository; @RequestMapping(value = { "/", "/index" }) public String index(Model model) { List<Post> latest5Posts = this.postRepository.findTop5ByOrderByCreatedAtDesc(); model.addAttribute("latest5Posts", latest5Posts); List<Post> latest3Posts = latest5Posts.stream().limit(3).collect(Collectors.toList()); model.addAttribute("latest3Posts", latest3Posts); return "index"; // "Normal use" } @GetMapping("posts/{id}") public String showPost(@PathVariable Long id, Model model) throws Throwable { Post post = postRepository.findById(id).orElseThrow(new Supplier<Throwable>() { public Throwable get() { return new RuntimeException("Post not found"); } }); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); String formattedDate = dateFormat.format(post.getCreatedAt()); model.addAttribute("formattedDate", formattedDate); model.addAttribute("post", post); model.addAttribute("imagesPath", IMAGES_DIRECTORY); return "/view"; } }
PostsController代码:
@Controller public class PostsController { @Autowired private PostService postService; @Autowired private PostRepository postRepository; @RequestMapping(value= { "/" }, method = RequestMethod.GET) public String indexView(Model model) { List<Post> pt = new ArrayList<Post>(); model.addAttribute("posts", postRepository.findTop5ByOrderByCreatedAtDesc().get(pt.size())); model.addAttribute("posts5", postRepository.findTop5ByOrderByCreatedAtDesc().stream().limit(3).collect(Collectors.toList())); return "index"; } }
备注:内容来源于stack exchange,提问作者J Maine

