跟着官網學spring—快速入門指南


這是跟着官網學習Spring的第一篇博客,後續會繼續更新。喜歡的話就多多點贊評論關注!

開始一個新的Spring Boot項目

使用 快速開始創建一個”web“項目,如下圖所示:

  • 需要注意的是需要在依賴關係中添加web依賴關係

  • 完成屬於自己的個性化配置後,點擊生成

  • 解壓後,用idea打開,就完成了Spring boot的創建。

    idea打開後效果圖如下圖所示:

開始編寫屬於自己的代碼

​ 在Application.java文件中添加如下代碼:

package com.zhonghu.springhelloworlddemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class SpringHelloworldDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringHelloworldDemoApplication.class, args);
	}

	@GetMapping("/hello")
	public String hellotest(@RequestParam(value = "name",defaultValue = "World")String name){
		return String.format("Hello %s!",name);
	}
}

  • @RequestParam:告訴Spring在請求中期望的一個值,如果不存在,使用後面的默認值。
  • @RestController:此註解告訴Spring,這個代碼描述應該可在網上的端點。
  • @GetMapping("/hello"):告訴Spring我們用hellotest方法來響應/hello

驗證效果

​ 啓動剛纔寫的代碼:

因爲Spring Boot中集成了諸如tomcat的工具,所以直接啓動,訪問剛纔的頁面:http://localhost:8080/hello,將會看到下面的界面:

​ 顯示Hello World!是因爲我們沒有給後端代碼返回一個參數,導致其使用默認值World,然後打印在界面中。

​ 相應的我們要是想從前端將名稱傳入到後端並且顯示出來,只需要在剛纔的鏈接後面拼接諸如:?name=zhonghu

​ 相應的zhonghu可以換成自己的名字甚至是漢字都可以將其顯示出來

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章