Restful服务

本文通过一个Spring Boot示例详细介绍了如何使用RESTful Web API,并解释了HTTP的四种基本操作:GET、POST、PUT和DELETE分别对应于查询、创建、更新和删除操作。示例展示了如何在Java中实现这些操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Restful Web API应该严格遵守Http的四个操作

            1、GET对应查询操作;

            2、POST对应创建操作;

            3、PUT对应更新操作;

            4、DELETE对应删除操作。

从HttpClient发过来的Request类型只能是上述四种之一。

下面是我做的一个例子,这样可以更快的理解

import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cf.pojo.User;
import com.cf.rest.service.RestService;

@Controller
public class RestController {

	@Autowired
	private RestService restService;
	
	/**
	 * 查询操作 REST风格 : /user/用户id
	 * 
	 */
	@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
	@ResponseBody
	public String get(@PathVariable("id") Long id) {
		User user = restService.selectByPrimaryKey(id);
		String result = JSON.toJSONString(user);
		System.out.println("---------------------------get:" + result);
		
		return result;
	}
	
	/**
	 * 创建操作 REST风格
	 * 
	 */
	@RequestMapping(value = "/user/register", method = RequestMethod.POST)
	@ResponseBody
	public String register(User user) {

		String result = JSON.toJSONString(user);
		System.out.println("---------------------------Post:" + result);
		
		return result;
	}
	
	/**
	 * 删除操作 REST风格
	 * 
	 */
	@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public String delete(@PathVariable("id") Long id) {

		System.out.println("---------------------------delete:" + id);
		
		return "delete";
	}
	
	/**
	 * 更新操作 REST风格
	 * 
	 */
	@RequestMapping(value = "/user/update", method = RequestMethod.PUT)
	@ResponseBody
	public String update(User user) {

		String result = JSON.toJSONString(user);
		System.out.println("---------------------------Put:" + result);
		
		return result;
	}
	
	/**
	 * 传统风格 : /user?name户zhangsan&age=18
	 * 
	 */
	@RequestMapping(value = "/user", method = RequestMethod.GET)
	@ResponseBody
	public String search(@RequestParam("name") String queryString) {
		
		System.out.println("---------------------------get:" + queryString);
		
		return queryString;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值