接口的架构风格:REST
RESTful注解的使用:四种请求方式
接口:
这些接口可以是函数或者url,指应用程序对外的入口,通过这个入口就可以访问应用程序的功能,比如之前用的Controller、Servlet,他们提供的url都是接口
暴露的是一个地址,别人只能访问这个地址.
http://localhost:8080/myboot/student/1001/1
在url中来传值,通过getParamter不同获取传递的数据,因为它不是在问号后面的数据,所以通过注解@PathVariable来获取数据
(1)@PathVariable注解的使用
创建Controller:MyRestController:get请求方式
package com.bjpowernode.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController //@Controller 和@ResponseBody的组合
public class MyRestController {
//学习注解使用
/*@PathVariable(路径变量):获取url中的数据
* 属性:value:路径变量名
* 位置:放在控制器方法形参的前面
* */
//查询id=1001的学生
@GetMapping("/student/{stuId}")
public String queryStudent(@PathVariable(value = "stuId") Integer studentId){
return "查询学生studentId="+studentId;
}
}
配置文件application.properties:设置端口号、上下文访问路径
server.port=9001
server.servlet.context-path=/myboot
主启动类:Application:启动项目
package com.bjpowernode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在浏览器输入:url
更换url:
addStudent.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>添加学生</h3>
<form action="student/zhangsan/20" method="post">
<input type="submit" value="注册学生">
</form>
</body>
</html>
MyRestController:其他请求方式:
package com.bjpowernode.controller;
import org.springframework.web.bind.annotation.*;
@RestController //@Controller 和@ResponseBody的组合
public class MyRestController {
//学习注解使用
/*@PathVariable(路径变量):获取url中的数据
* 属性:value:路径变量名
* 位置:放在控制器方法形参的前面
* http://localhost:9001/myboot/student/1002
* */
//查询id=1001的学生
@GetMapping("/student/{stuId}")
public String queryStudent(@PathVariable(value = "stuId") Integer studentId){
return "查询学生studentId="+studentId;
}
/*
* 创建资源Post 请求方式
*
* http://localhost:9001/myboot/student/zhangsan/1002
* */
@PostMapping("/student/{name}/{age}")
public String createStudent(@PathVariable("name") String name,@PathVariable("age") Integer age){
return "创建资源 student:name="+name+" age="+age;
}
/*
* 更新资源
* 当路径变量名称和形参名一样时,@PathVatiable中的value可以不写
* */
@PutMapping("/student/{id}/{age}")
public String mnodifyStudent(@PathVariable Integer id,@PathVariable Integer age){
return "更新资源,执行put请求方式:id="+id+" aeg="+age;
}
/*删除资源
* */
@DeleteMapping("/student/{id}")
public String removeStudent(@PathVariable Integer id){
return "删除资源,执行delete请求方式:id="+id;
}
}
Post请求方式:
访问addstudent.html:
使用Postman工具发送请求:发送Put Delete请求,就不用再写表单,编写页面代码了
Put请求:
Delete请求: