springmvc rest风格化案例
一,什么是RESTful
RESTful(RESTful Web Services)一種架構風格,表述性狀態轉移,它不是一個軟件,也不是一個標準,而是一種思想,不依賴于任何通信協議,但是開發時要成功映射到某協議時也需要遵循其標準,但不包含對通信協議的更改
特征:
1.通過url地址來標識資源,系統中的每個對象或資源都可以通過其url地址來獲取
2.統一接口,顯式地使用HTTP方法,來進行crud(create,update,insert,delete)映射
創建資源使用POST
更新資源使用PUT
檢索資源使用GET
刪除資源使用DELETE
3.資源多重反映.通過url地址訪問的每個資源都可以根據客戶端的規定進行返回,例:JSON,XML
RESTful服務適用web應用中創建服務的API,將資源以JSON或XML等數據格式進行暴露,從而可以更方便的讓客戶端進行調用
二.基于SpringMVC的RESTful服務
在SpringMVC中對RESTful支持,主要通過注解來實現
@Controller:聲明一個處理請求的控制器
@RequestMapping:請求映射地址到對應的方法,該注解又可以分為一下幾種類型:
@GetMapping
@PostMpping
@PutMapping
@DeleteMapping
@PatchMapping
@ResponsrBody:響應內容轉換為JSON格式
@RequestBody:請求內容轉換為JSON格式
@RestContrller:等同@Controller+@ResponsrBody
前臺跳轉代碼參考如下所示:
<%–
Created by IntelliJ IDEA.
User: qyq
Date: 2022/2/21
Time: 19:25
To change this template use File | Settings | File Templates.
–%>
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>
package com.aaa.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Component;
@Data
@AllArgsConstructor
@Component
public class Emp {
private Integer id;
private String name;
}
復制
控制器EmpController參考如下:
package com.aaa.controller;
import com.aaa.entity.Emp;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
@Controller
public class EmpController {
@RequestMapping(value = “/emp”,method = RequestMethod.GET)
public ModelAndView getAllEmps(){
ModelAndView mv=new ModelAndView();
List empList=new ArrayList();
empList.add(new Emp(1,“張三”));
empList.add(new Emp(2,“李四”));
mv.addObject(“emps”,empList);
mv.setViewName(“emplist”);
return mv;
}
@RequestMapping(value = “/emp/{id}”,method = RequestMethod.DELETE)
@ResponseBody
public String deleteEmp(@PathVariable(“id”)Integer id){
System.out.println(“調用service層業務…”);
return “emplist”;
}
@RequestMapping(value = “/emp”,method = RequestMethod.POST)
}
復制
針對PUT和DELETE操作可能會出問題,需要在web.xml中進行配置
總結
以上是生活随笔為你收集整理的springmvc rest风格化案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Maven入门极简使用教程
- 下一篇: spring整合问题集合1