【@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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/beiluoL/article/details/129270607
今日推荐