|
@@ -0,0 +1,57 @@
|
|
|
+package com.zhentao.controller;
|
|
|
+
|
|
|
+import com.zhentao.pojo.Api;
|
|
|
+import org.springframework.http.HttpStatus;
|
|
|
+import org.springframework.http.ResponseEntity;
|
|
|
+import org.springframework.validation.BindingResult;
|
|
|
+import org.springframework.validation.annotation.Validated;
|
|
|
+import org.springframework.web.bind.annotation.*;
|
|
|
+
|
|
|
+import javax.validation.Valid;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+@RestController
|
|
|
+@RequestMapping("/api")
|
|
|
+@Validated // @Validated 注解用于开启方法级别的参数验证
|
|
|
+public class ApiController {
|
|
|
+
|
|
|
+
|
|
|
+ // @RequestHeader 注解用于获取请求头中的 reqId 参数
|
|
|
+ // @Valid 注解用于对请求体中的 ApiRequest 对象进行验证
|
|
|
+ // BindingResult 用于存储验证结果
|
|
|
+ @PostMapping("/post")
|
|
|
+ public ResponseEntity<Map<String, Object>> postApi(@RequestHeader("reqId") String reqId,
|
|
|
+ @Valid @RequestBody Api pojo,
|
|
|
+ BindingResult bindingResult) {
|
|
|
+
|
|
|
+ Map<String, Object> response = new HashMap<>();
|
|
|
+ if (bindingResult.hasErrors()) {
|
|
|
+ //请求失败
|
|
|
+ response.put("success", false);
|
|
|
+ //获取第一个错误信息
|
|
|
+ response.put("message", bindingResult.getAllErrors().get(0).getDefaultMessage());
|
|
|
+
|
|
|
+ return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
|
|
|
+ }
|
|
|
+ //验证通过,成功
|
|
|
+ response.put("success", true);
|
|
|
+ response.put("message", "请求成功");
|
|
|
+ return new ResponseEntity<>(response, HttpStatus.OK);
|
|
|
+ }
|
|
|
+
|
|
|
+ @GetMapping("/get")
|
|
|
+ public ResponseEntity<Map<String, Object>> getApi(@RequestHeader("reqId") String reqId,
|
|
|
+ @Valid Api pojo,
|
|
|
+ BindingResult bindingResult) {
|
|
|
+ Map<String, Object> response = new HashMap<>();
|
|
|
+ if (bindingResult.hasErrors()) {
|
|
|
+ response.put("success", false);
|
|
|
+ response.put("message", bindingResult.getAllErrors().get(0).getDefaultMessage());
|
|
|
+ return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
|
|
|
+ }
|
|
|
+ response.put("success", true);
|
|
|
+ response.put("message", "请求成功");
|
|
|
+ return new ResponseEntity<>(response, HttpStatus.OK);
|
|
|
+ }
|
|
|
+}
|