一、创建基于Spring Boot的web 项目
1、创建一个spring boot项目。
2、点击web,选择Spring Web,Finish。
3、如图新建包和类。
4、四个类中分别写入以下代码。
Count:
package com.example.demo.bean;
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 com.example.demo.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.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 void initCount(int count){
this.count = count;
}
public int getCount(){
return count;
}
public synchronized void addCount(int count){
this.count += count;
}
public synchronized void minusCount(int count){
this.count -= count;
}
}
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){
ResourceManager.getInstance().addCount(count.getCount());
}
public void minusCount(Count count){
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());
}
}
}
5、运行时我一直报错"Web server failed to start. Port 8080 was already in use.",查找原因是端口被占用,解决办法如下:
- 修改端口:https://blog.csdn.net/zhouky1993/article/details/103974598
- 关闭占用端口的进程:https://blog.csdn.net/zhouky1993/article/details/103976320
6、我选择修改端口,然后成功运行。
二、安装Postman 软件,用Postman对web进行测试。
1、打开Postman,新建Wordspaces。
2、点击+,选择Get,url输入http://localhost:8004/me/count,点击Send。
3、选择Post。
4、再次Get查询,输出如下。
三、总结
学习了基于Spring Boot实现RESTful接口。
参考文献
https://www.cnblogs.com/wuyizuokan/p/11117294.html
https://blog.csdn.net/zhouky1993/article/details/103974598