本人程序媛一枚,近来闲来无事,学习学习springboot,想跟大家分享一下。初学springboot找不到方向各种坑,希望我的文章对初学者有所帮助。
- 首先我自己先创建了一个web项目,但是发现好多依赖包需要下载,果断创建了maven项目。方便了好多。顺便告诉大家可以安装一个springboot插件哦。(可以去官网根据自己使用的eclipse版本下载插件哦,我这里提供一个官方网址 Spring Boot 官网 )。安装完插件需要重启eclipse,可以直接创建spring start project
- 创建 项目后会生成一个主方法类,直接运行main方法,启动springboot项目。
- 下面我写一个简单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