SpringBoot之Controller层注解入门

声明为Controller层

一般使用注解@RestController,根据下面的源码,其集成了主要两个功能是:@Controller;声明其为Controller;@ResponseBody:默认返回值为一个JSON格式的对象

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

HTTP地址

例如服务器的地址和端口为http://localhost:90,根据RESTful风格,如果要操作示例这个类型其url都为http://localhost:90/example根据是get、post、delete、put决定具体操作,那么在SpringBoot中,其可以是@GetMapping(/example)、@DeleteMapping(/depts),也可以使用@RequestMapping("/example")在example的controller的头部直接声明

@RequestMapping("/depts")
public class ExampleController {
@GetMapping
xxx方法
@DeleteMapping
xxx方法
}

HTTP控制的增删改查

  1. 新增@PostMapping,其中请求体中带回来的参数,通过@RequestBody与声明的实体类关联,注意 JSON数据的键名与实体对象的属性名相同
 public Result add(@RequestBody Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptService.add(dept);
        return Result.success();
    }
  1. 删除@DeleteMapping,删除就可能涉及到根据参数删除,参数接受主要方式是通过@RequestParam,例如http://localhost:90/depets?id=1需要删除id为1的数据,其接受参数的语法为@RequestParam("id") Integer id当参数和形参的变量名一致是可以省略@RequestParam("id")
// 省略(@RequestParam("id")==>public Result delete(Integer id)
public Result delete(@RequestParam("id") Integer id) {
        System.out.println("根据id删除部门");
        int rows = deptService.deleteById(id);
        if (rows > 0) {
            return Result.success();
        } else {
            return Result.error("删除失败");
        }
    }

需要特别注意的是使用@RequestParam("id")就默认参数是必须的,如果参数是可以不需要的,使用@RequestParam(value="id",required=false)

  1. 修改@PutMapping
  2. 查询@GetMapping,需要注意的是如果查询参数写在了url地址中的这种形式http://localhost:90/depets/1其实1是参数,此时使用@PathVariable Integer id注解来获取路径中参数,具体代码如下:
 @GetMapping("/{id}")
    public Result getInfo(@PathVariable Integer id) {
        System.out.println("根据id获取部门数据");
        Dept dept = deptService.getInfo(id);
        return Result.success(dept);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值