【@PathVariable获取参数报错】Missing URI template variable ‘empId‘ for method parameter of type Integer

项目场景:

ajax请求 Missing URI template variable 'empId' for method parameter of type Integer

在这里插入图片描述


问题描述

前端请求代码:

  $.ajax({
                type: "post",
                data: {empId: empId},
                url: "http://localhost:8080/ssm/employee/deleteEmployee",
                success: function (data, status) {
                    console.log(data);
                    if (status == "success") {
                        toastr.success('提交数据成功');
                    }
                },
                error: function () {
                    toastr.error('Error');
                },
                complete: function () {
                }
            });

后端请求代码:

 @RequestMapping(value = "/deleteEmployee", method = RequestMethod.POST)
    public int deleteEmployee(@PathVariable("empId") Integer empId) {
        int num = employeeService.deleteEmployeeById(empId);
        return  num;
    }

原因分析:

添加了多余的注解@PathVariable ,@PathVariable 用于从一个URI模板里面取值来填充


解决方案:

PathVariable,它的用法是只有url是带有{id}是才能获取参数传参,删除@PathVariable之后问题解决

   @RequestMapping(value = "/deleteEmployee", method = RequestMethod.POST)
    @ResponseBody
    public int deleteEmployee( Integer empId) {
        int num = employeeService.deleteEmployeeById(empId);
        return  num;
    }

后端如何获取前端传的参数

传统来讲,肯定是两种方式为主,一种是 GET ,一种是 POST ,这两种方式都是向一个 URL 传参 GET 方式体现到了地址栏里,POST 方式将内容放在了 body 里

@RequestParam 和 @PathVariable 注解是用于从 request 中接收请求的,两个都可以接收参数,关键点不同的是@RequestParam 是从 request 里面拿取值,而 @PathVariable 是从一个URI模板里面来填充

@PathVariable

通过 URI 模板来填充
举例:

    @RequestMapping(value = "/getByEmpId/{empId}", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getByEmpId(HttpServletRequest request, @PathVariable("empId") int empId) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("empId", empId);
        return modelMap;
    }

当我们访问:http://localhost:8080/ssm/employee/getByEmpId/11
在这里插入图片描述

@PathParam

获取 request 里的值

    @RequestMapping(value = "/getById", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getById(HttpServletRequest request, @RequestParam(value = "id", required = true) int id) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("id", id);
        return modelMap;
    }

当我们访问:http://localhost:8080/ssm/employee/getById?id=123

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值