Spring Boot(四)Spring Boot的web项目开发

关注公众号【程序职场】,专注于 Spring Boot+微服务,小程序,flutter,Android,定期文章和视频教程分享,以及 职场规划,运营管理 等,关注后回复   Java资料 ,领取为你精心准备的 学习 干货!

大家好,我是“追梦蜗牛”,大家可以在公众号后台回复 “Java资料”获得技能提升的资料,绝对是干货。

本文是Spring Boot系列的第四篇,了解前面的文章有助于更好的理解本文:


1.Spring Boot(一)初识Spring Boot框架
2.Spring Boot(二)Spring Boot基本配置
3.Spring Boot(三)Spring Boot自动配置的原理


前言

(一). Thymeleaf 模板引

(二). Spring MVC集成Thymeleaf 

(三). Spring Boot中模板引擎Thymeleaf 的使用

Web开发是开发中很重要的,目前BS架构的开发占主流,Web开发的核心内容主要是 内嵌Servlet容器和SpringMVC

(一). Thymeleaf 模板引擎

Spring Boot提供了spring-boot-starter-web为web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及Spring MVC的依赖。

Web相关的自动配置存储在 spring-boot-autoconfigure.jar的org.springframework.boot.autoconfigure.web 包下,大家可以自行看源码学习一下。

SpringBoot的强大之处是提供了大量的模板引擎,其中包括:FreeMarker,Groovy,Thymeleaf,Velocity和Mustache等,SpringBoot中推荐使用Thymeleaf作为模板引擎,我也强烈推荐,简单,完美,并且Thymeleaf提供了完美的Spring MVC的支持。

那么什么是Thymeleaf呢?

Thymeleaf是一个Java类库,他是一个xml/xhtml/html5的模板引擎,可以作为MVC的 WEB应用的view层,还提供了了额外的模板和Spring mvc集成,所以这样可以完全替代了之前的jsp。

