書接上文,我們搭建好了Spring Boot 項目環境,我們按照“慣例”編寫一個Hello World程序並運行
1.瞭解
例如:http://localhost:8888/hello?name=world
系統運行成功後,我們需要在瀏覽器上輸入我們系統網址路徑來運行系統,
1.1 http:http是一個簡單的請求-響應協議,後面還有https協議,相比http協議更安全,可以自行查找了解
1.2 localhost:是ip地址,如果在本機運行,則默認可使用locaolhost/127.0.0.1作爲ip地址使用,如果後面我們項目部署在服務器上,則需要按照服務器ip或者服務器域名來代替ip,視情況而定
1.3 8888:端口號
1.4 /hello:路由地址/訪問資源路徑
1.5 name=XXX:參數
2.添加依賴
我們需要在pom.xml中添加Spring 提供的模板引擎thymeleaf依賴如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.創建包並編寫HelloController.java文件
在controller包下創建HelloController.java文件,代碼如下
@Controller //主要用於Spring容器識別這是一個前端控制頁面,用於頁面跳轉等
public class HelloController {
@GetMapping("/hello") //如上面提到的路由,
public String hello(@RequestParam(value = "name") String name,//前面提到的傳遞的參數,如name=zhangsan
Model model){
model.addAttribute("name",name); //將瀏覽器傳來的參數設置到model中,用於後端頁面獲取
return "hello"; //默認將跳轉到resources/templets/hello.html頁面
}
}
4.在resources/templets下創建hello.html頁面
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
5.開始運行我們的項目
查看控制檯,沒有報錯且運行成功如下:
6.在瀏覽器中運行打開我們的項目
在瀏覽器中輸入http://localhost:8080/hello?name=Word,回車出現如下頁面,運行成功
後面我們將開啓個人博客創作之旅…