SpringBoot:请求参数处理

请求映射

REST使用与原理

RESTful的简介和小案例:

SpringMVC:RESTful简介

SpringMVC:RESTFul案例

核心Filter;HiddenHttpMethodFilter

  • 用法: 表单method=post,隐藏域 _method=put
   // @RequestMapping(value = "/user",method = RequestMethod.GET)
    @ GetMapping("/user")
    public String getUser(){
        return "GET-张三";
    }

    //@RequestMapping(value = "/user",method = RequestMethod.POST)
    @Post("/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)
    @DeleteMapper("/user")
    public String deleteUser(){
        return "DELETE-张三";
    }
  • SpringBoot中手动开启
==============WebMvcConfiguration.java===============	
	@Bean
	@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
	@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)
	public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
		return new OrderedHiddenHttpMethodFilter();
	}
===========yaml===========
spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true   #开启页面表单的Rest功能

 

  • 如何把_method 这个名字换成我们自己喜欢的

上面@ConditionalOnMissingBean(HiddenHttpMethodFilter.class) 容器中没有这个类,在执行下面

可以自己新建一个filter HiddenHttpMethodFilter.java

并自己set methodParam 为自己喜欢的名字

//自定义filter
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
        methodFilter.setMethodParam("_m");
        return methodFilter;
    }

 REST原理:

(表单提交要使用REST的时候)
  • 表单提交会带上_method=PUT
  • 请求过来被HiddenHttpMethodFilter拦截
    • 请求是否正常,并且是POST
      • 获取到_method的值。
      • 兼容以下请求;PUT.DELETE.PATCH
      • 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。
      • 过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的

Rest使用客户端工具,

  • 如PostMan直接发送Put、delete等方式请求,无需Filter。

请求映射原理

 

阅读剩余
THE END