更多的Thymeleaf 知识,可以查看官网(http://www.thymeleaf.org)

(二). Spring MVC集成Thymeleaf

上面我们说到 Thymeleaf提供了完美的Spring MVC的支持,那么怎么集成Thymeleaf 的呢?

在SpringMVC中如果我们集成一个模板引擎需要定义ViewResolver而ViewResolver需要定义一个view,例如给jsp定义ViewResolver的代码如下:

@Beanpublic InternalResourceViewResolver viewResolver(){InternalResourceViewResolver viewResolver = new InternalResourceViewResolver ();viewResolver.setPrefix("/WEB-INF/classes/views/");viewResolver.setSuffix(".jsp");viewResolver.setViewClass(JstView.class);return viewResolver;}


上面代码可以看出使用了JsltView定义了一个InternalResourceViewResolver 因而使用Thymeleaf作为模板引擎也需要做雷士的操作。针对这点,Thymeleaf已经为我们定义好了 org.thymeleaf.spring4.view.ThymeleafView和org.thymeleaf.spring4.view.ThymeleafViewResolver(默认使用ThymeleafView作为View),并且Thymeleaf还提供了了模板类和通用的模板引擎(包括:前缀和后缀等)

代码如下:

@Beanpublic TemplateResolver templateResolver(){TemplateResolver templateResolver = new ServletContextTemplateResolver();templateResolver.setPrefix("/WEB-INF/templates");templateResolver.setSuffix(".html");templateResolver.setTemplateMode("HTML5");return templateResolver;}
@Beanpublic SpringTemplateEngine templateEngine(){SpringTemplateEngine templateEngine = new SpringTemplateEngine();templateEngine.setTemplateResolver(templateResolver());return templateEngine;}
@Beanpublic TemplateViewResolver templateViewResolver(){TemplateViewResolver templateViewResolver = new TemplateViewResolver();templateViewResolver.setTemplateEngine(templateEngine());templateViewResolver.setViewClass(TemplateView.class);return templateViewResolver;}

ok ,这样完成了Thymeleaf和SpringMVC的集成了,看起来也不难,但是还有更简单的。

(三). Spring Boot中模板引擎Thymeleaf 的使用

Thymeleaf和SpringMVC的集成,目的是为了大家理解 Thymeleaf和SpringMVC的集成的原理,然后和Spring Boot 集成 做对比。

看到上面的配置和代码添加 在Spring Boot中是不需要的,Spring Boot通过org.springframeword.boot.autoconfigure.thymeleaf包对Thymeleaf进行了自动配置,配置信息在ThymeleafAutoConfiguration中。

通过ThymeleafProperties来配置Thymeleaf,我们可以看一下ThymeleafPropreties的主要源码:
 

@ConfigurationProperties("spring.thymeleaf")public class ThymeleafProperties {    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");    public static final String DEFAULT_PREFIX = "classpath:/templates/";    public static final String DEFAULT_SUFFIX = ".html";    private boolean checkTemplate = true;    private boolean checkTemplateLocation = true;    /**    前缀设置 Springboot默认模板,放置在classpath:/templates/目录下    **/    private String prefix = "classpath:/templates/";    //后缀设置,默认是html    private String suffix = ".html";    //模板模式设置,默认为HTML5    private String mode = "HTML5";     //模板编码设置,默认为UTF-8    private String encoding = "UTF-8";    ......}

好了,下面我们通过一个实例实现springboot的集成。

1. 新建项目
 

创建项目的时候 需要 选择 Thymeleaf作为依赖,这样 spring-boot-starter-thymeleaf会自动包含spring-boot-starter-web。

2. 创建JavaBean

此类用来从后台传递数据给模板页面 展示数据。

public class Person {    private String name;    private Integer age;
    public Person() {        super();    }
    public Person(String name, Integer age) {        super();        this.name = name;        this.age = age;    }
    public String getName() {        return name;    }
    public void setName(String name) {        this.name = name;    }
    public Integer getAge() {        return age;    }
    public void setAge(Integer age) {        this.age = age;    }}

3.脚本静态文件

这里我们需要用到两个前端库,Bootstrap(https://v3.bootcss.com/getting-started/#download)和jQuery (https://jquery.com/download/)

可以通过上面的路径 到官网下载,根据原则,这些脚本样式和图片需要放在 src/mian/resources/static下面。

4. 前端展示界面

页面我们应该放在src/mian/resources/templates下面,新建一个文件index.html

代码如下:

<html lang="en" xmlns:th="http://www.thymeleaf.org"><head>    <meta charset="UTF-8" />    <title>SpringBoot_4</title>    <link th:href="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet" />    <link th:href="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet" /></head><body><div class="panel panel-primary">    <div class="panel-heading">        <h3 class="panel-title">访问Model</h3>    </div>    <div class="panel-body">        <span th:text="${singlePerson.name}"></span>    </div></div><div th:if="${not #lists.isEmpty(people)}">    <div class="panel panel-primary">        <div class="panel-heading">            <h3 class="panel-title">列表</h3>        </div>        <div class="panel-body">            <ul class="list-group">                <li class="list-group-item" th:each="person:${people}">                    <span th:text="${person.name}"></span>                    <span th:text="${person.age}"></span>                    <button class="btn" th:onclick="getName([[${person.name}]]);">获得名字</button>                </li>            </ul>        </div>    </div></div><script th:src="@{jquery-3.1.1.js}" type="text/javascript"></script><script th:src="@{bootstrap/js/bootstrap.min.js}" type="text/javascript"></script><script th:inline="javascript">    var single = [[${singlePerson}]];    console.log(single.name+"/"+single.age);    function getName(name) {        console.log(name);    }</script></body></html>

5.数据构造

package org.cxzc.myyoung.springboot_4;import org.cxzc.myyoung.springboot_4.bean.Person;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import java.util.ArrayList;import java.util.List;@Controller@SpringBootApplicationpublic class Springboot4Application {
    public static void main(String[] args) {        SpringApplication.run(Springboot4Application.class, args);    }
    @RequestMapping("/")    public String index(Model model) {        Person single = new Person("公众号   程序职场", 11);        List<Person> people = new ArrayList<Person>();        Person p1 = new Person("刘德华", 60);        Person p2 = new Person("张学友", 58);        Person p3 = new Person("吴奇隆", 55);        people.add(p1);        people.add(p2);        people.add(p3);        model.addAttribute("singlePerson", single);        model.addAttribute("people", people);        return "index";    }}

在入口类中添加代码,由后台向前台页面返回两种数据,一个单个的Person对象,还有一个people对象是一个List集合,集合中放了3个Person对象,我们要直接将这两条数据在html页面上显示出来

上面代码 主要是 返回给前台页面两个对象,一个singlePerson,一个people。

6.运行项目

访问页面,浏览器输入

点击获取名字 可以获取对应的名字信息。

ok,Spring Boot的web项目开发 到这里就完成了web的效果,如果小伙伴还有疑问,可以 公众号 加群,我们一起进步

本案例下载地址:

https://github.com/ProceduralZC/itcxzc/tree/master/springboot_4

关注公众号【程序职场】,专注于 Spring Boot+微服务,小程序,flutter,Android,定期文章和视频教程分享,以及 职场规划,运营管理 等,关注后回复   Java资料 ,领取为你精心准备的 学习 干货!

发布了55 篇原创文章 · 获赞 101 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/jianpengxuexikaifa/article/details/103024010