在springboot集成前端页面的thymleaf方法

在springboot集成前端页面的thymleaf方法

有时候想验证自己的某些想法时需要写一些前端界面,但是又不想写vue那么重的框架。
怎么办,采用thymleaf呀!
放在springboot下面的的static下面的文件是可以直接访问的
例如:目录结构
在springboot集成前端页面的thymleaf方法_第1张图片
这里的resources/static/index/css/GL.css
这种static下的静态文件,要访问GL.cc的话只需要http://localhost:10000/index/css/GL.css
就可以了。

如果访问templates下的文件就要用thymleaf
在springboot集成前端页面的thymleaf方法_第2张图片
第一步导包:

  <!--模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--thymeleaf 不重启刷新页面 工具-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <!-- optional=true,依赖不会传递,该项目依赖devtools;
			之后依赖boot项目的项目如果想要使用devtools,需要重新引入 -->
<!--            true-->
        </dependency>

此时可以直接通过ip+端口访问到templates下的index.html
例如:localhost:10000 就可以访问到index.html
如果要通过代码访问就要配置controller,比如要传参数或者不叫index.html就必须通过视图解析器。

  /**
     * 要往前端带数据就放进Model对象里面
     * @param model
     * @return
     */
    @GetMapping({"/","/index.html"})
    public String IndexPage(Model model){
        //todo 查询所有一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        /**
         * 在yml里面可配置前缀和后缀。不配就有默认的
         * 前缀:classpath:/templates/
         * 后缀:.html
         */
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

这样就可以访问到templates 下的index.html
这里的templates和.html是默认的也可以根据自己需要去yml里配置。index是 返回的。
这里返回给前端页面的参数绑定方法是通过Model。

东西虽小,积跬步至千里,积小流成江海

你可能感兴趣的:(java)