(12)SpringBoot使用Thymeleaf开发web页面
发布日期:2021-06-30 11:08:11 浏览次数:2 分类:技术文章

本文共 2258 字,大约阅读时间需要 7 分钟。

640?wx_fmt=png

   摘要:本文主要讲解SpringBoot使用Thymeleaf开发web页面。

SpringBoot官方不推荐使用JSP来开发WEB,而是推荐使用如下几种模板引擎来开发:

  • Thymeleaf(SpringBoot官方推荐)

  • FreeMarker

  • Velocity

  • Groovy

  • Mustache

前面我们讲过,这里再以Thymeleaf为例,介绍如何和SpringBoot集成,开发web项目。我们这里,因为之前的项目整合了jsp,如果再次整合Thymeleaf比较麻烦,这里直接新建了(所以本文可以独立参考学习),具体步骤如下:

目录:

  • 1.pom.xml引入依赖

  • 2.application.properties配置模板解析的前后缀

  • 3.upload.html创建页面

  • 4.写接口做测试

1.pom.xml引入依赖

       
           
org.springframework.boot
           
spring-boot-starter-thymeleaf
       

2.application.properties配置模板解析的前后缀

server.port=8086 spring.thymeleaf.prefix=classpath:/templates/   spring.thymeleaf.suffix=.html  

配置完之后,当我们接口返回"index"时,会自动解析为

/templates/index.html

3.upload.html创建页面

我们新建springBoot 的web项目时,目录结构中,resources结构如下:

resources

  • static:默认存放css等文件

  • templates:默认存放我们写得页面

我们现在在templates下创建一个文件上传页面:upload.html,里面写上简单的文件上传的代码:

       
   文件上传
   

文件:

   

如果你新建的目录结构没有templates文件夹,自己新建一个就好,前后缀配置对了就可以找到页面进行跳转。

4.写接口做测试

package com.java4all; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; /**  * Author: momo  * Date: 2018/4/11  * Description:Thymeleaf页面测试  */ @Controller @RequestMapping("thymeleaf") public class ThymeleafController {
   /**     * 跳转到文件上传页面     * @return     */    @RequestMapping(value = "upload",method = RequestMethod.GET)    public String upload(){
       return "upload";    }    /**     * 接收文件     * @param file212     * @return     */    @RequestMapping(value = "uploadBlog",method = RequestMethod.POST)    @ResponseBody    public String uploadBlog(MultipartFile file212){
       String originalFilename = file212.getOriginalFilename();        String name = file212.getName();        return "name:"+name+";=====================originalFilename:"+originalFilename;    } }

这个类上我们要用@Controller,如果用@RestController,就会返回json格式。

启动项目,我们访问一下:

http://localhost:8086/thymeleaf/upload

页面如下:

640?wx_fmt=png

选择文件,上传后,页面如下:

640?wx_fmt=png

项目结构如下:

640?wx_fmt=png

↓↓点击
阅读原文
,查看完整源码。
640?wx_fmt=gif

与其相忘江湖,不如点赞关注

本文为  java4all (公众号:java4all)原创

欢迎转载,请注明出处或文末给出二维码

谢谢!

转载地址:https://it4all.blog.csdn.net/article/details/89037702 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:(14)SpringBoot使用AOP
下一篇:(16)SpringBoot整合RabbitMQ

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月14日 02时46分49秒