SpringBoot 的概念什么的,这里就不赘述了,官方文档最齐全。
下面开始搭建第一个SpringBoot Web,这里我是使用maven来构建项目的:
1.pom文件引入spring-boot-starter-parent和springboot-web 依赖
<!--这个是必须引入的-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath />
</parent>
引入web依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.在src/main/java 下创建com.controller包,包里创建我们的RestController类(这里的controller相当于struts里面的action):
package com.controller;
import org.springframework.web.bind.annotation.RequestMapping;
// restful 风格的controller类,类里方法返回的都是json格式
@org.springframework.web.bind.annotation.RestController
public class RestController {
@RequestMapping("/hello")
public String helloSprinBoot() {
return "helloSprinBoot";
}
}
3.启动项目的主方法,在src/main/java下创建com.app包,包下创建APP类,如下:
package com.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
// 扫描的包
@ComponentScan(basePackages="com.controller")
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
由于springboot内嵌了tomcat,不用我们再去集成tomcat直接运行这个主方法,项目就跑起来了,非常简单方便!下面来看看效果:
跑起来后控制台如下:
我们来用浏览器访问一下看看效果:
至此就成功搭建了简单的web服务