springboot入门篇
1.构建maven环境
1.1 准备pom文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.2 创建启动类
package com.mp.prj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Unit test for simple App.
*/
@SpringBootApplication
public class AppTest
{
public static void main(String[] args) {
SpringApplication.run(AppTest.class,args);
}
}
注解说明:
(1)@SpringBootApplication: springboot提供简化配置,替代@Configuration、@EnableAutoConfiguration、@ComponentScan 这三个注解
(2)用于启动spring boot服务,默认端口为8080
1.3 创建controller
package com.mp.prj;
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;
@RestController
@RequestMapping("/controller01")
public class Controller01 {
@RequestMapping(value = "/print",method = RequestMethod.GET)
public String print(@RequestParam(value = "username") String username){
return "hello : "+username;
}
}
注解说明:
(1)@RestController::其实就是@Controller和@ResponseBody注解加在一起;@RestController 默认都是以json格式返回
(2) @RequestMapping:请求路径;一般我们会在controller类上加一级路径,在具体的请求方法里面加二级路径,这样就可以避免请求路径冲突的问题
(3)@RequestParam:用于从请求参数中获取参数值
(4)return 即页面中显示的内容 ;如果返回为一个具体的对象,则会返回为具体的json
1.4 访问接口
http://localhost:8080/controller01/print?username=xxx
即可以打印数据: hello world: xxx
1.5 样例2
这里我们接口返回的类型为Person对象
package com.mp.prj;
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;
@RestController
@RequestMapping("/controller01")
public class Controller01 {
@RequestMapping(value = "/print",method = RequestMethod.GET)
public Person print(@RequestParam(value = "username") String username,@RequestParam(value = "age") int age){
return new Person(username,age);
}
}
页面请求:
http://localhost:8080/controller01/print?username=zhangsan&age=10
返回内容:
{“username”:“zhangsan”,“age”:10}