Can anyone tell me where we should use pojo class and where we should use beans. We use pojo class to make the object of mapping file in hibernate framework. Can I use pojo class in those applications where I don't use any database and how ? Please give any example. Can I use pojo class in any simple application ? Can I use pojo class in struts application in which I don't use Hibernate.
Thanks in advance
Apart from Hibernate, you can use POJO class with JSP and Servlets also. Here is an example of POJO class which is connected to database and store data into arraylist. The Servlet class this POJO class and store the list into request object using setAttribute() method. This request is then send to jsp page. Using the getAttribute() method, the jsp page get the data and display it in the on the browser.
1)EmpBean.java:
package form; import java.sql.*; import java.util.*; public class EmpBean { public List dataList(){ ArrayList list=new ArrayList(); try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from employee"); while(rs.next()){ list.add(rs.getString("name")); list.add(rs.getString("address")); list.add(rs.getString("contactNo")); list.add(rs.getString("email")); } } catch(Exception e){} return list; } }
2)BeanInServlet.java:
import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class BeanInServlet extends HttpServlet{ protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ form.EmpBean p = new form.EmpBean(); List list=p.dataList(); req.setAttribute("data", list); RequestDispatcher rd = req.getRequestDispatcher("/jsp/beandata.jsp"); rd.forward(req, res); } }
3)beandata.jsp:
<%@page language="java" import="java.util.*" %> <html> <body> <table border="1" width="303"> <tr> <td width="119"><b>Name</b></td> <td width="168"><b>Address</b></td> <td width="119"><b>Contact no</b></td> <td width="168"><b>Email</b></td> </tr> <%Iterator itr;%> <% List data= (List)request.getAttribute("data"); for (itr=data.iterator(); itr.hasNext(); ){ %> <tr> <td width="119"><%=itr.next()%></td> <td width="168"><%=itr.next()%></td> <td width="168"><%=itr.next()%></td> <td width="168"><%=itr.next()%></td> </tr> <%}%> </table> </body> </html>