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

(一)、返回视图的例子
  1. 使用thymeleaf模板
    在pom.xml文件中添加依赖
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
  1. 在resources/template目录下创建模板文件books.html
    在这里插入图片描述

  2. 控制层代码

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";
    }
}

  1. 运行效果
    在这里插入图片描述
(二)、返回json数据的例子
  1. 控制层代码
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;
    }


}

  1. 运行效果
    在这里插入图片描述
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