目录 SpringBoot 核心注解 SpringBoot Restful 接口实现 封装响应数据 SpringBoot 核心注解 SpringBoot 基础入门 注解 说明 Component声明为 SpringBoot 的 beanRepository用于 dao 层的 beanAutowired用于向一个 b
- SpringBoot 核心注解
- SpringBoot Restful 接口实现
- 封装响应数据
SpringBoot 核心注解
SpringBoot 基础入门
SpringBoot Restful 接口实现
代码示例:
package com.example.apitestplatform.controller;
import com.example.apitestplatform.entity.User;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value="demo") // 类中所有接口地址的前缀
public class DemoController {
// @RequestMapping(value="loginGet", method= RequestMethod.GET)
@GetMapping("loginGet")
public String loginGet() {
return "登录成功";
}
// @RequestMapping(value="loginPost", method= RequestMethod.POST)
@PostMapping("loginPost") // 简便写法
public String loginPost(@RequestBody User user) { // 如果没用 @RequestBody,则获取结果为 null
System.out.println("username : "+user.getUsername());
System.out.println("password : "+user.getPassword());
return "登录成功:"+user.getUsername();
}
// 访问:http://localhost:8080/demo/userId/1/2
// @RequestMapping(value="userId/{userId}/{id}", method=RequestMethod.GET)
@GetMapping("getUser/{userid}/{id}")
public String loginUser1(@PathVariable("userid") Integer userid, @PathVariable("id") Integer id) {
System.out.println("userid : "+userid);
System.out.println("id : "+id);
return "userid: "+userid+" id: "+id;
}
// 访问:http://localhost:8080/demo/getUser?userid=1&id=2
// 访问:http://localhost:8080/demo/getUser?user=1&id=2,则 userid 值为 null
@GetMapping("getUser")
public String loginUser2(@RequestParam(value="userid", required=false) Integer userid, // required=false:参数非必须传
@RequestParam("id") Integer id) {
System.out.println("userid : "+userid);
System.out.println("id : "+id);
return "userid: "+userid+" id: "+id;
}
}
封装响应数据
响应对象类:
package com.example.apitestplatform.common;
import lombok.Builder;
import lombok.Data;
@Data
@Builder // 作用:调用时使用链式写法
public class ResultResponse {
private String code;
private String message;
private Object data;
}
接口类:
@GetMapping("loginSuccess")
public ResponseEntity loginSuccess() {
User user = new User();
user.setUsername("xiaoming");
user.setPassword("admin123");
ResultResponse resultResponse = ResultResponse.builder().code("00").message("登录成功").data(user).build();
return ResponseEntity.status(HttpStatus.OK).body(resultResponse);
}
@GetMapping("loginFail")
public ResponseEntity loginFail() {
User user = new User();
user.setUsername("xiaoming");
user.setPassword("admin123");
ResultResponse resultResponse = ResultResponse.builder().code("02").message("登录失败").data(user).build();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultResponse);
}
请求结果:
{"code":"00","message":"登录成功","data":{"username":"xiaoming","password":"admin123"}}
{"code":"00","message":"登录失败","data":{"username":"xiaoming","password":"admin123"}}