1. 程式人生 > >Spring Boot簡單入門(一)

Spring Boot簡單入門(一)

上個月第一次接觸了Spring Boot,當時摸索了一下便上手寫程式碼了,雖然沒什麼問題,但是沒什麼比自己從頭搭建一個更能瞭解其原理的了,於是今天自己根據網上的教程親手搭了一遍,踩了一些不該踩的坑,浪費了很多時間,特此記錄,寫上一個簡單的登入例項,方便後來的初學者。(登入例項在下篇詳細展示)

先宣告一下環境,jdk為1.8,用MyEclipse2017開發,資料庫採用mysql。

1.構建專案

訪問   https://start.spring.io/

 點選紅圈中的字,選擇如下選項:

 選好後點擊Generate Project按鈕下載專案,下載後解壓,然後匯入到MyEclipse中:

 2.匯入後在pom檔案中引入SpringBoot相關依賴,引入thymeleaf支援html

<dependency>
    <groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 3.在resources下的templates新建index.html:

<!DOCTYPE html>
<html>
  <head>
    <title>主頁</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3"/>
    <meta name="description" content="this is my page"/>
    <meta name="content-type" content="text/html; charset=UTF-8"/>
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <h3>Hello World!</h3>
  </body>
</html>

4.然後在com.example包新建controller包,新建UserController類

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@RequestMapping("/index")
	public String index(){
		return "index";
	}
	
}

5.最後,啟動Application,因為Spring Boot自帶tomcat,所以啟動Application就算啟動服務了。另外注意一點,Application這個類要放在所有子包的最外面,也就是本例中的com.example包裡。

啟動完成後,在瀏覽器輸入http://localhost:8080/user/index就能訪問到剛剛建立的html頁面啦。