Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

spring - Getting NumberFormatException while getting the value in JSP using JSTL

I am working on Spring/Hibernate sample web application. Actually, I am trying to load the employees from database. In this case, while getting the data from database for both employee and address tables i am getting the NumberFormat exception.

Following is the code i am working on,

JSP Code:

      <c:if  test="${!empty employeeList}">
        <table class="data">
<c:forEach items="${employeeList}" var="emp">
    <tr>
        <td><c:out value="${emp.firstname}" /></td>
        <td><c:out value="${emp.lastname}" /></td>
        <td><c:out value="${emp.email}" /></td>
        <td><a href="edit/${emp.id}">Edit</a></td>
        <td><a href="delete/${emp.id}">Delete</a></td>
    </tr>
</c:forEach>

Controller Code:

@RequestMapping(value = "/", method = RequestMethod.GET)
public String listEmployees(ModelMap map) 
{
    map.addAttribute("employeeList", employeeManager.getAllEmployees());
    return "editEmployeeList";
}

Service Layer Code:

 @Override
@Transactional
public List<EmployeeEnitity> getAllEmployees() {
    return employeeDAO.getAllEmployees();
}


public List<EmployeeEntity> getAllEmployees() {
    return this.sessionFactory.getCurrentSession().createQuery("select ee.firstname,ee.lastname,addr.email from " +
            "com.howtodoinjava.entity.EmployeeEntity ee, com.howtodoinjava.entity.AddressEntity addr where ee.id=addr.id").list();

}

Please help me to resolve this exception

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The return type of session.createQuery(String).list() in your service method getAllEmployees is List<Object[]>, it is not List<Employee>

In controller you are adding this List<Object[]> to your model at this line:

map.addAttribute("employeeList",employeeList);

Now in JSP you are trying to access the model object in JSTL forEach loop:

<c:forEach items="${employeeList}" var="emp">

As employeeList represents List<Object[]>, the variable emp represents Object[], it is not Employee. Now using dot (.) operator on variable emp means you are trying to access an element at a particular index position. For example:

emp.0 --> is same as emp[0]
emp.1 --> is same as emp[1]
emp.indexPosition --> is same as emp[indexPosition]

So when you say emp.firstName, then the firstName is converted to integer, as firstName is not an integer you are getting NumberFormatException


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...