1. 程式人生 > 其它 >1.建立一個hello springboot的web應用

1.建立一個hello springboot的web應用

目標;當地址欄http://localhost:8080/hello時,頁面可以輸出hello springboot
前提:maven使用的是3.3版本以上,jdk在maven配置檔案中指定版本為1.8
    <profile>
         <id>jdk-1.8</id>
         <activation>
              <jdk>1.8</jdk>
              <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
          <maven.compiler.source>1.8</maven.compiler.source>
          <maven.compiler.target>1.8</maven.compiler.target>
          <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
        </properties>
   </profile>
1.建立一個maven應用
2.編寫主類程式:加上@SpringBootApplication標籤來標明該類是springboot的主程式類(程式入口)
    /**
     * springboot的主程式類
     * @SpringBootApplication:這是一個springBoot的應用
     */
    @SpringBootApplication
    public class MainApplication {
        public static void main(String[] args) {
            //啟動程式:傳入該類名和方法入參
            SpringApplication.run(MainApplication.class, args);
        }
    }
3.編寫業務邏輯
    @Controller
    public class HelloController {
        @RequestMapping("/hello")
        @ResponseBody----->加上該標籤,會將string直接返回給瀏覽器,不需要走檢視解析器邏輯
        public String handleHello(){
            return "hello springboot";
        }
    }
    也可以將上面的註解合併為:
        @RestController----->可以將@ResponseBody標籤和@Controller合併為一個標籤:@RestController
        public class HelloController {
            @RequestMapping("/hello")
            public String handleHello(){
                System.out.println("處理hello請求,返回hello springboot!");
                return "hello springboot";
            }
        }
    詳解@RestController標籤:發現其裡面包含了@Controller,@ResponseBody標籤
        @Target({ElementType.TYPE})
        @Retention(RetentionPolicy.RUNTIME)
        @Documented
        @Controller
        @ResponseBody
        public @interface RestController {
            @AliasFor(
                annotation = Controller.class
            )
            String value() default "";
        }
        
4.配置檔案的新增:application.properties
    在配置檔案中可以指定tomcat的預設埠號等等配置:
    

5.在pom.xml新增打包方式,可以將其達成可執行的jar包
    在dependencies下發加上:
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
問題:為什麼jar包卻可以使用tomcat等