请求参数处理
Rest风格支持(使用HTTP请求方式动词来表示对资源的操作)
- 以前:
/getUser 获取用户
/deleteUser 删除用户
/editUser 修改用户
/saveUser 保存用户 - 现在:/user
GET-获取用户
DELETE-删除用户
PUT-修改用户
POST-保存用户 - 核心Filter:需要配置HiddenMethodFilter
用法:表单method=post,隐藏域 _method=put
SpringBoot中需要手动开启:
spring:
mvc:
hiddenmethod:
filter:
enabled: true
@RestController
public class MyController {
@RequestMapping(value = "/user",method = RequestMethod.GET)
public String getUser(){
return "GET-hpf";//获取用户
}
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String postUser(){
return "POST-hpf";//保存用户
}
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String putUser(){
return "PUT-hpf";//修改用户
}
@RequestMapping(value = "/user",method = RequestMethod.DELETE)
public String deleteUser(){
return "DELETE-hpf";//删除用户
}
}
----------------------------------------------------------------------
@Bean
@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter();
}
Rest原理(表单提交需要使用Rest的时候)
-
表单提交会带上_method=put
-
请求过来被HiddenHttpMethodFilter拦截
请求是否正常,并且是POST
获取到_method的值
兼容以下请求:PUT/DELETE/PATCH
改变默认的_method
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
@Configuration(proxyBeanMethods = false)
public class WebConfig {
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
methodFilter.setMethodParam("_m");
return methodFilter;
}
}
代码当中可以使用_m代替_method。