SpringBoot之Web开发02

请求参数处理

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。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值