springmvc rest风格化案例
一,什么是RESTful
RESTful(RESTful Web Services)一種架構(gòu)風(fēng)格,表述性狀態(tài)轉(zhuǎn)移,它不是一個軟件,也不是一個標準,而是一種思想,不依賴于任何通信協(xié)議,但是開發(fā)時要成功映射到某協(xié)議時也需要遵循其標準,但不包含對通信協(xié)議的更改
特征:
1.通過url地址來標識資源,系統(tǒng)中的每個對象或資源都可以通過其url地址來獲取
2.統(tǒng)一接口,顯式地使用HTTP方法,來進行crud(create,update,insert,delete)映射
創(chuàng)建資源使用POST
更新資源使用PUT
檢索資源使用GET
刪除資源使用DELETE
3.資源多重反映.通過url地址訪問的每個資源都可以根據(jù)客戶端的規(guī)定進行返回,例:JSON,XML
RESTful服務(wù)適用web應(yīng)用中創(chuàng)建服務(wù)的API,將資源以JSON或XML等數(shù)據(jù)格式進行暴露,從而可以更方便的讓客戶端進行調(diào)用
二.基于SpringMVC的RESTful服務(wù)
在SpringMVC中對RESTful支持,主要通過注解來實現(xiàn)
@Controller:聲明一個處理請求的控制器
@RequestMapping:請求映射地址到對應(yīng)的方法,該注解又可以分為一下幾種類型:
@GetMapping
@PostMpping
@PutMapping
@DeleteMapping
@PatchMapping
@ResponsrBody:響應(yīng)內(nèi)容轉(zhuǎn)換為JSON格式
@RequestBody:請求內(nèi)容轉(zhuǎn)換為JSON格式
@RestContrller:等同@Controller+@ResponsrBody
前臺跳轉(zhuǎn)代碼參考如下所示:
<%–
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;
}
復(fù)制
控制器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(“調(diào)用service層業(yè)務(wù)…”);
return “emplist”;
}
@RequestMapping(value = “/emp”,method = RequestMethod.POST)
}
復(fù)制
針對PUT和DELETE操作可能會出問題,需要在web.xml中進行配置
總結(jié)
以上是生活随笔為你收集整理的springmvc rest风格化案例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Maven入门极简使用教程
- 下一篇: liferay spring mvc 案