详解RESTful

Restful风格的API是一种软件架构风格而不是标准,只是提供了一组设计原则和约束条件。他主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

在Restful风格中,用户请求的url使用同一个url,但用请求方式:GET,POST,DELETE,PUT...等方式对请求的处理方法进行区分,这样可以在前后台分离式的开发中使得前端开发人员不会对请求的资源地址产生混淆和检查大量方法名的麻烦,形成一个统一的接口。

在Restful风格中,现有规定如下:

GET(SELECT):从服务器查询,可以在服务器通过请求的参数区分查询方式

POST(CREATE):在服务器新建一个资源,调用insert操作

PUT(UPDATE):在服务器更新资源,调用update操作

PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。目前jdk7未实现,tomcat7也不行。

DELETE(DELETE):从服务器删除资源,调用delete语句


基本介绍完了,我们来写个例子

基于RESTcontroller,实现REST api

GET request to /api/emp/ returns a list of emps

GET request to /api/emp/1 returns the emp with ID 1

POST request to /api/emp/ with a emp object as JSON creates a new emp

PUT request to /api/emp/3 with a emp object as JSON updates the emp with ID 3

DELETE request to /api/emp/4  deletes the emp with ID 4

DELETE request to /api/emp/ deletes all the emps 


上代码

package com.yy.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import com.yy.pojo.CustomErrorType;
import com.yy.pojo.Emp;
import com.yy.service.EmpService;

@Controller
@RequestMapping("/api")
public class RestApiController {

  public static final Logger logger = LoggerFactory.getLogger(RestApiController.class);        //slf4j的日志,可以传参数

  @Autowired
  private EmpService empService;


/*------------------------------------------------ Get All Emps ---------------------------------------------*/
  @RequestMapping(value = "/emp", method = RequestMethod.GET)
  // @ResponseBody       // 因为返回的是ResponseEntity,所以就不用写此标注,如果直接返回List<Emp>,就需要加注解将list转成json
  public ResponseEntity<List<Emp>> listAllEmps() {
    List<Emp> emps = empService.find();
    System.out.println(emps);
    if (emps.isEmpty()) {
      return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    return new ResponseEntity<List<Emp>>(emps, HttpStatus.OK);
  }

/* ------------------------------------------------- Get Single Emp------------------------------------------*/

  @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
  public ResponseEntity<?> getEmp(@PathVariable("id") Integer id) {  //注意T和?号的区别,返回值不能确定时一定要用问号?,T是传入参数不确定的时候
    logger.info("Fetching Emp with id {}", id);   //{}相当于占位符号,id会自动传入到{}里
    Emp emp = empService.find(id);
    if (emp == null) {
      logger.error("Emp with id {} not found.", id);
      return new ResponseEntity(new CustomErrorType("Emp with id " + id  + " not found"), HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Emp>(emp, HttpStatus.OK);
  }

/* --------------------------------------------------  Create a Emp -----------------------------------------------*/
  @RequestMapping(value = "/emp", method = RequestMethod.POST)
  public ResponseEntity<String> createEmp(@RequestBody Emp emp) {  //传进来的数据要是json,则用 @requestBody
  System.out.println("Creating  Emp....");
  //名字存在不能添加
    if (empService.isEmpExist(emp)) {
      return new ResponseEntity(new CustomErrorType("Unable to create." + " A Emp with name " + emp.getEname() + " already exist."), HttpStatus.CONFLICT);
    }
    empService.add(emp);
    return new ResponseEntity<String>(HttpStatus.OK);
  }

/* -------------------------------------------------- Update a Emp ----------------------------------------------------*/
  @RequestMapping(value = "/emp/{id}", method = RequestMethod.PUT)
  public ResponseEntity<?> updateEmp(@PathVariable("id") Integer id, @RequestBody Emp emp) {
    Emp currentEmp = empService.find(id);

    if (currentEmp == null) {
      return new ResponseEntity(new CustomErrorType("Unable to upate. " + "Emp with id " + id + " not found."), HttpStatus.NOT_FOUND);
    }
    currentEmp.setEname(emp.getEname());
    currentEmp.setSal(emp.getSal());
    currentEmp.setHiredate(emp.getHiredate());
    empService.modify(currentEmp);
    return new ResponseEntity<Emp>(currentEmp, HttpStatus.OK);
  }

/* -------------------------------------------------- Delete a Emp----------------------------------------------------*/

  @RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)
  public ResponseEntity<?> deleteEmp(@PathVariable("id") Integer id) {
    Emp emp = empService.find(id);
    if (emp == null) {
      return new ResponseEntity( new CustomErrorType("Unable to delete. Emp with id "+ id + " not found."),HttpStatus.NOT_FOUND);
    }
    empService.remove(id);
    return new ResponseEntity<Emp>(HttpStatus.OK);
  }


/* ------------------------------------------------ Delete All Emps ---------------------------------------------------*/
  @RequestMapping(value = "/emp/", method = RequestMethod.DELETE)
  public ResponseEntity<Emp> deleteAllEmps() {
    // empService.deleteAllEmps();          //删除全部一般不会
    return new ResponseEntity<Emp>(HttpStatus.OK);
  }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值