声明为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
控制的增删改查
- 新增
@PostMapping
,其中请求体中带回来的参数,通过@RequestBody
与声明的实体类关联,注意 JSON数据的键名与实体对象的属性名相同
public Result add(@RequestBody Dept dept) {
dept.setCreateTime(LocalDateTime.now());
dept.setUpdateTime(LocalDateTime.now());
deptService.add(dept);
return Result.success();
}
- 删除
@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)
- 修改
@PutMapping
- 查询
@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);
}