上篇Spring boot入门之搭建项目我们搭建了一个基本的Spring boot项目,我们继续在此基础上增加web项目开发常用的技术。
- 1.json 接口开发
- 2.页面渲染之Thymeleaf
- 3.极具野心的WebJars
json接口开发
以前在Spring和SpringMVC中做json的后台接口需要做什么呢?
- 在pom.xml里添加 jackjson 等相关依赖
- 在spring.xml配置controller扫描
- 方法上添加@ResponseBody
由于需要人为的进行各种配置,所以不可避免的导致各种错误,而这些错误也真的是烦透了,spring boot如何做呢,只需要类添加 @RestController 即可,默认类中的所有方法都会以json的格式返回,也就是说这个类就是一个后台接口类了。
@RestController//只需要添加这个注释,返回的结果自动转化为json
public class HelloController {
@RequestMapping("/hello")
public String index() {
return "Hello World";
}
}
页面渲染之Thymeleaf
Spring boot 推荐使用Thymeleaf来代替jsp,那么thymeleaf模板到底是什么呢?Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。
Oranges
0.99
可以看到Thymeleaf由html标签和json值组成,浏览器在解析html时,当检查到没有的属性时候会忽略,所以Thymeleaf的模板可以通过浏览器直接打开展现,这样非常有利于前后端的分离。
接下来我们使用它来写一个小例子,引入下面依赖,
org.springframework.boot
spring-boot-starter-thymeleaf
在默认的模板路径src/main/resources/templates下编写模板文件
Hello Thymeleaf!
Controller层
@Controller
public class HelloController {
@RequestMapping("/hello")
public String index(ModelMap map) {
// 加入一个属性,用来在模板中读取
map.addAttribute("name", "zx");
// return模板文件的名称,对应src/main/resources/templates/hello.html
return "hello";
}
}
启动项目,直接打开html页面展现Hello null,但是访问http://localhost:8080/hello,则会展示Controller中name的值:Hello zx。
thymeleaf常用语法:
//字符串
//条件判断
Login
thymeleaf更多用法请参考官方文档:http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#integrating-thymeleaf-with-spring
极具野心的WebJars
我们在开发Java web项目的时候会使用像Maven,Gradle等构建工具以实现对jar包版本依赖管理,以及项目的自动化管理,但是对于JavaScript,Css等前端资源包,我们只能采用拷贝到webapp下的方式,这样做就无法对这些资源进行依赖管理。
WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件,以对资源进行统一依赖管理。WebJars的jar包部署在Maven中央仓库上。
在thymeleaf中,我们可以看到html代码和数据分离的vue的影子,包括angularjs等前端框架也都有异曲同工之妙,我们再看WebJars对这些的整合
org.webjars.bower
vue
1.0.21
org.webjars
jquery
2.2.4
org.webjars
bootstrap
3.3.6
前端页面引用
很显然,Spring boot把很多前端框架都大包大揽了起来,不仅满足于在后端,野心极大。