跟我学Spring Boot(三)Spring Boot 的web开发

1、Web开发中至关重要的一部分,Web开发的核心内容主要包括内嵌Servlet容器和SpringMVC

spring boot  提供了spring-boot-starter-web 为web开发提供支持,spring-boot-starter-web为我们提供了嵌入的tomcat以及spring mvc 的依赖。而web相关的自动配置存储在spring-boot-autoconfigure.jar的org.springframework.boot.autoconfigure.web下。如果还想了解其它相关支持可查阅相关资料,这里不在深入讲解。

2、本节将带领大家开始学习使用Thymeleaf模板

  首先先对Thymeleaf模板进行一些简单介绍,Thymeleaf模板是一个java类库,它是一个xml/xhtml/html5的模板引擎,可以作为MVC的Web应用的View层。Spring Boot 提供了大量模板引擎,包括FreeMarker Groovy Thymeleaf Velocity 和Mustache,国为Thymeleaf提供了完美的Spring mvc 的支持,所以我们这里使用Thymeleaf

2.1引入Thymeleaf模板

  下面代码是一个基本的Thymeleaf模板页面,在这里我们引入了BootStrap作为样式控制,和jQuery dom操作。

按前面步骤创建一个spring boot项目、目录结构如下:

  1、 在template目录下新建index.html页面代码如下:

index.html

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
    <link th:src="@{bootstrap/css/bootstrap.min.css}" href="//cdn.bootcss.com/bootstrap/4.0.0-alpha.5/css/bootstrap.css" rel="stylesheet"/>
    <script th:src="@{jquery.min.js}" ></script>
</head>
<body>
<span th:text="${single.name}">${single.name}</span>
</body>
</html>

 2、新一个model包,再创建一个person类

package com.example.model;

/**
 * Created by Administrator on 2016-12-16.
 */
public class Person {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

3、DemoApplication代码如下:

package com.example;

import com.example.model.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;

@Controller //1
@SpringBootApplication
public class DemoApplication {

    //2
    @RequestMapping("/helloboot")
    public String helloBoot(Model model){
        Person single=new Person();
        single.setId(1);
        single.setName("lvxiaolong");
        model.addAttribute("single",single);
        return "index";
    }
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

4、application.properties

server.port=80

启动项目输入:http://localhost/helloboot就可以看到页面输出内容(lvxiaolong)

下载地址:http://download.csdn.net/detail/ttyyadd/9713292

原文地址:https://www.cnblogs.com/lvlv/p/6159806.html