RESTful风格、注解梳理、logback

发布于 4 天前 0 次阅读 1193 字 预计阅读时间: 5 分钟 JAVA


REST风格URL

  • http://localhost:8080/users/1 GET:查询id为1的用户
  • http://localhost:8080/users POST:新增用户
  • http://localhost:8080/users PUT:修改用户
  • http://localhost:8080/users/1 DELETE:删除id为1的用户

@Result(s)

1.使用:

@Select("SELECT id, username, email, create_time FROM users WHERE id = #{id}")
@Results({
    @Result(column = "id", property = "id", id = true),//标记为主键
    @Result(column = "username", property = "username"),
    @Result(column = "email", property = "email"),
    @Result(column = "create_time", property = "createTime")//列名映射属性名(驼峰命名)
})
User getUserById(Long id);

2.起别名

在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。

@Select("select id, name, create_time createTime, update_time updateTime from dept")
public List<Dept> findAll();

3.开启驼峰命名(推荐)

如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射。驼峰命名规则: abc_xyz => abcXyz

  • 表中字段名:abc_xyz
  • 类中属性名:abcXyz

在application.yml中做如下配置,开启开关。

mybatis:
  configuration:
    map-underscore-to-camel-case: true

要使用驼峰命名前提是 实体类的属性数据库表中的字段名 严格遵守驼峰命名。

@RequestMapping

作用:用于建立 URL 请求与Controller方法之间的映射关系

放在类前面:提供公共的 URL 前缀

放在方法前面:指定具体的请求路径和方式

完整请求路径=类上的 @RequestMapping 的value属性 + 方法上的 @RequestMapping的value属性。

注解等效的 @RequestMapping说明
@GetMapping@RequestMapping(method = RequestMethod.GET)处理 GET 请求
@PostMapping@RequestMapping(method = RequestMethod.POST)处理 POST 请求
@PutMapping@RequestMapping(method = RequestMethod.PUT)处理 PUT 请求
@DeleteMapping@RequestMapping(method = RequestMethod.DELETE)处理 DELETE 请求
@PatchMapping@RequestMapping(method = RequestMethod.PATCH)处理 PATCH 请求

@RequestParam

1.使用

@DeleteMapping("/depts")
public Result delete(@RequestParam("id") Integer deptId){
//将前端请求的id参数绑定方法形参deptId
    System.out.println("根据ID删除部门: " + deptId);
    return Result.success();
}

@RequestParam 注解的value属性,需要与前端传递的参数名保持一致 。

@RequestParam注解required属性默认为true,代表该参数必须传递,如果不传递将报错。 如果参数可选,可以将属性设置为false。

2.省略

如果请求参数名与形参变量名相同,直接定义方法形参即可接收。

@DeleteMapping("/depts")
public Result delete(Integer id){
    System.out.println("根据ID删除部门: " + deptId);
    return Result.success();
}

@RequestBody

放在方法参数前

处理流程:客户端请求 (JSON) → HTTP Request Body → @RequestBody → Java 对象

前端请求示例:

POST /api/users HTTP/1.1
Content-Type: application/json

{
    "name": "张三",
    "age": 25,
    "email": "zhangsan@example.com"
}
@PostMapping("/users")
public ResponseEntity createUser(@RequestBody User user) {
   // 处理 user 对象
   return ResponseEntity.ok("User created");
}

@ResponseBody

放在方法或类前

// 放在方法前(具体方法)
@RequestMapping("/users/{id}")
@ResponseBody  // ← 在方法前面
public User getUser(@PathVariable Long id) {
    return userService.findById(id);
}

// 或者放在类前(整个类)
@Controller
@ResponseBody  // ← 在类前面,所有方法都生效
@RequestMapping("/api")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {  // 不需要在方法前再加@ResponseBody
        return userService.findById(id);
    }
}

处理流程:Java 对象 → @ResponseBody → HTTP Response Body → 客户端接收 (JSON)

后端处理示例:

@GetMapping("/users/{id}")
@ResponseBody  // 可省略,因为@RestController已包含
public User getUser(@PathVariable Long id) {
    User user = userService.findById(id);
    return user;  // 自动转换为JSON
}

前端接收到:

HTTP/1.1 200 OK
Content-Type: application/json

{
    "id": 1,
    "name": "张三",
    "age": 25,
    "email": "zhangsan@example.com"
}

@PathVariable

作用:

接收路径参数如/depts/1/depts/2

使用{…}来标识该路径参数,使用 @PathVariable获取路径参数。

    @GetMapping("/depts/{id}")
    public Result getInfo(@PathVariable Integer id){
        Dept dept=deptService.findById(id);
        return Result.success(dept);
    }

省略:

如果路径参数名与controller方法形参名称一致,@PathVariable注解的value属性是可以省略的。

@Slf4j

//Example:
  @Slf4j
  public class LogExample {
  }
  
//will generate:
  public class LogExample {
      private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
  }

logback

准备工作:

1.引入logback的依赖(springboot中无需引入,在springboot中已经传递了此依赖)

2.引入配置文件 logback.xml(可ai生成)

3.记录日志:定义日志记录对象Logger,记录日志

public class LogTest {
    
    //定义日志记录对象
    private static final Logger log = LoggerFactory.getLogger(LogTest.class);

    @Test
    public void testLog(){
        log.debug("开始计算...");
        int sum = 0;
        int[] nums = {1, 5, 3, 2, 1, 4, 5, 4, 6, 7, 4, 34, 2, 23};
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        log.info("计算结果为: "+sum);log.debug("结束计算...");
    }

}
日志级别说明记录方式
trace追踪,记录程序运行轨迹 【使用很少】log.trace("...")
debug调试,记录程序调试过程中的信息,实际应用中一般将其视为最低级别 【使用较多】log.debug("...")
info记录一般信息,描述程序运行的关键事件,如:网络连接、io操作 【使用较多】log.info("...")
warn警告信息,记录潜在有害的情况 【使用较多】log.warn("...")
error错误信息 【使用较多】log.error("...")