SpringBoot学习8.0-创建REST风格站点

17 篇文章 0 订阅
10 篇文章 0 订阅

1.REST风格

REST即表述性状态传递(英文:Representational State Transfer,简称REST)。

REST是一种约定风格,不是标准。

REST风格被推荐为微服务之间的交互方式。

2.http动作

  • GET:查询
  • POST:新增
  • PUT:修改所有属性
  • PATCH:修改部分属性
  • DELETE:删除

3.springmvc整合rest风格

3.1.@RestController标注类,默认所有方法请求结果默认转换为json。

3.2.用以下注解相应http动作:

  • @GetMapping:GET
  • @PostMapping:POST
  • @PutMapping:PUT
  • @PatchMapping:PATCH
  • @DeleteMapping:DELETE

3.3.传递参数 

可以使用json传递参数。

也可以使用url传递参数:参考SpringBoot学习5.4-SpringMVC-控制器获取参数 中2.4.url传递参数 

代码实例

package com.zyf.serviceuser.user;
import java.util.Arrays;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**rest风格站点*/
@RestController // 请求结果默认转换为json
@RequestMapping("/userRestController")
public class UserRestController {

	@PostMapping("/user")
	@ResponseStatus(HttpStatus.CREATED) // 配置制定的响应码
	public User insert(@RequestBody User user) {
		// 省略insert过程
		return user;
	}

	// consumes限定请求类型。produces限定返回类型。
	@GetMapping(value = "/user/{id}", consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public ResponseEntity<User> getUser2(@PathVariable int id) {
		// 省略主键查询过程
		System.out.println("用户id=" + id);
		User user = new User(1, "李四", 1, "rest风格获取用户");
		HttpHeaders headers = new HttpHeaders();
		headers.add("issuccess", "true");// 设置响应头
		// ResponseEntity 封装错误消息和状态码
		return new ResponseEntity<User>(user, headers, HttpStatus.OK);
	}

	@GetMapping("/user/{id}/{name}")
	public List<User> getUsers(@PathVariable int id, @PathVariable String name) {
		// 省略条件查询过程
		User[] users = { new User(1, "吉姆格林", 1, "rest风格,更新部分属性") };
		return Arrays.asList(users);
	}

	@PutMapping("/user/{id}") // 更新全部属性
	public User update(@PathVariable int id, @RequestBody User user) {
		// 省略更新过程
		user.setName("李雷");
		return user;
	}

	@PatchMapping("/user/{id}/{name}/{note}") // 更新部分属性
	public User update(@PathVariable int id, @PathVariable String name, @PathVariable String note) {
		// 省略更新过程
		return new User(1, "吉姆格林", 1, "rest风格,更新部分属性");
	}

	// delete、getUser及update的参数完全一样,但是http的动作类型不同,所以能够成功调用
	@DeleteMapping("/user/{id}")
	public User delete(@PathVariable int id) {
		// 省略更新过程
		return new User(1, "吉姆格林", 1, "rest风格,删除");
	}
}

js发起请求举例:

$(function() {
	var user = {
		id : 15,
		name : 'zhangsan',
		note : 'rest风格mvc',
		sex : 2
	};
	$("#insert").click(function() {
		$.post({
			url : "/user",
			type : 'POST',
			// 此处需要告知传递参数类型为JSON,不能缺少
			contentType : "application/json",
			// 将JSON转化为字符串传递
			data : JSON.stringify(user),
			// 成功后的方法
			success : function(result,status,jqXHR) {
				var sta = jqXHR.status;// 获取HttpStatus
				if (result != null) {
					alert(JSON.stringify(result));
				}
			}
		});
	});
	
	$("#getUser").click(function() {
		$.post({
			url : "/user/1",
			type : 'GET',
			success : function(result,status,jqXHR) {
				var issuccess = jqXHR.getResponseHeader("issuccess"); //获取响应头数据
				var sta = jqXHR.status;// 获取HttpStatus
				if (result != null) {
					alert(JSON.stringify(result));
				}
			}
		});
	});
	
	$("#getUsers").click(function() {
		$.get({
			url : "/user/1/zhang",
			type : 'GET',
			success : function(result) {
				if (result != null) {
					alert(JSON.stringify(result));
				}
			}
		});
	});
	
	var user2 = {
		id : 15,
		name : 'zhangsan',
		note : 'rest风格更新put',
		sex : 2
	};
	$("#update").click(function() {
		$.ajax({
			url : "/user/1",
			type : 'PUT',
			// 此处需要告知传递参数类型为JSON,不能缺少
			contentType : "application/json",
			// 将JSON转化为字符串传递
			data : JSON.stringify(user2),
			// 成功后的方法
			success : function(result) {
				if (result != null) {
					alert(JSON.stringify(result));
				}
			}
		});
	});
	
	$("#updatepatch").click(function() {
		$.ajax({
			url : "/user/1/zhang/部分更新",
			type : "PATCH",
			success : function(result) {
				if (result != null) {
					alert(JSON.stringify(result));
				}
			}
		});
	});
	
	$("#delete").click(function() {
		$.ajax({
			url : "/user/1",
			type : "DELETE",
			success : function(result) {
				if (result != null) {
					alert(JSON.stringify(result));
				}
			}
		});
	});
});

RestTemplate访问rest风格后端请见:SpringBoot学习8.1-RestTemplate请求rest风格后端

github:https://github.com/zhangyangfei/spring-cloud-learn.git 中的cloud-parent工程。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值