Springboot-请求参数处理
实例(boot-05-web-1)
0、请求映射
1、rest使用与原理
• @xxxMapping;
• Rest风格支持(使用HTTP请求方式动词来表示对资源的操作)
• 以前:/getUser 获取用户 /deleteUser 删除用户 /editUser 修改用户 /saveUser 保存用户
• 现在: /user GET-获取用户 DELETE-删除用户 PUT-修改用户 POST-保存用户
• 核心Filter;HiddenHttpMethodFilter
• 用法: 表单method=post,隐藏域 _method=put
• SpringBoot中手动开启
• 扩展:如何把_method 这个名字换成我们自己喜欢的
使用:
在controller里面写:
package com.zm.boot.controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "你好呀!";
}
// @RequestMapping(value = "/user",method = RequestMethod.GET)
@GetMapping("/user") //和上面的@RequestMapping(value = "/user",method = RequestMethod.GET)效果一样
public String getUser(){
return "GET-李白";
}
// @RequestMapping(value = "/user",method = RequestMethod.POST)
@PostMapping("/user")
public String saveUser(){
return "POST-李白";
}
// @RequestMapping(value = "/user",method = RequestMethod.PUT)
@PutMapping("/user")
public String putUser(){
return "PUT-李白";
}
// @RequestMapping(value = "/user",method = RequestMethod.DELETE)
@DeleteMapping("/user")
public String deleteUser(){
return "DELETE-李白";
}
}
在页面中写表单:如在index.html里面写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
<link rel="shortcut icon" href="/favicon.ico"/>
<link rel="bookmark" href="/favicon.ico"/>
</head>
<body>
<h3>测试REST风格</h3>
<form action="/user" method="get">
<input value="REST-GET 提交" type="submit"/>
</form>
<form action="/user" method="post">
<input value="REST-POST 提交" type="submit"/>
</form>
<form action="/user" method="post">
<input name="_method" type="hidden" value="PUT"/>
<input value="REST-PUT 提交" type="submit"/>
</form>
<form action="/user" method="post">
<input name="_method" type="hidden" value="DELETE"/>
<input value="REST-DELETE 提交" type="submit"/>
</form>
</body>
</html>
扩展:如何把_method 这个名字换成我们自己喜欢的。新建一个config包下的文件,如WebConfig.java,在WebConfig.java加入下面的语句即可
@Configuration(proxyBeanMethods=false)
public class WebConfig{
//自定义filter
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
methodFilter.setMethodParam("_m");
return methodFilter;
}
}
当我们修改了_method的名字时,我们用的时候就要改为我们自己设置的名字,如
<form action="/user" method="post">
<input name="_m" type="hidden" value="PUT"/>
<input value="REST-PUT 提交" type="submit"/>
</form>
Rest原理(表单提交要使用REST的时候)
• 表单提交会带上_method=PUT
• 请求过来被HiddenHttpMethodFilter拦截
• 请求是否正常,并且是POST
• 获取到_method的值。
• 兼容以下请求;PUT、DELETE、PATCH
• 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。
• 过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的。
Rest使用客户端工具,
• 如PostMan直接发送Put、delete等方式请求,无需Filter。
在配置文件.yaml里开启页面表单的Rest功能
spring:
mvc:
hiddenmethod:
filter:
enabled: true #开启页面表单的Rest功能