创建REST服务,获取、创建、修改、删除资源

package tacos.web.api;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tacos.Order;
import tacos.Taco;
import tacos.data.OrderRepository;
import tacos.data.TacoRepository;

import java.util.Optional;

@RestController//控件器中的所有处理器方法的返回值都要直接写入响应主体中,而不是将值放入模型Model中并传递给视图.
@RequestMapping(path = "/design",produces = {"application/json"})//指定API生成Json数据
@CrossOrigin(origins = "*")//允许跨域访问,允许来自任何域的客户端消费该API
public class DesignTacoApiController {
    private TacoRepository tacoRepo;
    private OrderRepository orderRepo;

//    @Autowired
//    EntityLinks entityLinks;

    public DesignTacoApiController(TacoRepository tacoRepo, OrderRepository orderRepo) {
        this.tacoRepo = tacoRepo;
        this.orderRepo = orderRepo;
    }

    @GetMapping("/recent")
    public Iterable<Taco> recentTacos(){
        PageRequest page=PageRequest.of(0,12, Sort.by("createdAt").descending());
        return tacoRepo.findAll(page).getContent();
    }

    //1.获取资源
    //返回普通Json
    @GetMapping("/{id}")//访问路径:“/design/{id}” 的 GET 请求,
    public Taco tacoById(@PathVariable("id") Long id){
        Optional<Taco> optTaco=tacoRepo.findById(id);
        if(optTaco.isPresent()){
            return optTaco.get();
        }
        return null;
    }

    //利用ResponseEntity<>响应实例将对象包装成带状态的响应
    @GetMapping("/Entity/{id}")//访问路径:“/design/{id}” 的 GET 请求,
    public ResponseEntity<Taco> tacoByIdForEntity(@PathVariable("id") Long id){
        Optional<Taco> optTaco=tacoRepo.findById(id);
        if(optTaco.isPresent()){
            return new ResponseEntity<>(optTaco.get(), HttpStatus.OK);
        }
        return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
    }

    @GetMapping("/order/{id}")
    public Order GetOrder(@PathVariable("id") Long id){
        Optional<Order> optOrder= orderRepo.findById(id);
        if (optOrder.isPresent()){
            return optOrder.get();
        }
        return null;
    }

    //2.创建资源
    @PostMapping(consumes = "application/json")//consumes指定请求输入,该方法只会处理Content-type与application/json相匹配的请求。
    @ResponseStatus(HttpStatus.CREATED)//响应客户端的状态
    public Taco postTaco(@RequestBody Taco taco){
        //@RequestBody注解,请求会将Json转换成Taco对象
        return tacoRepo.save(taco);
    }

    //3.更新资源
    //3.1 全部更新
    @PutMapping("/{orderId}")
    public Order putOrder(@RequestBody Order order){
        return orderRepo.save(order);
    }
    //3.2 部分更新
    @PatchMapping(path = "/{orderId}",consumes = "application/json")
    public Order patchOrder(@PathVariable("orderId") Long orderId,@RequestBody Order patch){
        Order order=orderRepo.findById(orderId).get();
        if(patch.getName()!=null){
            order.setName(patch.getName());
        }
        if(patch.getStreet()!=null){
            order.setStreet(patch.getStreet());
        }
        if (patch.getCity()!=null){
            order.setCity(patch.getCity());
        }
        if ((patch.getState()!=null)){
            order.setState(patch.getState());
        }
        if(patch.getZip()!=null){
            order.setZip(patch.getZip());
        }
        if(patch.getCcNumber()!=null){
            order.setCcNumber(patch.getCcNumber());
        }
        if (patch.getCcCVV()!=null){
            order.setCcNumber(patch.getCcCVV());
        }
        if (patch.getCcExpiration()!=null){
            order.setCcExpiration(patch.getCcExpiration());
        }
        return orderRepo.save(order);

    }

    //4.删除资源
    @DeleteMapping("{orderId")
    @ResponseStatus(code=HttpStatus.NO_CONTENT)
    public void deleteOrder(@PathVariable("orderId") Long orderId) {
        try {
            orderRepo.deleteById(orderId);
        } catch (EmptyResultDataAccessException e) {
        }

    }


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值