Springboot集成 thymeleaf+ swagger
一、.模板引擎(thymeleaf)
SpringBoot 推荐使用模板引擎来渲染html,如果你不是历史遗留项目,一定不要使用JSP,常用的模板引擎很多,有freemark,thymeleaf等,其实都大同小异,其中springboot 强烈推荐的是用thymeleaf。
二、pom.xml中添加thymeleaf的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
三、添加工程中相应的文件
3.1新建com.liheng.controller.ThymeleafController.class
@Controller
public class ThymeleafController {
@RequestMapping("/testThymeleaf")
public String testThymeleaf(ModelMap map) {
// 设置属性
map.addAttribute("name", "liheng");
// 对应src/main/resources/templates/testThymeleaf.html
return "testThymeleaf";
}
}
3.2 添加前台页面
Springboot默认的模板配置路径为:src/main/resources/templates
在resources目录里面新建一个templates目录,在目录里面新建testThymeleaf.html文件
testThymeleaf.html文件
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
<meta charset="UTF-8" />
<title>liheng</title>
</head>
<body>
<h1 th:text="${name}"/>
</body>
</html>
运行App.class,在浏览器上输入:localhost:8082/testThymeleaf(我修改了启动端口,默认8080),可以看到页面。
说明thymeleaf已经集成成功。
4 集成Swagger2构建API文档
4.1 Swagger2 的作用
-
随项目自动生成强大RESTful API文档,减少工作量
- API文档与代码整合在一起,便于同步更新API说明
- 页面测试功能来调试每个RESTful API
4.2 添加pom.xml中swagger的依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency> //swagger的界面优化组件
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.6</version>
</dependency>
4.3 创建com.liheng.util.SwaggerConfig.class文件
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.liheng"))// 指定扫描包下面的注解
.paths(PathSelectors.any())
.build();
}
// 创建api的基本信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("集成Swagger2构建RESTful APIs")
.description("集成Swagger2构建RESTful APIs")
.termsOfServiceUrl("http://www.liheng.cn/")
.contact(new Contact("liheng","com.liheng","1137740772@qq.com"))
.version("1.0.0")
.build();
}
}
4.4 创建com.liheng.controller.SwaggerController.class文件测试swagger是否成功
@RestController
@RequestMapping(value="/swagger")
public class SwaggerController {
@ApiOperation(value="获取用户信息", notes="根据id来获取用户详细信息")
@ApiImplicitParam(name="id", value="用户ID", required=true, dataType="String")
@RequestMapping(value="/{id}", method= RequestMethod.GET)
public Map<String,String> getInfo(@PathVariable String id) {
Map<String ,String> map = new HashMap<String, String>();
map.put("name", "liheng");
map.put("age", "18");
return map;
}
}
启动App.class,在浏览器中访问:http://localhost:8082/doc.html
至此:Springboot集成swagger成功。