Spring Boot html和template(四)

静态页面

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

    /static

    /public  

    /resources

    /META-INF/resources

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

动态页面

  动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问jsp,spring boot建议不要使用jsp,默认使用Thymeleaf来做动态页面。

  在pom.xml中添加Thymeleaf组件

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

  TemplatesController.java

@Controller //返回的是页面所以用简单的controller
public class TemplatesController {
    @GetMapping("/templates")
    String test(HttpServletRequest request){
        request.setAttribute("key","hello world");
        //跳转到templates/index.html动态页面,templates目录是spring boot 默认配置的动态页面路径
        return "index";
    }
}

  templates/index.html

<html xmlns:th="http://www.w3.org/1999/xhtml">
<span th:text="${key}"></span>
</html>

  访问localhost:8080/templates 

这是一个最基本的像页面传递参数,templates标签和jsp标签一样,也可以实现条件判断,循环等各种功能,建议使用静态html+rest代替动态页面。

猜你喜欢

转载自www.cnblogs.com/baidawei/p/9101281.html