请求的方式主要分为以下几种:get,post,put,delete
get:从后端查找数据
post:插入数据
put:修改数据
delete:删除数据
@PathVaribale 获取url中的数据
@RequestParam 获取请求参数的值
@GetMapping 组合注解,是 @RequestMapping(method = RequestMethod.GET) 的缩写
@RequestBody 利用一个对象去获取前端传过来的数据
controller中的请求处理:
①处理哪个请求
②处理怎样的请求
③怎样获得请求中的参数
(1)@RequestMapping指定处理哪个请求,处理怎样的请求
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
①Request Mapping 基础用法
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping("/")
String get() {
//mapped to hostname:port/home/
return "Hello from get";
}
@RequestMapping("/index")
String index() {
//mapped to hostname:port/home/index/
return "Hello from index";
}
}
如上述代码所示,到 /home 的请求会由 get() 方法来处理,而到 /home/index 的请求会由 index() 来处理。
② @RequestMapping 来处理多个 URI
你可以将多个请求映射到一个方法上去,只需要添加一个带有请求路径值列表的 @RequestMapping 注解就行了。
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = {
"",
"/page",
"page*",
"view/*,**/msg"
})
String indexMultipleMapping() {
return "Hello from index multiple mapping.";
}
}
如你在这段代码中所看到的,@RequestMapping 支持统配符以及ANT风格的路径。前面这段代码中,如下的这些 URL 都会由 indexMultipleMapping() 来处理:
localhost:8080/home
localhost:8080/home/
localhost:8080/home/page
localhost:8080/home/pageabc
localhost:8080/home/view/
localhost:8080/home/view/view
③ 用 @RequestMapping 来处理生产和消费对象
可以使用 @RequestMapping 注解的 produces 和 consumes 这两个元素来缩小请求映射类型的范围。
为了能用请求的媒体类型来产生对象, 你要用到 @RequestMapping 的 produces 元素再结合着 @ResponseBody 注解。
你也可以利用 @RequestMapping 的 comsumes 元素再结合着 @RequestBody 注解用请求的媒体类型来消费对象
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/prod", produces = {
"application/JSON"
})
@ResponseBody
String getProduces() {
return "Produces attribute";
}
@RequestMapping(value = "/cons", consumes = {
"application/JSON",
"application/XML"
})
String getConsumes() {
return "Consumes attribute";
}
}
在这段代码中, getProduces() 处理方法会产生一个 JSON 响应, getConsumes() 处理方法可以同时处理请求中的 JSON 和 XML 内容。
③ 使用 @RequestMapping 来处理消息头
@RequestMapping 注解提供了一个 header 元素来根据请求中的消息头内容缩小请求映射的范围。
在可以指定 header 元素的值,用 myHeader = myValue 这样的格式:
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/head", headers = {
"content-type=text/plain"
})
String post() {
return "Mapping applied along with headers";
}
}
在上面这段代码中, @RequestMapping 注解的 headers 属性将映射范围缩小到了 post() 方法。有了这个,post() 方法就只会处理到 /home/head 并且 content-typeheader 被指定为 text/plain 这个值的请求。
你也可以像下面这样指定多个消息头:
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/head", headers = {
"content-type=text/plain",
"content-type=text/html"
}) String post() {
return "Mapping applied along with headers";
}
}
这样, post() 方法就能同时接受 text/plain 还有 text/html 的请求了。
④ 使用 @RequestMapping 来处理请求参数
@RequestMapping 直接的 params 元素可以进一步帮助我们缩小请求映射的定位范围。使用 params 元素,你可以让多个处理方法处理到同一个URL 的请求, 而这些请求的参数是不一样的。
你可以用 myParams = myValue 这种格式来定义参数,也可以使用通配符来指定特定的参数值在请求中是不受支持的。
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = "/fetch", params = {
"personId=10"
})
String getParams(@RequestParam("personId") String id) {
return "Fetched parameter using params attribute = " + id;
}
@RequestMapping(value = "/fetch", params = {
"personId=20"
})
String getParamsDifferent(@RequestParam("personId") String id) {
return "Fetched parameter using params attribute = " + id;
}
}
在这段代码中,getParams() 和 getParamsDifferent() 两个方法都能处理相同的一个 URL (/home/fetch) ,但是会根据 params 元素的配置不同而决定具体来执行哪一个方法。
例如,当 URL 是 /home/fetch?id=10 的时候, getParams() 会执行,因为 id 的值是10,。对于 localhost:8080/home/fetch?personId=20 这个URL, getParamsDifferent() 处理方法会得到执行,因为 id 值是 20。
⑤ @RequestMapping 注解可以同 @PathVaraible 注解一起使用,用来处理动态的 URI,URI 的值可以作为控制器中处理方法的参数。你也可以使用正则表达式来只处理可以匹配到正则表达式的动态 URI。
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = “/fetch/{id}”, method = RequestMethod.GET)
String getDynamicUriValue(@PathVariable String id) {
System.out.println("ID is " + id);
return “Dynamic URI parameter fetched”;
}
@RequestMapping(value = “/fetch/{id:[a-z]+}/{name}”, method = RequestMethod.GET)
String getDynamicUriValueRegex(@PathVariable(“name”) String name) {
System.out.println("Name is " + name);
return “Dynamic URI parameter fetched using regex”;
}
}
在这段代码中,方法 getDynamicUriValue() 会在发起到 localhost:8080/home/fetch/10 的请求时执行。这里 getDynamicUriValue() 方法 id 参数也会动态地被填充为 10 这个值。
方法 getDynamicUriValueRegex() 会在发起到 localhost:8080/home/fetch/category/shirt 的请求时执行。不过,如果发起的请求是 /home/fetch/10/shirt 的话,会抛出异常,因为这个URI并不能匹配正则表达式。
@PathVariable 同 @RequestParam的运行方式不同。你使用 @PathVariable 是为了从 URI 里取到查询参数值。换言之,你使用 @RequestParam 是为了从 URI 模板中获取参数值。
(2) @RequestParam 获取请求参数的值
@PostMapping(value = "login")
public void login(@RequestParam String name, @RequestParam String password) {
System.out.println(name + ":" + password);
}
我们可以不用这个注解,也能只要传入参数名和方法的参数名一致,也能匹配:
@PostMapping(value = "login")
public void login(String name, @RequestParam String password) {
System.out.println(name + ":" + password);
}
这里的name参数没有加这个注解,实际上也匹配到了。
如果传入参数名字和方法参数名字不一致,可以给@RequestParam的属性赋值:
@PostMapping(value = "login")
public void login(@RequestParam("account") String name, @RequestParam String password) {
System.out.println(name + ":" + password);
}
(3) @RequestBody
用法如下:
@PostMapping(path = "register")
public String registerUser(@RequestBody User user) {
return user.toString();
}
public class User {
private String name;
private String password;
省略get、set、toString...
}
@RequestBody可以用来解析json字符串(还可以解析xml),并将字符串映射到对应的实体中,实体的字段名和json中的键名要对应。
注意提交请求的时候要在请求头指定content-type为application/json charset=utf-8。
(4) @RequestHeader 用来将请求头的内容绑定到方法参数上
用法如下:
@PostMapping(value = "login")
public void login(@RequestHeader("access_token") String accessToken,@RequestParam String name) {
System.out.println("accessToken:" + accessToken);
}
(5) PathVaribale 获取url路径的数据
请求URL:
localhost:8080/hello/id 获取id值
实现代码如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){
return "id:"+id+" name:"+name;
}
}
在浏览器中 输入地址:
localhost:8080/hello/100/hello
输出:
id:81name:hello
(6) post请求的获得请求参数
① 请求体为String
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SpringBootTest {
@RequestMapping(value = “/test”,method = RequestMethod.POST)
public @ResponseBody
String getString(@RequestBody String body) {
return body;
}
}
请求只要是String类型就能获取成功,返回也是String类型,这样就不会强制传json格式的参数文件,也不用写Content-Type:application/json
② 请求体为json
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller
public class SpringBootTest {
@RequestMapping(value = "/test",method = RequestMethod.POST)
public @ResponseBody
Map getString(@RequestBody Map body) {
return body;
}
}
请求要用json格式,键值对,返回的也是json格式:方法的返回类型、方法的请求参数类型都要用Map
post请求要添加头信息
Content-Type=application/json
③ 请求体为文本
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@Controller
@RequestMapping(value ="/test")
public class SpringBootTest {
@RequestMapping(value = "/getParam",method = RequestMethod.POST)
public @ResponseBody Object getParam(HttpServletRequest request){
String body=null;
try {
/**
* 用HttpServletRequest类型的参数属性request获取输入流(读)
* 赋值给BufferedReader类型的bufferedReader(缓冲区读取)读取数据
* 将获取到的转为json
**/
BufferedReader bufferedReader=
new BufferedReader
(new InputStreamReader(request.getInputStream()));
body=org.apache.commons.io.IOUtils.toString(bufferedReader);
} catch (IOException e) {
e.printStackTrace();
}
return body;
}
}
请求参数为文本类型的时候就要通过这种输入流获取参数内容,请求的参数非json格式
④ 请求体为自定义的实体类
实体类
import lombok.Data;
@Data
public class Animal {
private String name;
private Integer age;
private char sex;
}
import com.longteng.lesson2.my.animal.Animal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value ="/test")
public class SpringBootTest {
@RequestMapping(value = "/getParam",method = RequestMethod.POST)
public @ResponseBody
Animal getParam(@RequestBody Animal animal) {
return animal;
}
}