从 Jsp 访问值时出现数字格式异常

Getting Number Format Exception while accessing the value from Jsp

servlet 代码

    String id=request.getParameter("id");
     UserProfileDAO dao = new UserProfileDAO();
     List<UserProfilePojo> list = dao.UserProfile(id);
     request.setAttribute("Profile", list);
     RequestDispatcher view= request.getRequestDispatcher("Profile.jsp");
     view.forward(request, response);

用数据访问对象编写的代码Class

public List<UserProfilePojo>UserProfile(String id)
{
    String query ="select fname from registration where Id="+id;
    List<UserProfilePojo> list = new ArrayList<UserProfilePojo>();
    UserProfilePojo User = null;
    try {   
        connection = getConnection();
        stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) 
        {
                User = new UserProfilePojo();
                User.setFname(rs.getString("fname"));
                list.add(Profile);
        }                                                                                 }                                                                                  

Pojo 中编写的代码Class

public class UserProfilePojo
{
 private String fname;
 public String getFname();
        {
            return fname;
        }

        public void setFname(String fname) 
        {
            this.fname = fname;

        }
 }

通过Jsp

访问
       <td>${Profile.fname}</td>

异常堆栈跟踪

    message java.lang.NumberFormatException: For input string: "fname"    

    description The server encountered an internal error that prevented     

    it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: java.lang.NumberFormatException:     

    For input string: "fname"


  root cause

  java.lang.NumberFormatException: For input string: "fname"
  java.lang.NumberFormatException.forInputString(Unknown Source)

问题是当使用 ${Profile.fname} 从 jsp 调用 setter 方法时,它显示数字格式异常。在研究了这个特殊的异常之后,我了解到只有在尝试将一种数据类型转换为另一种数据类型时才会发生这种情况。我无法理解在这种特定情况下它发生在哪里。

请帮我解决问题。 谢谢 问候

那是因为您试图访问列表中的元素而不引用它所在的索引。

request.setAttribute("Profile", list); //Profile is a List object

改用这个:

<td>${Profile[0].fname}</td>