先說一點題外話,LZ最近學習java web。今天剛看到hibernate,發(fā)現(xiàn)在hibernate配置數(shù)據(jù)源時網(wǎng)上的資料都太久遠了,一般以tomcat 5 版本下的配置居多。而tomcat 7下的配置略有變化,新手找資料困難,可能會略受打擊,故整理資料與大家共享,也可作備忘之用!若有不當之處,還請不吝賜教!
1.添加數(shù)據(jù)庫驅動包mysql-connector-java-5.1.13-bin.jar加入到tomcat目錄下的lib包中。
注意:網(wǎng)上幾乎所有版本都說需要添加commons-dbcp-1.4.jar,commons-pool-1.5.4.jar和commons-collections.jar。
但是tomcat 7 已經(jīng)不用添加這些jar文件了,因為tomcat 7的lib包下面已經(jīng)集成了這些庫。
官方集成文檔上有:These libraries are located in a single JAR at$CATALINA_HOME/lib/tomcat-dbcp.jar.
大概意思就是:這些庫文件都位于一個單獨的JAR文件中,該文件的路徑是/lib/tomcat-dbcp.jar。
2.修改Tomcat_Home/conf/server.xml,標簽之前加入:
username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest"/>
3.在context.xml中加入引用
4.在你的工程項目的web.xml中加入
5.在hibernate.cfg.xml文件中配置數(shù)據(jù)庫連接,這個有很多教程,此處便不再詳述。
另外,注意數(shù)據(jù)源只有在web項目中才可以使用。
再次出來寫個簡單的servlet來輸出hibernate 的session對象:
代碼如下:
packagecom.amaker.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.hibernate.Session;
importcom.amaker.util.HibernateUtil;
@SuppressWarnings("serial")
publicclasstestServletextendsHttpServlet {
* Constructor of the object.
publictestServlet() {
super();
* Destruction of theservlet.
publicvoiddestroy() {
super.destroy();// Just puts "destroy" string in log
* The doGet method of theservlet.
* This method is called when a form has its tag value method equals to get.
*@paramrequest the request send by the client to the server
*@paramresponse the response send by the server to the client
*@throwsServletException if an error occurred
*@throwsIOException if an error occurred
publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
HibernateUtil util =newHibernateUtil();
//HibernateUtil 類用來返回一個Session
對象,很簡單,相信大家可以搞定。
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("
out.println("
");out.println("
");out.println("");
publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
doGet(request, response);
* Initialization of theservlet.
*@throwsServletException if an error occurs
publicvoidinit()throwsServletException {
}
訪問結果如圖,返回一個session對象。
原文地址:http://blog.csdn.net/canglangwenyue/article/details/25924735
Copyright ? 2019- 91gzw.com 版權所有 湘ICP備2023023988號-2
違法及侵權請聯(lián)系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市萬商天勤律師事務所王興未律師提供法律服務