index.html
UserController
package com.springboot.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController //ResponseBody 与 Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/get",method = RequestMethod.GET)
public String getInfo1(){
return "get";
}
@RequestMapping(value = "/post",method = RequestMethod.POST)
public String getInfo2(){
return "post";
}
@RequestMapping(value = "/delete",method = RequestMethod.DELETE)
public String getInfo3(){
return "delete";
}
@RequestMapping(value = "/put",method = RequestMethod.PUT)
public String getInfo4(){
return "put";
}
}
访问http://localhost:8003/结果
说明:html只有get和post请求,但是后端接收存在GET-获取用户 DELETE-删除用户 PUT-修改用户 POST-保存用户4种提交方式,故:
- 1.1 需要设置表单method=post,隐藏域 _method=put,delete为例;
- 1.2 SpringBoot配置文件中手动开启页面表单的Rest功能
spring:
mvc:
hiddenmethod:
filter:
enabled: true #开启页面表单的Rest功能
Rest原理(表单提交要使用REST的时候)
● 表单提交会带上_method=PUT
● 请求过来被HiddenHttpMethodFilter拦截
- 请求是否正常,并且是POST
- 获取到_method的值。
- 兼容以下请求;PUT.DELETE.PATCH
- 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。
- 过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的。
Rest使用客户端工具,如PostMan直接发送Put、delete等方式请求,无需Filter。
2、参数注解2.1 @PathVariable
- 路径变量,动态替换路径上的值,可以为单个,也可以放入map
@PathVariable Integer id, @PathVariable String name,@PathVariable Mapkv
2.2 @RequestHeader
- 有key只取对应key的值,不带key默认所有
2.3 @RequestParam
- 获取请求参数 ?age=18&hobby=篮球&hobby=足球,必须要存在与变量名一致的参数名
2.4 @cookievalue
- 获取cookie
2.5 @RequestBody
- 获取请求体,只限post请求
2.6 @RequestAttribute
- 获取request域的属性
2.7 矩阵变量
url: /boss/1;age=20/2;age=10
用分号的形式隔离,分号之前是真正的访问路径,后面熟需要导属性及其值
@GetMapping("/boss/{bossId}/{empId}")
public Map boss(@MatrixVariable(value = "age",pathVar = "bossId") Integer bossAge,
@MatrixVariable(value = "age",pathVar = "empId") Integer empAge){
Map map = new HashMap<>();
map.put("bossAge",bossAge);
map.put("empAge",empAge);
return map;
}
3、总结
package com.springboot.Controller;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/user")
public class ParameterTestController {
@GetMapping("/{id}/{name}")
public Map getUser(@PathVariable Integer id, @PathVariable String name, @PathVariable Map kv,
@RequestHeader("User-Agent") String requestHeader, @RequestHeader Map headers,
@RequestParam Integer age, @RequestParam List hobby, @RequestParam Map params
){
Map map = new HashMap<>();
map.put("name", name);
map.put("id", id);
map.put("kv", kv);
map.put("requestHeader", requestHeader);
map.put("headers", headers);
map.put("age", age);
map.put("hobby", hobby);
map.put("params", params);
return map;
}
}



