一、HTTP基础
概念:
HTTP是应用层协议,同其他应用层协议一样,是为了实现某一类具体应用的协议,并由某一运行在用户空间的应用程序来实现其功能。HTTP是一种协议规范,这种规范记录在文档上,为真正通过HTTP进行通信的HTTP的实现程序。
HTTP是基于B/S架构进行通信的,而HTTP的服务器端实现程序有httpd、nginx等,其客户端的实现程序主要是Web浏览器,例如Firefox、Internet Explorer、Google Chrome、Safari、Opera等,此外,客户端的命令行工具还有elink、curl等。Web服务是基于TCP的,因此为了能够随时响应客户端的请求,Web服务器需要监听在80/TCP端口。这样客户端浏览器和Web服务器之间就可以通过HTTP进行通信了。
二、创建项目
1.创建一个springboot项目
2.选择spring web
.3.编写
Count:
package com.example.demo.been;
public class Count {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
ResourceController:
package com.example.demo.controller;
import com.example.demo.bean.Count;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.demo.service.ResourceService;
@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();
}
}
ResourceService:
package com.example.demo.service;
import com.example.demo.bean.Count;
import com.example.demo.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());
}
}
}
ResourceManager:
package com.example.demo.manager;
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;
}
}
4.运行
测试
参考文献:【SpringBoot】使用IDEA创建一个SpringBoot服务,并创建三个restful风格的接口 - 微弦 - 博客园 (cnblogs.com)