目录
一、HTTP基础知识
参考这里https://www.jianshu.com/p/9b8b9672b8e6
二、项目代码
1.项目的创建
2.项目内容
通过http不同的请求来进行对数字进行相应的操作。
- 当发出get请求的时候对数字进行初始化为0。
- 当发出post请求的时候对数字进行相加操作。
- 当发出put请求的时候把数字重置为指定值。
3.核心代码
项目结构
负责处理http请求的NumberWeb类
根据不同的请求来执行不同的函数,最后返回执行结果。
package com.example.demo.controller;
import com.example.demo.operation.NumberOperation;
import com.example.demo.service.NumberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class NumberWeb {
@Autowired
/**
* GET请求,页面加载时执行
*/
@ResponseBody
@RequestMapping(value = "/index",method = RequestMethod.GET)
public String init(){
NumberService.init();
return "初始化为: "+NumberService.get();
}
/**
* POST请求,对数字进行运算
* @param n
* @return
*/
@ResponseBody
@RequestMapping(value = "/index",method = RequestMethod.POST)
public String get(int n){
NumberService.add(n);
return "新的数字: "+NumberService.get();
}
/**
* PUT请求,重新设置数字的值
* @param n
* @return
*/
@ResponseBody
@RequestMapping(value = "/index",method = RequestMethod.PUT)
public String set(int n){
NumberService.set(n);
return "新的数字: "+NumberService.get();
}
}
负责对数字进行相关操作的NumberService类
主要负责对调用NumberOperation的对应方法
package com.example.demo.service;
import com.example.demo.operation.NumberOperation;
public class NumberService {
/**
* 把新的数字和原来数字进行相加
* @param n
*/
public static void add(int n){
NumberOperation.getNumberOperation().add(n);
}
/**
* 返回数字
* @return
*/
public static int get(){
return NumberOperation.getNumberOperation().getNumber();
}
/**
* 重新给数字赋值
* @param n
*/
public static void set(int n){
NumberOperation.getNumberOperation().setNumber(n);
}
/**
* 初始化数字
*/
public static void init(){
NumberOperation.getNumberOperation().init();
}
}
操作NumberService的NumberOperation类
主要提供操作数字的相关方法。
package com.example.demo.operation;
public class NumberOperation {
private int number;//数字
private static NumberOperation numberOperation = new NumberOperation();//接口
private NumberOperation(){
}
/**
* 返回接口
* @return
*/
public static NumberOperation getNumberOperation() {
return numberOperation;
}
/**
* 设置新的数字
* @param number
*/
public void setNumber(int number) {
this.number = number;
}
/**
* 返回数字
* @return
*/
public int getNumber() {
return number;
}
/**
* 对数字进行相加
* @param n
*/
public synchronized void add(int n){
this.number+=n;
}
/**
* 初始化数字
*/
public void init(){
this.number=0;
}
}
三、测试
使用postman软件进行模拟请求
1.测试get
当发出get请求的时候,可以看到数字初始化为0。
2.测试post
把请求改为post,同时连续请求两次,参数值分别为5和4。
可以发现每一次请求后n的值都增加了对应的值。
3.测试put
把请求改为put,同时参数改为3可以发现值也变为了3。