在 Servlet 上调用 DAO 方法
Posted
技术标签:
【中文标题】在 Servlet 上调用 DAO 方法【英文标题】:Invoking a DAO method on a Servlet 【发布时间】:2014-09-19 02:46:43 【问题描述】:我正在制作网页,用户可以通过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
【问题讨论】:
嗯,创建 RentHibernateDao 对象,并调用适当的方法,根据需要返回 HTML。 【参考方案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
【讨论】:
以上是关于在 Servlet 上调用 DAO 方法的主要内容,如果未能解决你的问题,请参考以下文章
带有 JDBC 的 JSF 项目,我无法在 Servlet 上调用 DAO [重复]