0
点赞
收藏
分享

微信扫一扫

SpringBoot框架:第二章:SpringBoot中static和templates二个目录下的页面和静态资源访问的三个常见问题


静态页面:

在resources建立一个static目录和index.htm静态文件,访问地址 ​​http://localhost:8080/index.html​​ 

SpringBoot框架:第二章:SpringBoot中static和templates二个目录下的页面和静态资源访问的三个常见问题_html

spring boot项目只有src目录,没有webapp目录,会将静态访问(html/图片等)映射到其自动配置的静态目录,如下

/static

/public

/resources

/META-INF/resources

如果要从后台跳转到静态index.html

@Controller
public class HtmlController {
@GetMapping("/html")
public String html() {
return "/index.html";
}

动态页面:

使用Thymeleaf来做动态页面,在pom.xml  中添加Thymeleaf组件

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

templates目录为spring boot默认配置的动态页面路径

package hello;  

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
public class TemplatesController {

@GetMapping("/templates")
String test(HttpServletRequest request) {
//逻辑处理
request.setAttribute("key", "hello world");
return "/index";
}
}

index.html页面:

<!DOCTYPE html>
<html>
<span th:text="${key}"></span>
</html>

SpringBoot框架:第二章:SpringBoot中static和templates二个目录下的页面和静态资源访问的三个常见问题_html_02

访问地址:​​http://localhost:8080/templates​​

问题来了

第一个是:启动项目之后,不需要进过后台,直接localhost:8080就可以直接访问templates中的index.html页面,不是访问static中的index.html页面,这个要怎么设置?

回答:正常途径应该是用nginx或apach代理服务器做跳转

第二个是:需求是在templates目录下的一个动态页面index.html中有个超链接,访问的是templates中另一个动态页面cat.html页面,而前端人员给的index.html中其中一个超链接是<a href="car.html">car</a>,页面不好改动,但是不改动,这样写访问的是static中的静态页面,要怎么设置才能访问同一templates目录各个动态页面之间的跳转。

回答:动态页面目录不能用静态方式跳转,动态页面跳转,只能通过控制层,但是页面上有许多要跳转动态页面的超链接,写很多个到控制层也不是很好,所以可以使用xml配置:

标签是view-controller
属性:path
属性:view-name

第三个是:访问http://localhost:8080/templates页面之后,页面之后引入了static目录中的css,js等等静态资源,可是页面访问不到static里面的静态资源

回答:如果是访问js,css表态资源,用绝对路径, / 斜杠开头。控制层映射路径也 / 斜杠开头



举报

相关推荐

0 条评论