1. 程式人生 > >SpringBoot入門系列:第二篇 再學Hello World

SpringBoot入門系列:第二篇 再學Hello World

Spring-Boot是Spring的新東東,為了讓人儘快的使用,它提供了一個非常好的輔助工具,直接為我們生成Maven架構的工程。下面,我們通過helloworld看

一、在瀏覽器中開啟http://start.spring.io/,如圖

Artifact中輸入spring-boot-sample-helloworld,點選“Switch to the full version.”,勾選"web",然後點選“ Generate Project alt +”按鈕,把檔案儲存到本地某個位置

二、下載檔案匯入eclips

1、解壓下載的檔案到某個資料夾;

2、在eclips中匯入工程file->import->Import Existing Maven Projects-->Select Maven projects-->finish

3、在eclips中執行工程,正確則入圖

三、新增HelloController

1、在包com.example中點選右鍵,選擇new->class,再在Name中輸入HelloController,入下圖

在上圖中點選"Finish"

2、在類上面條件宣告@RestController

3、增加方法

@RequestMapping("/")
	public String helloworld(){
		return "Hello world!";
	}
	
	@RequestMapping("/hello/{name}")
	public String hellName(@PathVariable String Name){
		return "Hello "+Name;
	}

4、儲存Ctrl+S

5、自動新增引用 Ctrl+SHift+O

6、整個HelloController檔案如下

package com.example;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	@RequestMapping("/")
	public String helloworld(){
		return "Hello world!";
	}
	
	@RequestMapping("/hello/{name}")
	public String hellName(@PathVariable String name){
		return "Hello "+name;
	}
}
7、啟動測試

在瀏覽器中依次輸入

http://localhost:8080/

http://localhost:8080/hello/上帝