草庐IT

若依框架前后端各个请求方式参数传递示例

D__O__N 2023-10-31 原文
    • get请求

1.1 不带params(Restful风格)

封装方法getBanner

export function getBanner(customerBannerId) {
  return request({
    url: '/recruit/banner/' + customerBannerId,
    method: 'get'
  })
}

getBanner方法调用(customerBannerId是一个数字)

import {getBanner} from "@/api/recruit/banner"; 

    handleUpdate(row) {
      this.reset();
      this.pageStatus = "edit";
      const customerBannerId = row.customerBannerId || this.ids;
      getBanner(customerBannerId).then(response => {
        if (response.code === 200) {
          this.form = response.data;
          this.open = true;
          this.title = "修改【" + row.name + "】横幅";
        } else this.$modal.msgError("请求横幅信息失败,请刷新页面后重试!");
      });
    }

后端接口(@PathVariable 注解取得请求路径中的参数,注意此处的三个参数名要一致)

    @GetMapping(value = "/{customerBannerId}")
    public AjaxResult getInfo(@PathVariable("customerBannerId") Long customerBannerId) {
        return AjaxResult.success(customerBannerService.getById(customerBannerId));
    }

1.2 带params(传统风格)

封装方法getBanner

export function getBanner(customerBannerId) {
  return request({
    url: '/recruit/banner/view',
    method: 'get',
    params: customerBannerId
  })
}

getBanner方法调用(customerBannerId是一个对象,这里属性名与属性值一致,简写)

import {getBanner} from "@/api/recruit/banner";

    handleUpdate(row) {
      this.reset();
      this.pageStatus = "edit"
      const customerBannerId = row.customerBannerId || this.ids
      getBanner({customerBannerId}).then(response => {
        if (response.code === 200) {
          this.form = response.data;
          this.open = true;
          this.title = "修改【" + row.name + "】横幅";
        } else this.$modal.msgError("请求横幅信息失败,请刷新页面后重试!");
      });
    },

后端接口(前端传递的对象的属性名要与此处的参数名一致,否则接收不到)

    @GetMapping(value = "/view")
    public AjaxResult getInfo(Long customerBannerId) {
        return AjaxResult.success(customerBannerService.getById(customerBannerId));
    }

1.3 带params(传统风格,后端用@RequestParam注解绑定参数值)

封装方法delBanner

export function delBanner(customerBannerId) {
  return request({
    url: '/recruit/banner/del',
    method: 'get',
    params: customerBannerId
  })
}

delBanner方法调用(传入参数要为对象形式)

import {delBanner} from "@/api/recruit/banner";

    handleDelete(row) {
      this.$modal.confirm('是否确认删除横幅名称为【' + row.name + '】的数据项?').then(function () {
        return delBanner({customerBannerId: row.customerBannerId});
      }).then(res => {
        if (res.code === 200) {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        } else this.$modal.msgError("删除失败,请刷新页面后重试!");
      }).catch(err => {
        console.log(err)
      });
    }

后端接口(@RequestParam注解绑定参数值)

    @GetMapping("/del")
    public AjaxResult remove(@RequestParam("customerBannerId") Long customerBannerId) {
        // 处于显示状态不能删除
        CustomerBanner banner = customerBannerService.getById(customerBannerId);
        if (banner.getIsShow() == 0 || banner.getIsShow().equals(0)) {
            return AjaxResult.error("【" + banner.getName() + "】横幅处于显示状态,不能删除");
        }
        return toAjax(customerBannerService.removeById(customerBannerId));
    }

2. post请求

封装方法addBanner

export function addBanner(data) {
  return request({
    url: '/recruit/banner/create',
    method: 'post',
    data: data
  })
}

addBanner方法调用(this.form 为一个对象)

import {addBanner} from "@/api/recruit/banner";

    addBanner(this.form).then(response => {
      if (response.code === 200) {
        this.$modal.msgSuccess("新增成功");
        this.open = false;
        this.getList();
      } else this.$modal.msgError("新增失败,请刷新页面后重试!");
    });

