I was making a pretty basic web app with servlet and jsp and I had the following setup:
public class DataManager {
//some method implementations omitted since they are not important
public DataManager(){}
public class Author{
public int id;
public String name;
public String born;
public String died;
}
public Author getAuthor(int authorId){}
public ArrayList<Author> getAuthors(){}
}
public class AuthorsServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletContext context = getServletContext();
DataManager dm = (DataManager) context.getAttribute("datamanager");
ArrayList<DataManager.Author> authors = dm.getAuthors();
request.setAttribute("authors", authors);
request.getRequestDispatcher("/authors.jsp").forward(request, response);
}
}
In my jsp file I had:
<c:forEach var="author" items="${authors}">
<tr>
<td>${author.id}</td>
<td><a href="author.jsp">${author.name}</a></td>
<td>${author.born}</td>
<td>${author.died}</td>
</tr>
</c:forEach>
However I kept getting an error that says Property 'id' not found on type db.DataManager$Author
until I put in getters in the inner Author
class of my DataManager
class:
public class Author{
public int id;
public String name;
public String born;
public String died;
public int getId(){ return id; }
public String getName(){ return name;}
public String getBorn(){return born; }
public String getDied(){ return died;}
}
I have two (kind of basic) questions:
Why do I have to add getters to access a public inner class's variables?
Even after I put in the getters, I didn't directly called them (i.e.
author.id
instead ofauthor.getId()
) is there a naming convention where the compiler follows, so I have to definegetFoo
to get the value of afoo
variable?