首先来学习如何建立一个项目然后输出hello world!
一、创建一个maven工程
创建好后如图
二、导入spring boot相关的依赖
打开pom.xml,这是一个配置文件
org.springframework.boot
spring-boot-starter-parent
1.5.9.RELEASE
org.springframework.boot
spring-boot-starter-web
三、创建一个主程序
创建一个Java
代码如下
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/***
* @SpringBootApplication 来标注一个主程序类,说明这是一个spring boot应用
*/
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
//Spring 应用启动起来
SpringApplication.run(HelloWorldApplication.class,args);
}
}
再创建一个controller,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";
}
}
controller是用来处理请求的,其中还会用到@ResponseBody和@RequestMapping
@RequestMapping("/hello")是用来接受浏览器发送过来的“hello”请求
下面的hello方法就是响应浏览器的请求,并返回"Hello world",@ResponseBody就是把"Hello world"返回给浏览器
四、测试运行
到HelloWorldApplication主程序里找到Main,点击左侧的绿色三角运行,然后再浏览器里输入http://localhost:8080/hello
出现这个页面就代表顺利完成了。