Restful API
GET http://localhost:8080/api/v1/users 获取用户列表
POST http://localhost:8080/api/v1/users 新增一个用户
GET http://localhost:8080/api/v1/users/{id} 获取某个用户信息
PUT http://localhost:8080/api/v1/users 更新用户信息
DELETE http://localhost:8080/api/v1/users/{id} 删除一个用户
@RequestMapping、@RestController、@Controller、@ResponseBody注解
@RequestMapping:用于标明方法对应的 HTTP 请求路由的关系映射
@RestController:该注解结合了 @Controller 和 @ResponseBody 的功能
@Controller:职责是使控制层可以处理 HTTP 请求
@ResponseBody:当返回的数据不是HTML标签的页面,而是其他某种格式的数据时(如JSON、XML等)使用它
ps:个人觉得可以这么理解@RestController = @Controller+@ResponseBody
(一)、返回视图的例子
- 使用thymeleaf模板
在pom.xml文件中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
-
在resources/template目录下创建模板文件books.html
-
控制层代码
package com.cax.SpringBootDemo.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/api")
public class HelloController {
@GetMapping("/books")
public String getAll(){
return "books";
}
}
- 运行效果
(二)、返回json数据的例子
- 控制层代码
package com.cax.SpringBootDemo.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@Controller
//与@Controller二者选一
//@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/books")
//当使用@Controller时开启
@ResponseBody
public Object getAll(){
Map<String,Object> map = new HashMap<>();
map.put("name","cax");
map.put("bookname","SpringBoot教程");
return map;
}
}
- 运行效果