1、前言
??原先的页面访问地址为:http://127.0.0.1:8888/office/schdule/index/ , 重构项目,SpringBoot 项目,前后分离,前端文件放置静态目录(static )下,访问地址:http://127.0.0.1:8888/office/schdule/index.html 。可以看出,原先是请求接口进行转发到指定页面的,而现在是直接访问静态文件,为了能兼容原先访问地址,则需对请求进行转发处理。
2、多种方式尝试
2.1 redirect、forward关键字(不是 Java 关键字)
@Controller
public class JumpController extends BaseResultController {
@GetMapping("html/index")
public String forwordIndexHtml() {
return "forword:/schdule/index.html";
}
@GetMapping("html/index")
public String redirectIndexHtml() {
return "redirect:/schdule/index.html";
}
}
注意:需要使用@Controller ,不可使用@RestController 。 @RestController 相当于@Controller 和@ResponseBody 合在一起的作用,如果使用@RestController 注解Controller 层的话,则返回的是return 里面的内容,无法返回到指定的页面,配置的视图解析器InternalResourceViewResolver 也就自然没有作用了。
??然而,上述代码报了Cannot resolve MVC View ‘forword:/schdule/index.html’ 无法解析视图的错误。
2.2 重写 WebMvcConfigurer 接口中的方法
??创建 WebConfig 类实现 WebMvcConfigurer 接口,重写 addViewControllers 方法。如下代码:
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.*;
@SpringBootConfiguration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("html/index").setViewName("schdule/index.html");
}
}
??依然还是报了Cannot resolve MVC View ‘forword:/schdule/index.html’ 无法解析视图的错误。
2.3 引入 thymeleaf
??以上的错误是因为没有使用模板引擎,无法识别静态页面。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
server.servlet.context-path=/office/
server.port=10000
spring.resources.static-locations=classpath:/static/, classpath:/templates/
??值得注意的是,SpringBoot 默认的静态目录是resources 下的 static ,引入thymeleaf 模板引擎后,还是无法识别static 下的文件,只能识别templates 下的文件。因此applicaiton.properties 需配置templates 资源路径地址,如下图index.html 路径: 
??去掉forword redirect 关键字,直接写需跳转的地址。
@Controller
public class JumpController extends BaseResultController {
@GetMapping("html/index")
public String forwordIndexHtml() {
return "schdule/index.html";
}
}
另外,引入了引入thymeleaf 模板引擎后,上述addViewControllers(ViewControllerRegistry registry) 方法也能在 IDEA 中正常跳转到指定地址,但是运行时,却总是报找不到静态文件,无论怎么修改路径都不行。具体原因不明,因此不采用。
3、最终效果
http://127.0.0.1:8888/office/schdule/index/

http://127.0.0.1:8888/office/schdule/index.html

|