在Servlet上调用DAO方法

时间:2014-07-27 22:39:21

标签: java hibernate jsp servlets dao

我正在制作网页,用户可以通过rentID搜索租用的产品,在Servlet中我想调用DAO方法根据该rentID查找租借的产品,并将用户重定向到新的网页是否找到租金。

这是用户按ID

搜索产品的JSP
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>Find Rent</h3><br>

<form  action="FindRent" method="GET">
<fieldset>
<p>
<label for="id">Rent ID</label>
<input type="text" name="id"/>
</p>
<p>
<input type="submit" value="Search" />
</p>
</fieldset>

</form>

</body>
</html>

这是DAO实施。

public class RentHibernateDao implements RentDao {

@Override
public void saveRent(Rent rent) {

    SessionFactory factory = 
            HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        session.getTransaction().begin();

         session.save(rent);

        session.getTransaction().commit();
        session.close();

}

@Override
public Rent find(Integer rentId) {
    SessionFactory factory = 
            HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        session.getTransaction().begin();

        Rent rent=(Rent)session.get(Rent.class, rentId);
        session.close();
    return rent;
}

@Override
public void EndRent(Integer rentId) {

    SessionFactory factory = 
            HibernateUtil.getSessionFactory();
        Session session = factory.openSession();

        session.getTransaction().begin();

        Rent rent=this.find(rentId);
        rent.setRealReturnDate(new Date());
        rent.getProduct().changeStatus();
        session.saveOrUpdate(rent);
        session.getTransaction().commit();
        session.close();


    }

这就是Servlet。我该如何调用该方法?

public class FindRent extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public Rent find() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

1 个答案:

答案 0 :(得分:1)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    int rentId= Integer.parseInt(request.getParameter("id"));       // capture the rent id
    RentDao dao= new RentHibernateDao();        // create the dao object
    dao.find(rentId);   // If successful, it returns you an object of Rent class
   // means Id is there
  // put your processing logic here
    request.getRequestDispatcher("desiredpage.jsp").forward(request, response);         // forward to your desired page

   }