简体   繁体   English

无法将“java.lang.String”类型的属性值转换为属性“id”所需的类型“int”

[英]Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'id'

I have a very simple spring boot application where I am trying to save an updated location to the database.我有一个非常简单的 spring boot 应用程序,我试图将更新的位置保存到数据库中。 But whenever I am retrieving a list of saved locations and saving the updated location to the DB, I am getting below error:但是每当我检索已保存位置列表并将更新后的位置保存到数据库时,我都会收到以下错误:

2019-11-27 09:29:05.330  WARN 14764 --- [nio-8080-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'location' on field 'id': rejected value []; codes [typeMismatch.location.id,typeMismatch.id,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [location.id,id]; arguments []; default message [id]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'id'; nested exception is java.lang.NumberFormatException: For input string: ""]]

Below are my classes:下面是我的课:

LocationRepository.java: LocationRepository.java:

package com.springBoot.location.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.springBoot.location.entities.location;
import com.springBoot.location.service.LocationService;

@Controller
public class LocationController {

    @Autowired
    private LocationService service;

    @RequestMapping("/showCreate")
    public String showCreate() {
        return "createLocation";
    }

    //when the form in "createLocation.jsp" will be submitted, the same page "createLocation.jsp" will be returned, 
    @RequestMapping("/saveLoc")                                 //but this time, with a message, stating that the location has been saved.
    public String saveLocation(@ModelAttribute("location")location location,ModelMap modelmap) {//when the page will be saved, a "location" bean/object will be created
        location saveLocation = service.saveLocation(location);            //all the fields from that page will be saved into that object and
        String msg = "location saved with id "+saveLocation.getId();      //will be sent as request to the database
        modelmap.addAttribute("msg",msg);//modelMap is for handling responses from the db.
        return "createLocation";                                           
    } 

    @RequestMapping("/displayLocations")
    public String displayLocations(ModelMap modelMap) {
        List<location> allLocations = service.getAllLocations();
        modelMap.addAttribute("locations",allLocations);
        return "displayLocations";
    }

    @RequestMapping("/addLoc")
    public String showCreate1() {
        return "createLocation";
    }

    @RequestMapping("/getID")
    public String getId(@ModelAttribute("location")location location,ModelMap modelMap) {
        List<location> allLocations = service.getAllLocations();
        location Lastlocation = allLocations.get(allLocations.size()-1);
        int id = Lastlocation.getId();
        String lastId = "The last ID was "+id;
        modelMap.addAttribute("lastId",lastId);
        return "createLocation";

    }

    @RequestMapping("/deleteLocation")
    public String deleteLocation(@RequestParam("id")int id,ModelMap modelMap) {
        location l = service.getLocationById(id);
        service.deleteLocation(l);
        List<location> allLocations = service.getAllLocations();
        modelMap.addAttribute("locations",allLocations);
        return "displayLocations";
    }

    @RequestMapping("/updateLocation")
    public String updateLocation(@RequestParam("id")int id,ModelMap modelMap) { 
        location l = service.getLocationById(id);
        modelMap.addAttribute("locations",l);
        return "updateLocation";

    }

    @RequestMapping("/updateLoc")
    public String saveUpdateLocation(@ModelAttribute("location")location location,ModelMap modelMap) {
        service.updateLocation(location);
        List<location> locations = service.getAllLocations();
        modelMap.addAttribute("locations",locations);
        return "displayLocations";
    }




}

Location.java位置.java

package com.bharath.location.entities;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Location {

    @Id
    private int id;
    private String code;
    private String name;
    private String type;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Location [id=" + id + ", code=" + code + ", name=" + name + ", type=" + type + "]";
    }

}

Below are my jsp files:下面是我的jsp文件:

createLocation.jsp创建位置.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Create location</title>
</head>
<body>
 <form action="saveLoc" method="post"> <!-- value of the "action" attribute is same as the value inside "request controller" method name, to which the method maps to --> 
 <pre>
    Id:<input type="text" name="id"/><!-- the value in the "name" attribute should be same as the variable names in the "entity" class -->
    <a href="getID">Want to know the last ID ?</a>
    Code:<input type="text" name="code"/>
    Name:<input type="text" name="name"/>
    Type: Urban<input type="radio" name="type" value="URBAN"/><!-- when the page will be saved, the value will be saved as "URBAN" -->
          Rural<input type="radio" name="type" value="RURAL"/>
     <input type="submit" value="save"/>
 </pre>
 </form>
