在Spring Boot项目中,接口跳转页面有多种方式,以下是详细的解决方案:

1. 使用 @Controller 注解(推荐)

@Controller
public class PageController {
    
    // 直接返回视图名称
    @GetMapping("/home")
    public String home() {
        return "home"; // 对应 templates/home.html
    }
    
    // 重定向到其他页面
    @GetMapping("/redirect")
    public String redirect() {
        return "redirect:/target-page";
    }
    
    // 转发到其他页面
    @GetMapping("/forward")
    public String forward() {
        return "forward:/target-page";
    }
}

2. 使用 @RestController 注解

@RestController
public class RedirectController {
    
    @GetMapping("/redirect")
    public void redirectToPage(HttpServletResponse response) throws IOException {
        response.sendRedirect("/target-page.html");
    }
    
    @GetMapping("/redirect2")
    public ResponseEntity<Void> redirectToPage2() {
        return ResponseEntity.status(HttpStatus.FOUND)
                .location(URI.create("/target-page.html"))
                .build();
    }
}

3. 使用 ModelAndView

@Controller
public class ModelAndViewController {
    
    @GetMapping("/mv-page")
    public ModelAndView showPage() {
        ModelAndView mv = new ModelAndView("page"); // 视图名称
        mv.addObject("message", "Hello World");
        mv.addObject("data", List.of("A", "B", "C"));
        return mv;
    }
    
    @GetMapping("/mv-redirect")
    public ModelAndView redirectPage() {
        return new ModelAndView("redirect:/target-page");
    }
}

4. 使用 HttpServletResponse 重定向

@RestController
public class ResponseRedirectController {
    
    @GetMapping("/response-redirect")
    public void responseRedirect(HttpServletResponse response) throws IOException {
        response.sendRedirect("/target-page.html");
    }
    
    @GetMapping("/response-redirect-external")
    public void responseRedirectExternal(HttpServletResponse response) throws IOException {
        response.sendRedirect("https://example.com");
    }
}

5. 使用 ResponseEntity 重定向

@RestController
public class ResponseEntityController {
    
    @GetMapping("/entity-redirect")
    public ResponseEntity<Void> entityRedirect() {
        return ResponseEntity.status(HttpStatus.FOUND)
                .location(URI.create("/target-page.html"))
                .build();
    }
    
    @GetMapping("/permanent-redirect")
    public ResponseEntity<Void> permanentRedirect() {
        return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY)
                .location(URI.create("/new-page.html"))
                .build();
    }
}

6. 返回 HTML 重定向脚本

@RestController
public class ScriptRedirectController {
    
    @GetMapping("/script-redirect")
    public String scriptRedirect() {
        return """
            <html>
                <head>
                    <script>
                        window.location.href = '/target-page.html';
                    </script>
                </head>
            </html>
            """;
    }
    
    @GetMapping("/meta-redirect")
    public String metaRedirect(@RequestParam(defaultValue = "3") int delay) {
        return String.format("""
            <html>
                <head>
                    <meta http-equiv="refresh" content="%d;url=/target-page.html">
                    <title>Redirecting...</title>
                </head>
                <body>
                    <p>正在跳转,请稍候...</p>
                </body>
            </html>
            """, delay);
    }
}

7. 使用 RedirectView

@Controller
public class RedirectViewController {
    
    @GetMapping("/redirect-view")
    public RedirectView redirectView() {
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("/target-page.html");
        redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY); // 可选
        return redirectView;
    }
}

8. 带参数的重定向

@Controller
public class RedirectWithParamsController {
    
    @GetMapping("/redirect-with-params")
    public String redirectWithParams(RedirectAttributes redirectAttributes) {
        redirectAttributes.addAttribute("param1", "value1"); // 添加到URL
        redirectAttributes.addFlashAttribute("message", "操作成功!"); // 临时存储,一次有效
        return "redirect:/target-page";
    }
    
    // 目标页面接收参数
    @GetMapping("/target-page")
    public String targetPage(@RequestParam String param1, 
                           Model model,
                           @ModelAttribute("message") String message) {
        model.addAttribute("receivedParam", param1);
        return "target-page";
    }
}

9. 条件跳转

@Controller
public class ConditionalRedirectController {
    
    @GetMapping("/conditional")
    public String conditionalRedirect(@RequestParam String action) {
        switch (action) {
            case "login":
                return "redirect:/login";
            case "home":
                return "redirect:/home";
            case "error":
                return "forward:/error-page";
            default:
                return "index";
        }
    }
    
    @GetMapping("/auth-check")
    public String authCheck(HttpSession session) {
        if (session.getAttribute("user") == null) {
            return "redirect:/login";
        }
        return "dashboard";
    }
}

10. 全局跳转配置

@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    // 配置视图解析器
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
        // 或者使用 Thymeleaf(默认配置)
    }
    
    // 添加静态页面跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addRedirectViewController("/old-url", "/new-url");
        registry.addStatusController("/error", HttpStatus.NOT_FOUND);
    }
}

11. 异常跳转

@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e, Model model) {
        model.addAttribute("error", e.getMessage());
        return "error-page"; // 跳转到错误页面
    }
    
    @ExceptionHandler(UnauthorizedException.class)
    public String handleUnauthorized() {
        return "redirect:/login"; // 未授权跳转到登录页
    }
}

配置文件示例

application.yml

spring:
  mvc:
    view:
      prefix: /templates/
      suffix: .html
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML
    encoding: UTF-8

注意事项

  1. 模板引擎选择
    • Thymeleaf(默认):return "page" 对应 templates/page.html
    • JSP:需要额外配置,返回 return "page" 对应 /WEB-INF/views/page.jsp
    • FreeMarker:return "page" 对应 templates/page.ftl
  2. 路径规则
    • return "page" - 视图解析
    • return "redirect:/url" - 重定向
    • return "forward:/url" - 转发
  3. 静态资源
    • HTML文件放在 static/ 目录下可直接访问
    • 模板文件放在 templates/ 目录下通过控制器访问

根据项目需求选择合适的跳转方式,@Controller + 视图名称是最常用的方案。

Logo

智能硬件社区聚焦AI智能硬件技术生态,汇聚嵌入式AI、物联网硬件开发者,打造交流分享平台,同步全国赛事资讯、开展 OPC 核心人才招募,助力技术落地与开发者成长。

更多推荐