1. 自定义状态枚举
package hello;
public enum TestEnum {
YET_OPEN(1,"待营业"),OPEN(2,"营业中"),CLOSE(3,"已关闭");
private Integer status;
private String description;
TestEnum(Integer status, String description) {
this.status = status;
this.description = description;
}
public Integer getStatus() {
return status;
}
public String getDescription() {
return description;
}
/**
* 状态码是否合规
* @param status
* @return
*/
public static boolean isCorrectStatus(int status) {
boolean isPass = false;
for (int i = 0; i < TestEnum.values().length; i++) {
if (status == TestEnum.values()[i].status) {
isPass = true;
}
}
return isPass;
}
public static void main(String[] args) {
System.out.println("testEnum.main");
System.out.println(TestEnum.YET_OPEN.getStatus());
System.out.println(TestEnum.OPEN.getDescription());
}
}
2. 测试demo:
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController1 {
@RequestMapping("/")
public String index(Integer status) {
if (!TestEnum.isCorrectStatus(status)) {
System.out.println("错误的状态码");
}
return "Greetings from Spring Boot!";
}
}
3. 状态码合规性测试结果:
因为这边定义的状态码是:1,2,3,所以当我在postman中输入localhost:8088?status=7,即status=7不合规的状态码时,将会打印错误信息到控制台,测试结果打印如下截图: