在 Spring Boot 中,可以通过使用RedirectViewController类或在Controller中使用RedirectAttributes来配置重定向。\n\n1. 使用RedirectViewController类配置重定向:\n在@Configuration类中,可以使用WebMvcConfigurer接口的addViewControllers方法来配置重定向。首先,需要创建一个RedirectViewController对象,并指定目标URL和重定向的路径。然后,通过调用addViewController方法将RedirectViewController对象添加到ViewControllersRegistry中。最后,使用addViewControllers方法将ViewControllersRegistry注册到ViewControllerRegistry中。\n\n示例代码如下:\n\njava\n@Configuration\npublic class WebConfig implements WebMvcConfigurer {\n\n @Override\n public void addViewControllers(ViewControllerRegistry registry) {\n RedirectViewController redirectViewController = new RedirectViewController("/source", "/target");\n registry.addViewController("/source").setViewController(redirectViewController);\n }\n}\n\n\n2. 在Controller中使用RedirectAttributes配置重定向:\n在Controller的处理方法中,可以使用RedirectAttributes将重定向的信息传递给目标URL。首先,将需要传递的信息添加到RedirectAttributes对象中,然后使用"redirect:URL"格式的字符串作为返回值来指定重定向的URL。\n\n示例代码如下:\n\njava\n@Controller\npublic class MyController {\n\n @GetMapping("/source")\n public String redirectToTarget(RedirectAttributes redirectAttributes) {\n redirectAttributes.addFlashAttribute("message", "Redirected successfully!");\n return "redirect:/target";\n }\n\n @GetMapping("/target")\n public String showTargetPage(@ModelAttribute("message") String message) {\n return "target";\n }\n}\n\n\n在上述示例中,redirectToTarget方法将消息添加到RedirectAttributes对象中,并返回"redirect:/target",表示需要重定向到/target路径。然后,showTargetPage方法接收message属性,并在目标页面中显示该消息。\n\n注意:在使用RedirectAttributes进行重定向时,使用addFlashAttribute方法添加的属性会暂时保存在会话中,并且在重定向后立即删除。这样可以确保属性在重定向后仍然可用。


原文地址: https://www.cveoy.top/t/topic/pLlk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录