总结一下过去一段时间学到的知识,spring boot的好处,不用多说,总结一个字,“爽”,其他请各位看官自行百度、Google。
这里是开篇,编写第一个spring boot demo,hello world!
一、开发环境等
1、环境:WIN7 64位
2、IDE: IntelliJ IDEA 2018.1.5
3、JDK:1.8.0_191
4、Maven:3.6.0
二、编码过程
1、用idea新建项目,File->New->Project:
2、弹出窗口选择Spring Initializr,选择自己安装的JDK,点击下一步“Next”:
3、弹出窗口指定自己的Group和Artifact(自行命名),点击下一步“Next”:
4、弹出窗口,指定springboot版本,我这里是2.1.3,选择支持web工程需要的Dependencies,Web->Web,点击下一步“Next”:
5、弹出窗口,指定工程保存地址,点击“OK”,点击“Finish”:
6、新建项目之后,可以查看一下目录结构,自行斟酌,删去不必要的东西,我删掉的是.mvn、mvnw、mvnw.cmd:
7、剩下的文件中,WebdemoApplication.java是项目的启动类,application.properties是配置文件,配置文件可以改成.yml,也可以不改,个人比较喜欢配置:
8、编写hello world,在webdemo目录下新建controller文件,新建HelloWorld.java,添加类注解@RestController,@RequestMapping("/hello"),指定声明web层和映射,添加方法say()方法,并指定返回值和入参,加方法注解@RequestMapping("/say")指定方法访问路径:
package com.cobra.webdemo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: Baron
* @Description:
* @Date: Created in 2019/3/4 18:40
*/
@RestController
@RequestMapping("/hello")
public class HelloWorld {
/**
* hello world demo
* @param word
* @return
*/
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say(@RequestParam("word") String word) {
return "hello,"+ word+" !";
}
}
三、启动:
点击,右上角,启动键
当出现下面的日志输出,说明启动成功:
四、测试
在浏览器中数输入:http://localhost:8080/hello/say?word=world,得到结果,测试成功!
五、补充:
1、@RestController=@Controller+@ResponseBody,返回JSON给前端;
2、@GetMapping("/say")=@RequestMapping(value = "/say",method = RequestMethod.GET);
3、启动springboot程序个人常用的方法:
1)开发工具启动;
2)部署时,先用maven命令打成jar包,然后再用java -jar命令启动。