本文讲解如何创建一个springboot的web应用
推荐访问我的个人网站,排版更好看: https://chenmingyu.top/springboot-web/
系列教程: https://chenmingyu.top/tags/springboot/
使用idea生成springboot项目
1,idea 找到 file ->new -> project ->spring Initializr
2,选择next,填项目信息
3,选择next,勾选项目依赖,由于是一个web demo,所以只勾选web
4,选择next,然后finish
那第一个springboot的web应用就创建完了。
在生成的代码中,最要的是在pom.xml中引入的spring-boot-starter-web依赖,启动后默认使用内置的tomcat作为容器。
第一个web应用
目录结构:
- SpringbootHelloworldApplication :项目启动类,建议启动类的包名层次最高,其子类包中的类将自动扫描
- application.properties :配置文件
- pom.xml:由idea自动生成maven相关配置及依赖,这个项目就只引入了spring-boot-starter-web
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.my</groupId>
<artifactId>springboot-helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-helloworld</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
运行启动类:SpringbootHelloworldApplication
@SpringBootApplication
public class SpringbootHelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloworldApplication.class, args);
}
}
springboot的web模块默认使用tomcat容器作为启动容器
看到8080(springboot 默认端口)启动成功,就成功启动了
访问 http://localhost:8080
报404是因为没有找到默认 "/ "的请求地址
接口
/**
* @author: chenmingyu
* @date: 2018/10/21 14:29
* @description:
*/
@RestController
public class HelloController
{
@GetMapping("/")
public String sayHello(){
return "say hello";
}
}
重启项目,访问http://localhost:8080