文章目录
前言
初步了解HTTP协议,掌握B/S之间的 请求Request、服务响应Response和get、put、post等主要概念和技术方法
一、创建项目
▪ 创建spring boot
▪ 选择修改Group、Artifact
▪ 选择Web -> Spring Web
▪ 选择项目保存路径,然后Finish
二、代码编写
演示的功能就是提供一个计数器功能,可以初始化计数器,修改计数器,查询计数器当前值。没有使用数据库,直接用一个单例类来模拟了,项目结构如下:
Count:
package com.res.resource.bean;
public class Count {
private int count;
public int getCount(){
return count;
}
public void setCount(int count){
this.count=count;
}
}
ResourceController:
package com.res.resource.controller;
import com.res.resource.bean.Count;
import com.res.resource.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class ResourceController {
@Autowired
ResourceService resourceService;
@RequestMapping(value = "/me/count", method = RequestMethod.PUT)
@ResponseBody
public void initCount(@RequestBody Count count){
resourceService.initCount(count);
}
@RequestMapping(value = "/me/count", method = RequestMethod.POST)
@ResponseBody
public void modifyCount(@RequestBody Count count){
resourceService.addCount(count);
}
@RequestMapping(value = "/me/count", method = RequestMethod.GET)
@ResponseBody
public Count getCount() {
return resourceService.getCount();
}
}
ResourceManager:
package com.res.resource.manager;
import org.springframework.stereotype.Service;
@Service
public class ResourceManager {
private int count = 0;
private static ResourceManager instance = new ResourceManager();
private ResourceManager(){}
public static ResourceManager getInstance(){
return instance;
}
public synchronized void addCount(int i){
count = count + i;
}
public synchronized void minusCount(int i){
count = count -i;
}
public int getCount(){
return count;
}
public void initCount(int i){
count = i;
}
}
ResourceService:
package com.res.resource.service;
import com.res.resource.bean.Count;
import com.res.resource.manager.ResourceManager;
import org.springframework.stereotype.Service;
@Service
public class ResourceService {
public void addCount(Count count){
if(count !=null){
ResourceManager.getInstance().addCount(count.getCount());
}
}
public void minusCount(Count count){
if(count !=null){
ResourceManager.getInstance().minusCount(count.getCount());
}
}
public Count getCount(){
Count count = new Count();
count.setCount(ResourceManager.getInstance().getCount());
return count;
}
public void initCount(Count count){
if (count != null) {
ResourceManager.getInstance().initCount(count.getCount());
}
}
}
项目成功启动:
三、项目测试
服务提供了三个接口:
URL都是:/me/count 只是分PUT、POST和GET,其中PUT用于初始化,POST用于修改(这里修改是累加),GET用于查询。
下面使用POSTMan进行测试:
查询接口,服务启动,count默认就是0:
初始化:
再次使用查询接口:
修改接口:
修改后查询:
添加一个负数:
再次查询:
到此,使用Postman对我的web的测试完成
参考文章
https://www.cnblogs.com/*zuokan/p/11117294.html