Github地址:
https://github.com/xiandanin/SpringBootSample
相关链接
https://projects.spring.io/spring-boot
https://www.thymeleaf.org
介绍
Spring Boot跟Spring MVC不太一样,Spring MVC建新项目的时候是要配置很多东西的,而Spring Boot讲究的是快速,提供了很多默认配置,所以新建一个项目不需要手动配置任何东西,并且个性化配置也比Spring MVC简单很多。
创建新项目
创建一个新项目,
Maven
输入
GroupId
和ArtifactId
输入项目名称并指定项目存放的路径
引入SpringBoot
打开pom.xml,引入SpringBoot
1 | <parent> |
如果提示是否需要开启自动导入,选择Enable Auto-Import,否则更改了pom.xml不会自动更新
创建Application
创建SampleApplication
,加上注解@SpringBootApplication
,这个类的main方法就会成为整个程序的入口,@EnableAutoConfiguration
开启自动配置,如果有需要,可以通过@ComponentScan
再指定自动扫描的包
1 | package com.springboot.sample; |
创建Controller
- 创建SampleController,并注解
@Controller
,加上访问路径的注解 - 在SampleController内创建一个home方法,在方法上注解
@RequestMapping("/")
,这样就根目录的访问路径注册到这个方法上,当访问http://localhost:8080
的时候,就会执行这个方法 - 这里还注解了
@ResponseBody
,表示输出Hello World!
字符串1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package com.springboot.sample.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SampleController {
/**
* ResponseBody样例
* @return
*/
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
}
运行配置
Run - Run Configurations

+
- Applicaltion
,Main-Class
选择最开始创建的SampleApplication
Spring Boot是不需要发布到外部Tomcat的,所以确定后直接运行即可

测试
运行完成后,在浏览器访问http://localhost:8080
,就可以看到SampleController
的home
方法返回的Hello World!
了

* hymeleaf支持
在Spring Boot中,官方是不推荐使用JSP的,所以我们需要用thymeleaf
模板
引入thymeleaf
pom.xml加入依赖
1 | <!--thymeleaf--> |
创建模板html
在resources
文件夹下创建templates文件夹
,再创建一个index.html

配置访问路径
在之前创建的SampleController
增加了一个index
方法,路径配置到/index
,这里加入一个message
参数传到页面,再return "index"
,这样当访问http://localhost:8080/index
的时候,就会跳转到resources/templates
文件夹下面的index.html
1 | /** |
在模板html获取参数
在index.html
中,用thymeleaf语法获取SampleController
添加的message
参数。
1 | <p th:text="${message}"></p> |
注意还要在html标签上加上命名空间
1 | xmlns:th="http://www.w3.org/1999/xhtml" |
如果你用的是Vue,还需要在script标签上加上
th:inline
1 | <script th:inline="javascript"> |

测试
在浏览器访问http://localhost:8080/index

*导出可执行jar
在pom.xml指定包类型并添加插件
1 | <packaging>jar</packaging> |
1 | <build> |
执行package命令

等待编译成功,会在工程目录的target
文件夹下生成一个jar
运行jar
命令行cd
到target
目录
1 | java -jar sample-1.0.0.jar |
Related Issues not found
Please contact @xiandanin to initialize the comment