后端接口(@RequestBody 注解读出前端传递data的各个属性,前提是data的属性名要与CustomerBanner的属性名一致)

    @PostMapping("/create")
    public AjaxResult add(@RequestBody CustomerBanner customerBanner) {
        String userNickname = SecurityUtils.getUserNickname();//getUserNickname():自己在若依框架SecurityUtils类添加的一个方法
        Long userId = SecurityUtils.getUserId();//获取登录用户id
        customerBanner.setCreateBy(userNickname);
        customerBanner.setCreateById(userId);
        customerBanner.setCreateTime(new Date());
        return toAjax(customerBannerService.save(customerBanner));
    }


    /**
     * 获取登录用户昵称,数据库用户名字段存储的是电话号码,真正的用户名存储在昵称字段
     */
    public static String getUserNickname()
    {
        LoginUser loginUser = SecurityContextHolder.get(SecurityConstants.LOGIN_USER, LoginUser.class);
        return loginUser.getSysUser().getNickName();
    }

3. put请求

方法封装updateBanner

export function updateBanner(data) {
  return request({
    url: '/recruit/banner',
    method: 'put',
    data: data
  })
}

updateBanner方法调用

import {updateBanner} from "@/api/recruit/banner";

    updateBanner(this.form).then(response => {
      if (response.code === 200) {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      } else this.$modal.msgError("修改失败,请刷新页面后重试!");
    });

后端接口(@RequestBody 注解读出前端传递data的各个属性,前提是data的属性名要与CustomerBanner的属性名一致)

    @PutMapping
    public AjaxResult edit(@RequestBody CustomerBanner customerBanner) {
        String userNickname = SecurityUtils.getUserNickname();
        Long userId = SecurityUtils.getUserId();
        customerBanner.setUpdateBy(userNickname);
        customerBanner.setUpdateById(userId);
        customerBanner.setUpdateTime(new Date());
        return toAjax(customerBannerService.updateById(customerBanner));
    }

4. delete请求

封装方法delBanner

export function delBanner(customerBannerId) {
  return request({
    url: '/recruit/banner/' + customerBannerId,
    method: 'delete'
  })
}

delBanner方法调用

import {delBanner} from "@/api/recruit/banner";

    handleDelete(row) {
      const customerBannerIds = row.customerBannerId;
      this.$modal.confirm('是否确认删除横幅名称为【' + row.name + '】的数据项?').then(function () {
        return delBanner(customerBannerIds);
      }).then(res => {
        if (res.code === 200) {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        } else this.$modal.msgError("删除失败,请刷新页面后重试!");
      }).catch(err => {
        console.log(err)
      });
    }

后端接口(@PathVariable 注解取得请求路径中的参数,此时方法参数名称和需要绑定的url中变量名称一致,可以简写)

@PathVariable 注解简单用法

    @DeleteMapping("/{customerBannerIds}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] customerBannerIds) {
        // 处于显示状态不能删除
        for (Long customerBannerId : customerBannerIds) {
            CustomerBanner banner = customerBannerService.getById(customerBannerId);
            if (banner.getIsShow() == 0 || banner.getIsShow().equals(0)) {
                return AjaxResult.error("【" + banner.getName() + "】横幅处于显示状态,不能删除");
            }
        }
        return toAjax(customerBannerService.removeBatchByIds(Arrays.asList(customerBannerIds)));
    }

有关若依框架前后端各个请求方式参数传递示例的更多相关文章

  1. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  4. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  5. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  6. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  7. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  8. ruby - 定义方法参数的条件 - 2

    我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano

  9. ruby-on-rails - 正确的 Rails 2.1 做事方式 - 2

    question的一些答案关于redirect_to让我想到了其他一些问题。基本上,我正在使用Rails2.1编写博客应用程序。我一直在尝试自己完成大部分工作(因为我对Rails有所了解),但在需要时会引用Internet上的教程和引用资料。我设法让一个简单的博客正常运行,然后我尝试添加评论。靠我自己,我设法让它进入了可以从script/console添加评论的阶段,但我无法让表单正常工作。我遵循的其中一个教程建议在帖子Controller中创建一个“评论”操作,以添加评论。我的问题是:这是“标准”方式吗?我的另一个问题的答案之一似乎暗示应该有一个CommentsController参

  10. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

随机推荐