要求:浏览器发送hello请求,服务器接受请求并处理,相应hello world字符串。
1.创建一个maven工程(jar)
打开idea首页,点击create new project,然后选择maven,选好相应的jdk,然后next
继续next,填入项目名springboot-01-helloworld,另外选择项目存储位置,点击finish
出现该页面之后记得点击右下角的Enable Auto Import,之后每写入一个依赖idea都会帮我们自动导入。
2.导入springboot的相关依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</parent>
3.编写主程序,启动应用
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//@SpringBootApplication 来标注一个主程序类,说明这是一个Springboot应用
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
//springboot应用启动
SpringApplication.run(MainApplication.class,args);
}
}
4.编写相关的Controller和Service
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "hello world";
}
}
*Application启动类的位置:要将Application类放在最外侧,即包含所有子包 ,spring-boot会自动加载启动类所在包下及其子包下的所有组件。
5.运行主程序,浏览器访问
浏览器网址输入http://localhost:8080/hello访问得到页面
访问成功,以上说明,springboot简单示例成功。
以上过程出现过的一个问题,就是把MainAppilication的位置放错了,导致最后请求无法得到相应,最后改正了位置,就成功了。
错误演示:
运行: