springboot通过jar发布时,页面资源都是放在src/main/resources目录下
1.一般静态资源放在static文件夹下,如此时直接在浏览器上输入localhost:8080/show.html是可以访问到页面的
2.若此时springboot集成了freemarker、thymeleaf等模板引擎
我这里使用的是freemarker
(1)在application.yml配置文件做一下配置
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true
spring.freemarker.suffix=
spring.freemarker.template-loader-path=classpath:/templates
(2)pom.xml加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
此时若在templates建立hello.html文件,此时在浏览器上输入localhost:8080/hello.html是不可以访问到正常页面的
原因:因为在浏览器上直接输入页面地址时,springboot是将此资源作为静态资源去访问的,而动态页面是需要视图解析器来解析它的。所以必须通过服务器内部进行访问,也就是要走控制器--服务--视图解析器这个流程才行。
那我们想要通过在浏览器上输入动态页面地址就可以访问渲染后的页面,该怎么做呢?
解决方案:可以创建一个动态页面公共控制层
package com.test.test.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class FreeMarkerController
{
@RequestMapping(value = "/freemarker/**")
public String commonController(HttpServletRequest req)
{
String path = "";
// System.out.println("测试" + req.getRequestURL());
String url = req.getRequestURI();
int index = url.indexOf("/freemarker/");
path = url.substring(index + 12);
// System.out.println("测试1" + path);
return path;
}
}
此时在浏览器上输入localhost:8080/freemarker/hello.html,则这个地址会与上面控制层处理器方法所映射的url匹配上,从而达到了控制器--服务--视图解析器这个流程,继而可以访问到渲染后的动态页面