Spring Boot中如何将/home.html请求转发至/abc/home.html?
请求转发实现方案
针对你的配置:
server.servlet.context-path=/ spring.mvc.servlet.path=/abc
要实现localhost:8080/home.html到localhost:8080/abc/home.html的转发,可以用以下两种简单方式:
方法一:通过WebMvcConfigurer配置转发规则
创建配置类,利用ViewControllerRegistry添加转发规则:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcForwardConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home.html") .setViewName("forward:/abc/home.html"); } }
方法二:用控制器实现转发
编写一个基础控制器,处理/home.html的GET请求并转发:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeForwardController { @GetMapping("/home.html") public String forwardToHome() { return "forward:/abc/home.html"; } }
两种方式都是通过Spring MVC的内部转发机制,将根路径下的/home.html请求转发到MVC处理路径/abc下的对应资源,不需要额外修改配置文件。
内容的提问来源于stack exchange,提问作者Shashank
相关产品推荐
相关产品推荐

