首页 > 解决方案 > Reacts JS/SpringBoot 错误:无法在 API 中将字符串转换为长更新方法

问题描述

当我发送更新 PUT 调用时,我不断收到此错误:

无法将“java.lang.String”类型的值转换为所需的“java.lang.Long”类型;嵌套异常是java。朗。数字格式异常:对于输入字符串:“未定义”

我正在使用一项服务来执行 CRUD 调用:

getEmployees(){
    return axios.get("http://localhost:8080/api/v1/employees");
}

createEmployee(employee){
    return axios.post(EMPLOYEE_API_BASE_URL,employee);
}

getEmployeeById(id){
    const url = EMPLOYEE_API_BASE_URL + "/" + id;
    
    return axios.get(url);
}

updateEmployee(employee, employeeId){
    return axios.put(EMPLOYEE_API_BASE_URL + '/' + employeeId, employee);
}

员工组件:

constructor(props){
    super(props);
    this.state = {
        currentEmployee: {
            id: null,
            firstName: "",
            lastName: "",
            emailId: ""
        }
       

    }

    this.fetchData = this.fetchData.bind(this);
    this.saveUpdateData = this.saveUpdateData.bind(this);

    this.onChangeData = this.onChangeData.bind(this);
}


componentDidMount(){
    this.fetchData();
}

fetchData(){

    EmployeeService.getEmployeeById(this.props.match.params.id).then(response => {
        this.setState({
            currentEmployee: {
                
                firstName: response.data.firstName,
                lastName: response.data.lastName,
                emailId: response.data.emailId
            }
            
        });
        
    })
}

onChangeData(e){
    this.setState({
        currentEmployee: {
        [e.target.name] : e.target.value
            
        }
    });
    console.log(e.target.name, e.target.value)
}

saveUpdateData(event){
    event.preventDefault();
    let currentEmp = this.state.currentEmployee;
    let emp = {firstName: currentEmp.firstName, lastName: currentEmp.lastName, emailId: currentEmp.emailId};
    EmployeeService.updateEmployee(emp, this.state.currentEmployee.id)
        .then(res => {
            this.props.history.push("/employees");
            console(res.data);
        })
}

render() {
    const {currentEmployee} = this.state;

    return (
        <div>
            {currentEmployee ? (

                <div className="edit-form">
                    <h4>Employee</h4>
                    <form>
                        <div className="form-group">
                            <label htmlFor="firstName">First Name</label>
                            <input 
                                className="form-control"
                                type="text"
                                id="fname"
                                name="firstName"
                                value={currentEmployee.firstName}
                                onChange={this.onChangeData}/>


                        </div>

                        <div className="form-group">
                            <label htmlFor="lastName">Last Name</label>
                            <input 
                                className="form-control"
                                type="text"
                                id="lname"
                                name="lastName"
                                value={currentEmployee.lastName}
                                onChange={this.onChangeData}/>

                                
                        </div>

                        <div className="form-group">
                            <label htmlFor="emailId">Email</label>
                            <input 
                                className="form-control"
                                type="text"
                                id="email"
                                name="emailId"
                                value={currentEmployee.emailId}
                                onChange={this.onChangeData}/>

                                
                        </div>

                        <button  className="btn btn-success" onClick={this.saveUpdateData}>
                            Edit
                        </button>
                        <Link to={"/employees/"} className="btn btn-warning ml-3">Back</Link>
                    </form>
                </div>

            ) : (<div>
                <br />
                <p>Please choose an employee</p>
            </div>)}
        </div>
    );
}

SpringBoot 代码:

@GetMapping("/employees")
public List<Employee> getAllEmployees(){
    return employeeRepository.findAll();
}

@PostMapping("/employees")
public Employee createEmployee(@RequestBody Employee emp) {
    return employeeRepository.save(emp);
}

@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) {
    Employee employee = employeeRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Employee Doesnt Exist!"));
    
    return ResponseEntity.ok(employee);
    
    
}


@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employeeDetails){
    Employee employee = employeeRepository.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Employee Doesnt Exist!"));
    
    employee.setFirstName(employeeDetails.getFirstName());
    employee.setLastName(employeeDetails.getLastName());
    employee.setEmailId(employeeDetails.getEmailId());
    
    Employee updatedEmployee = employeeRepository.save(employee);
    return ResponseEntity.ok(updatedEmployee);
    
}

标签: mysqlreactjsspring-bootjpa

解决方案


像这样更改您的代码:

@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) {

@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable("id") Long idLong) {

必须将getmapping中定义的参数名添加到PathVariable注解中,入参名无所谓


推荐阅读