1. 程式人生 > >SpringBoot菜鳥教程(一)

SpringBoot菜鳥教程(一)

  本人程式媛一枚,近來閒來無事,學習學習springboot,想跟大家分享一下。初學springboot找不到方向各種坑,希望我的文章對初學者有所幫助。

  1.   首先我自己先建立了一個web專案,但是發現好多依賴包需要下載,果斷建立了maven專案。方便了好多。順便告訴大家可以安裝一個springboot外掛哦。(可以去官網根據自己使用的eclipse版本下載外掛哦,我這裡提供一個官方網址 Spring Boot 官網 )。安裝完外掛需要重啟eclipse,可以直接建立spring start project
  2. 建立 專案後會生成一個主方法類,直接執行main方法,啟動springboot專案。
  3. 下面我寫一個簡單demo來測試     
                                                                                                                                                                               package com.example;

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

    @SpringBootApplication
    @RestController
    public class DemoWebApplication {

        public static void main(String[] args) {
            SpringApplication.run(DemoWebApplication.class, args);
        }
        
        
        @RequestMapping("/hello")
        public String greeting(){
            return "Hello World!";
        }
        
    }

         執行程式:http:localhost:8080/hello

         執行結果:

      4.   springboot 載入靜態資源

            因為springboot繼承了thymeleaf,所以他會預設查詢src/main/resources/templates目錄下面的檔案,但是需要在pom.xml中加入

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

          我寫了一個類HelloController.java

          package com.example;

          import org.springframework.stereotype.Controller;
          import org.springframework.ui.Model;
          import org.springframework.web.bind.annotation.PathVariable;
          import org.springframework.web.bind.annotation.RequestMapping;

          @Controller
          public class HelloController {

         @RequestMapping("/hello/{name}")
         public String hello(@PathVariable("name") String name,Model model){
         model.addAttribute("name", name);
         return "hello";
           }
    
    
        }

        在src/main/resources/templates資料夾下面建hello.html檔案

        <!DOCTYPE html>
        <html xmlns:th="http://www.thymeleaf.org">
        <head>
        <meta charset="UTF-8"/>
        <title>Insert title here</title>
        </head>
        <body>
        <p th:text="'Hello, ' + ${name} + '!'" />
        </body>
        </html>

        執行結果如下:

     5. 最後跟大家說一下在上面我有介紹過執行時直接執行main方法,但是我們部署到伺服器上就很不方便。那就需要把專案打jar包。如打包為:demo.jar

        用docs命令執行  java  -jar  demo.jar