SpringBoot Rest風格接口
使用Spring Tool Suite工具選擇Web Starter開發(fā)Rest風格Web項目
使用靜態(tài)頁面html,在resources建立一個static目錄和index.htm靜態(tài)文件,訪問地址http://localhost:8080/index.html
如果想做動態(tài)效果,即請求服務器,訪問后臺應用程序,然后帶著返回數(shù)據(jù)再轉(zhuǎn)向到頁面。SpringBoot可以使用Thymeleaf來做動態(tài)頁面。
在pom.xml??中添加Thymeleaf組件:
<dependency>
??? <groupId>org.springframework.boot</groupId>?
??? <artifactId>spring-boot-starter-thymeleaf</artifactId>?
</dependency>??
Controller控制器若要返回頁面,則不能使用RestController,@RestController注解相當于@ResponseBody + @Controller合在一起的作用,如果只是使用@RestController注解Controller,則Controller中的方法無法返回jsp或者html頁面,配置的視圖解析器InternalResourceViewResolver不起作用,返回的內(nèi)容就是Return里的內(nèi)容。如果需要返回到指定頁面,則需要用@Controller配合視圖解析器InternalResourceViewResolver才行。如果需要返回JSON,XML或自定義mediaType內(nèi)容到頁面,則需要在對應的方法上加上@ResponseBody注解。
@Controller?
public?class?TemplatesController?{??
??? @GetMapping("/templates")?
??? String?test(HttpServletRequest?request)?{
??????? // 向頁面轉(zhuǎn)參數(shù) key和value
? ? ? ? request.setAttribute("key",?"hello?world");?
??????? return?"index";?
??? }???
}???
return "index"表示默認跳轉(zhuǎn)到 templates/index.html? 動態(tài)頁面,templates目錄為spring boot默認配置的動態(tài)頁面路徑。這里注意Springboot中關(guān)于 static 和 templates 兩個默認文件夾的區(qū)別: 默認情況下, 網(wǎng)頁存放于static目錄下, 默認的"/"指向的是~/resouces/static/index.html,如果引入了thymeleaf, 則默認指向的地址為~/resouces/templates/index.html。在引入thymeleaf后, 如果仍需要訪問~/static/index.html, 則可以使用重定向?,?return"redirect:/index.html"。
index.html頁面代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
??? <span th:text="${key}"></span>
</body>
</html>
訪問http://localhost:8080/templates:

SpringBoot properties參數(shù)配置
SpringBoot默認的配置文件是 application.properties,也可以自己定義一個或多個配置文件,spring boot默認會在以下兩個路徑搜索并加載這個文件 src\main\resources 、src\main\resources\config 。application.properties默認為空,其實是SpringBoot都用默認的配置幫我們配好了,所以直接新建一個項目可以不用寫任何配置,需要改動配置時寫 application.properties 配置文件即可。
SpringBoot JdbcTemplate訪問數(shù)據(jù)庫
先在pom.xml添加 jdbc模塊和 mysql的依賴
<dependency>
??? <groupId>org.springframework.boot</groupId>
??? <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
??? <groupId>mysql</groupId>
??? <artifactId>mysql-connector-java</artifactId>
</dependency>
然后在application.properties中設置數(shù)據(jù)庫的參數(shù),springboot可以根據(jù)url可以識別并自動加載mysql驅(qū)動,自動創(chuàng)建數(shù)據(jù)庫實例,自動實現(xiàn)連接池等等。
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
新建一個Dao,用@Repository 注釋類,@Autowired 自動裝配一個JdbcTemplate。寫一個方法
public void test() throws Exception {? ? jdbcTemplate.update("insert into t_user values(15, ?, ?)", "aaa", "bbb");? ? }
這里直接在控制層,也就是上文寫好的TemplatesController 中直接調(diào)用Dao的test方法,注意在controller層不管調(diào)用 service層還是 dao都要通過注入(@Autowired)的方式引入資源,不然會報錯空指針異常。運行Application 訪問http://localhost:8080/templates 觸發(fā)TemplatesController的test方法調(diào)用Dao的test方法,查看數(shù)據(jù)庫,新增一條記錄,測試成功。
