spring boot 菜鸟教程

2025-11-04 11:45:45

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@RestControllerpublic 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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