${lastId}<br>
${msg}<br>
 <a href="displayLocations">View all</a> <!-- the value in the "href" attribute will be inside the "RequestMapping" 
</body>                                                     annotation mapping to a specific class for handling a request -->
</html>

displayLocations.jsp显示位置.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!-- in order to use JSTL, we first mentioned the jstl dependency in the pom.xml and then used taglib directive. We use a prefix so that -->
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!-- we dont have to use the full uri everywhere -->
<%@page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>List of locations</title>
</head>
<body>
    <table>
        <tr>
            <th>ID</th>
            <th>Code</th>
            <th>Name</th>
            <th>Type</th>
        </tr>

        <c:forEach items="${locations}" var="location"><!-- the value in the "items" attribute is same as the "key" value in the modelMap, in the respective java class -->
        <tr>
            <td>${location.id}</td>
            <td>${location.code}</td>
            <td>${location.name}</td>
            <td>${location.type}</td>
            <td><a href="deleteLocation?id=${location.id}">Delete</a></td> <!--"?id=${location.id}" will pass the id dynamically to the controller -->
            <td><a href="updateLocation?id=${location.id}">Update</a></td>
        </tr>  
        </c:forEach>
    </table>
    <br>
<a href="addLoc">Add more locations</a>
</body>
</html>

updateLocation.jsp更新位置.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Create Location</title>
</head>
<body>

<form action="updateLoc" method="post">
<pre>
Id: <input type="text" name="id" value="${location.id}" readonly/>
Code: <input type="text" name="code" value="${location.code}"/>
Name: <input type="text" name="name" value="${location.name}"/>
Type: Urban <input type="radio" name="type" value="URBAN" ${location.type=='URBAN'?'checked':''}/>
    Rural <input type="radio" name="type" value="RURAL" ${location.type=='RURAL'?'checked':''}/>
Email: <input type="text" name="email" value="${location.name}"/>
Phone: <input type="text" name="phone" value="${location.name}"/>
Address: <input type="text" name="address" value="${location.name}"/>
<input type="submit" value="save"/>
</pre>
</form>

</body>
</html>

将 ID 属性的输入类型更改为数字,如下所示

Id: <input type="number" name="id" value="${location.id}" readonly/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 [无法将类型&#39;java.lang.String []&#39;的属性值转换为属性的必需类型&#39;java.util.List&#39; - [Failed to convert property value of type 'java.lang.String[]' to required type 'java.util.List' for property 无法将类型为java.lang.String的属性值转换为属性电话所需的long类型; 嵌套的超验 - Failed to convert property value of type java.lang.String to required type long for property phone; nested exce 无法将 [java.lang.String] 类型的属性值转换为所需类型 [java.time.LocalDate] - Failed to convert property value of type [java.lang.String] to required type [java.time.LocalDate] 无法将 java.lang.String 类型的属性值转换为所需类型 java.util.Date - Failed to convert property value of type java.lang.String to required type java.util.Date [无法将&#39;java.lang.String&#39;类型的属性值转换为所需的&#39;java.sql.Time&#39;类型 - [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Time' 无法将类型&#39;java.lang.String&#39;的属性值转换为必需类型&#39;java.util.Date&#39; - Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' 无法将 java.lang.String[] 类型的属性值转换为所需的类型 java.util.List - Failed to convert property value of type java.lang.String[] to required type java.util.List 无法将类型java.lang.String的属性值转换为所需的类型java.time.LocalDateTime - Failed to convert property value of type java.lang.String to required type java.time.LocalDateTime 无法将“java.lang.String”类型的属性值转换为所需类型“java.sql.Date” - Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Date' 在 Open API 3 中无法将类型“java.lang.String”的属性值转换为所需类型 - Failed to convert property value of type 'java.lang.String' to required type in Open API 3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM