首页 新闻 会员 周边 捐助

从csdn上找到的源码例子现在运行出问题

0
[已解决问题] 解决于 2016-05-18 16:48
  1 严重: Could not find datasource: java:/comp/env/jdbc/test
  2 javax.naming.NameNotFoundException: Name [jdbc/test] is not bound in this Context. Unable to find [jdbc].
  3     at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
  4     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
  5     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
  6     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
  7     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
  8     at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
  9     at org.apache.naming.SelectorContext.lookup(SelectorContext.java:156)
 10     at javax.naming.InitialContext.lookup(Unknown Source)
 11     at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)
 12     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
 13     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56)
 14     at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:385)
 15     at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:61)
 16     at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1928)
 17     at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1211)
 18     at shtest.hibernate.HibernateUtil.setupSessionFactory(HibernateUtil.java:61)
 19     at shtest.servlet.LauncherServlet.init(LauncherServlet.java:65)
 20     at javax.servlet.GenericServlet.init(GenericServlet.java:158)
 21     at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
 22     at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
 23     at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
 24     at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5253)
 25     at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5543)
 26     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
 27     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
 28     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
 29     at java.util.concurrent.FutureTask.run(Unknown Source)
 30     at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 31     at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 32     at java.lang.Thread.run(Unknown Source)
 33 
 34 五月 17, 2016 10:36:17 上午 shtest.hibernate.HibernateUtil setupSessionFactory
 35 严重: Building SessionFactory failed.
 36 org.hibernate.HibernateException: Could not find datasource
 37     at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:56)
 38     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
 39     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56)
 40     at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:385)
 41     at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:61)
 42     at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1928)
 43     at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1211)
 44     at shtest.hibernate.HibernateUtil.setupSessionFactory(HibernateUtil.java:61)
 45     at shtest.servlet.LauncherServlet.init(LauncherServlet.java:65)
 46     at javax.servlet.GenericServlet.init(GenericServlet.java:158)
 47     at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
 48     at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
 49     at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
 50     at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5253)
 51     at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5543)
 52     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
 53     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
 54     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
 55     at java.util.concurrent.FutureTask.run(Unknown Source)
 56     at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 57     at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 58     at java.lang.Thread.run(Unknown Source)
 59 Caused by: javax.naming.NameNotFoundException: Name [jdbc/test] is not bound in this Context. Unable to find [jdbc].
 60     at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
 61     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
 62     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
 63     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
 64     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
 65     at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
 66     at org.apache.naming.SelectorContext.lookup(SelectorContext.java:156)
 67     at javax.naming.InitialContext.lookup(Unknown Source)
 68     at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)
 69     ... 21 more
 70 
 71 org.hibernate.HibernateException: Could not find datasource
 72     at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:56)
 73     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
 74     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56)
 75     at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:385)
 76     at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:61)
 77     at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1928)
 78     at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1211)
 79     at shtest.hibernate.HibernateUtil.setupSessionFactory(HibernateUtil.java:61)
 80     at shtest.servlet.LauncherServlet.init(LauncherServlet.java:65)
 81     at javax.servlet.GenericServlet.init(GenericServlet.java:158)
 82     at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
 83     at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
 84     at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
 85     at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5253)
 86     at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5543)
 87     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
 88     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
 89     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
 90     at java.util.concurrent.FutureTask.run(Unknown Source)
 91     at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 92     at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 93     at java.lang.Thread.run(Unknown Source)
 94 Caused by: javax.naming.NameNotFoundException: Name [jdbc/test] is not bound in this Context. Unable to find [jdbc].
 95     at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
 96     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
 97     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
 98     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
 99     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
100     at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
101     at org.apache.naming.SelectorContext.lookup(SelectorContext.java:156)
102     at javax.naming.InitialContext.lookup(Unknown Source)
103     at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)
104     ... 21 more
105 五月 17, 2016 10:36:17 上午 org.apache.catalina.core.ApplicationContext log
106 严重: StandardWrapper.Throwable
107 java.lang.ExceptionInInitializerError
108     at shtest.hibernate.HibernateUtil.setupSessionFactory(HibernateUtil.java:68)
109     at shtest.servlet.LauncherServlet.init(LauncherServlet.java:65)
110     at javax.servlet.GenericServlet.init(GenericServlet.java:158)
111     at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
112     at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
113     at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
114     at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5253)
115     at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5543)
116     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
117     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
118     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
119     at java.util.concurrent.FutureTask.run(Unknown Source)
120     at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
121     at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
122     at java.lang.Thread.run(Unknown Source)
123 Caused by: org.hibernate.HibernateException: Could not find datasource
124     at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:56)
125     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
126     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56)
127     at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:385)
128     at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:61)
129     at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1928)
130     at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1211)
131     at shtest.hibernate.HibernateUtil.setupSessionFactory(HibernateUtil.java:61)
132     ... 14 more
133 Caused by: javax.naming.NameNotFoundException: Name [jdbc/test] is not bound in this Context. Unable to find [jdbc].
134     at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
135     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
136     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
137     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
138     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
139     at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
140     at org.apache.naming.SelectorContext.lookup(SelectorContext.java:156)
141     at javax.naming.InitialContext.lookup(Unknown Source)
142     at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)
143     ... 21 more
144 
145 五月 17, 2016 10:36:17 上午 org.apache.catalina.core.StandardContext loadOnStartup
146 严重: Servlet [launcher] in web application [/Struts2_Hibernate_Test] threw load() exception
147 javax.naming.NameNotFoundException: Name [jdbc/test] is not bound in this Context. Unable to find [jdbc].
148     at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
149     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
150     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
151     at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
152     at org.apache.naming.NamingContext.lookup(NamingContext.java:830)
153     at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
154     at org.apache.naming.SelectorContext.lookup(SelectorContext.java:156)
155     at javax.naming.InitialContext.lookup(Unknown Source)
156     at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)
157     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
158     at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:56)
159     at org.hibernate.cfg.SettingsFactory.createConnectionProvider(SettingsFactory.java:385)
160     at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:61)
161     at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1928)
162     at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1211)
163     at shtest.hibernate.HibernateUtil.setupSessionFactory(HibernateUtil.java:61)
164     at shtest.servlet.LauncherServlet.init(LauncherServlet.java:65)
165     at javax.servlet.GenericServlet.init(GenericServlet.java:158)
166     at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
167     at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
168     at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
169     at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5253)
170     at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5543)
171     at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
172     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574)
173     at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564)
174     at java.util.concurrent.FutureTask.run(Unknown Source)
175     at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
176     at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
177     at java.lang.Thread.run(Unknown Source)
178 
179 五月 17, 2016 10:36:17 上午 org.apache.coyote.AbstractProtocol start
180 信息: Starting ProtocolHandler ["http-bio-8080"]
181 五月 17, 2016 10:36:17 上午 org.apache.coyote.AbstractProtocol start
182 信息: Starting ProtocolHandler ["ajp-bio-8009"]
183 五月 17, 2016 10:36:17 上午 org.apache.catalina.startup.Catalina start
184 信息: Server startup in 2813 ms
185 五月 17, 2016 10:36:59 上午 org.apache.catalina.core.StandardWrapperValve invoke
186 严重: Servlet.service() for servlet [default] in context with path [/Struts2_Hibernate_Test] threw exception
187 java.lang.IllegalStateException: SessionFactory not available.
188     at shtest.hibernate.HibernateUtil.getSessionFactory(HibernateUtil.java:102)
189     at shtest.servlet.HibernateFilter.doFilter(HibernateFilter.java:41)
190     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
191     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
192     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
193     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
194     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
195     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
196     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
197     at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
198     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
199     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
200     at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
201     at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
202     at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
203     at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
204     at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
205     at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
206     at java.lang.Thread.run(Unknown Source)
报错日志
 1 <%@ page contentType="text/html; charset=UTF-8" %>
 2 <%@ page import="java.util.List" %>
 3 <%@ page import="java.util.ArrayList" %>
 4 <%@ taglib prefix="s" uri="/struts-tags" %>
 5 
 6 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 7 <%
 8     List<String> list = new ArrayList<String>();
 9     list.add("Max");
10     list.add("Scott");
11     list.add("Jeffry");
12     list.add("Joe");
13     list.add("Kelvin");
14     request.setAttribute("names", list);
15 %>
16 <html>
17     <head>
18         <title>Iterator Tag Test</title>
19     </head>
20     <body>
21       <h3>Iterator Tag Test</h3>
22         <h3>Names: </h3>
23         <!-- 
24             1、此处的空property元素用于获得当前iterator的值 
25             2、status被设成stuts,在iterator的里面就可以通过#stuts取得IteratorStatus的对象。IteratorStatus类包含当前序号信息,如是否第一个或最后一个,是否为奇数序号。这些信息在我们做格式化的时候,显得非常有用。
26         -->
27         <ol>
28             <s:iterator value="#request.names" status="stuts">                
29                 <s:if test="#stuts.odd == true">
30                     <li>White <s:property /></li>
31                 </s:if>
32                 <s:else>
33                     <li style="background-color:gray"><s:property /></li>
34                 </s:else>
35             </s:iterator>
36         </ol>
37     </body>
38 </html>
iteratortagtest.jsp
 1 <%@ page language="java" contentType="text/html; charset=utf-8"%>
 2 <%@ taglib prefix="s" uri="/struts-tags"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>查看用户信息</title>
 8 <script language="javascript">
 9 
10 </script language="javascript">
11 </head>
12 <body>
13 <h1>以下是用户信息</h1>
14 <table width="60%" border="1" >
15     <tr>
16         <th>id</th>
17         <th>account</th>
18         <th>name</th>
19         <th>active</th>
20         <th>edit</th>
21         <th>delete</th>
22     </tr>
23     <s:iterator value="users"  status="stuts"><!-- 此处自动调用ViewUserAction.getUsers()方法-->
24     <s:if test="#stuts.odd == true">
25          <tr bgcolor="#35FF68">
26     </s:if>
27      <s:else>
28      <tr bgcolor="#B9EA99"> 
29      </s:else>
30             <td><s:property value="id" /></td>
31             <td><s:property value="account" /></td>
32             <td><s:property value="name" /></td>
33             <td><s:property value="active" /></td>
34             <td><a href="loaduser.action?id=<s:property value="id" />" >编辑</a></td>
35 
36             <td><a href="deleteuser.action?id=<s:property value="id"/>" >删除</a></td>
37         </tr>
38     </s:iterator>
39 </table>
40 <br>
41 <h2><a href="adduser.jsp">增加新用户</a></h2>
42 </body>
43 </html>
listusers.jsp
 1 <%@ page language="java" contentType="text/html; charset=utf-8"%>
 2 <%@ taglib prefix="s" uri="/struts-tags"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>操作成功</title>
 8 </head>
 9 <body>
10 
11 <h1> successful !</h1>
12 <h2><a href="listusers.action" target="_parent">返回</a></h2>
13 
14 </body>
15 </html>
success.jsp
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5 <title>Struts2_DBTest</title>
 6 </head>
 7 <body>
 8 <h1>Struts2 + Hibernate Operating Test</h1>
 9 <h2><a href="listusers.action" target="_parent">view users infomation</a></h2>
10 <h2><a href="iteratortagtest.jsp" target="_parent">Iterator Tag test</a></h2>
11 </body>
12 </html>
index.html
 1 <%@ page language="java" contentType="text/html; charset=utf-8"%>
 2 <%@ taglib prefix="s" uri="/struts-tags"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>操作失败</title>
 8 </head>
 9 <body>
10 
11 <h1> fail !</h1>
12 <h2><a href="listusers.action" target="_parent">返回</a></h2>
13 
14 </body>
15 </html>
error.jsp
 1 <%@ page language="java" contentType="text/html; charset=utf-8"%>
 2 <%@ taglib prefix="s" uri="/struts-tags" %>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>修改用户信息</title>
 8 </head>
 9 <body>
10 <h1>用户信息</h1>
11 <s:form action="edituser">
12 <table width="240" border="1">
13 <tr> <td align="left" valign="middle" width="40%"><s:textfield name="user.id" label="id" readonly="true"/> </td>    </tr>
14 <tr> <td align="left" valign="middle" width="40%"><s:textfield name="user.account" label="account" readonly="true"/> </td></tr>
15 <tr> <td align="left" valign="middle" width="40%"><s:textfield name="user.name" label="name"/> </td></tr>
16 <tr>  <td align="left" valign="middle" width="40%"> <s:checkbox label="活动用户" name="user.active" fieldValue="true"/> </td></tr>
17 
18 <tr><td align="center"><s:submit value="更新" /></td></tr>
19 </table>
20 </s:form>
21 </body>
22 </html>
edituser.jsp
 1 <%@ page language="java" contentType="text/html; charset=utf-8"%>
 2 <%@ taglib prefix="s" uri="/struts-tags" %>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>增加新用户</title>
 8 <script language="javascript">
 9 
10 //简单的检测
11 function checkForm(f)
12 {
13    if(f.account.value == "")
14     {
15             alert("账号不能为空!");
16             f.account.focus();
17                 return false;
18         }    
19     if(f.name.value == "")
20     {
21         alert("真实姓名不能为空!");
22         f.name.focus();
23             return false;
24     }        
25         return true;
26 }
27 </script language="javascript">
28 
29 </head>
30 <body>
31 <h1>新用户信息</h1>
32 <s:form action="adduser" onsubmit="return checkForm(this);">
33 <table width="240" border="1">
34 <tr><td><s:textfield name="user.account" label="account" id="account"/> </td></tr>
35 <tr><td><s:textfield name="user.name" label="name" id="name"/> </td></tr>
36 
37 <tr><td><s:submit value="增加" /></td></tr>
38 </table>
39 </s:form>
40 </body>
41 </html>
adduser.jsp
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 3     <display-name>Struts2_Hibernare_Test</display-name>
 4     <servlet>
 5     <!-- 网站启动时,先导入网站配置类  -->
 6         <servlet-name>launcher</servlet-name>
 7         <servlet-class>shtest.servlet.LauncherServlet</servlet-class>
 8         <load-on-startup>1</load-on-startup>
 9     </servlet>
10     
11     <filter>
12         <filter-name>hibernateFilter</filter-name>
13         <filter-class>shtest.servlet.HibernateFilter</filter-class>
14     </filter>
15 
16     <filter-mapping>
17         <filter-name>hibernateFilter</filter-name>
18         <url-pattern>/*</url-pattern>
19     </filter-mapping>
20     
21     <filter>
22         <filter-name>struts2</filter-name>
23         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
24     </filter>
25     
26     <filter-mapping>
27         <filter-name>struts2</filter-name>
28         <url-pattern>/*</url-pattern>
29     </filter-mapping>
30     
31 
32     
33     <welcome-file-list>
34         <welcome-file>index.html</welcome-file>
35         <welcome-file>index.jsp</welcome-file>
36     </welcome-file-list>
37 </web-app>
web.xml
  1 /**
  2  * @author qiaoger 2009-5-16
  3  * @author qiaoger@126.com
  4  */
  5 package shtest.action;
  6 
  7 
  8 import java.util.List;
  9 
 10 import com.opensymphony.xwork2.ActionSupport;
 11 
 12 import shtest.User;
 13 import shtest.dao.DBUtil;
 14 import shtest.dao.UserDAO;
 15 
 16 public class UserAction extends ActionSupport {
 17     private int id;
 18     private String account;
 19     private String name;
 20     private boolean active;
 21     private User user;
 22     private List<User> users;
 23     private UserDAO userDAO =  DBUtil.getDAOManager().getUserDAO();
 24         
 25     /**
 26      * @return the id
 27      */
 28     public int getId() {
 29         return id;
 30     }
 31 
 32     /**
 33      * @param id the id to set
 34      */
 35     public void setId(int id) {
 36         this.id = id;
 37     }
 38     /**
 39      * @return the account
 40      */
 41     public String getAccount() {
 42         return account;
 43     }
 44     /**
 45      * @param account the account to set
 46      */
 47     public void setAccount(String account) {
 48         this.account = account;
 49     }
 50     /**
 51      * @return the name
 52      */
 53     public String getName() {
 54         return name;
 55     }
 56     /**
 57      * @param name the name to set
 58      */
 59     public void setName(String name) {
 60         this.name = name;
 61     }
 62 
 63     /**
 64      * @return the active
 65      */
 66     public boolean isActive() {
 67         return active;
 68     }
 69     /**
 70      * @param active the active to set
 71      */
 72     public void setActive(boolean active) {
 73         this.active = active;
 74     }
 75     /**
 76      * @return the user
 77      */
 78     public User getUser() {
 79         return user;
 80     }
 81 
 82     /**
 83      * @param user the user to set
 84      */
 85     public void setUser(User user) {
 86         this.user = user;
 87     }
 88 
 89     /**
 90      * @return the users
 91      */
 92     public List<User> getUsers() {
 93         return users;
 94     }
 95 
 96     /**
 97      * @param users the users to set
 98      */
 99     public void setUsers(List<User> users) {
100         this.users = users;
101     }
102     
103     /**
104      * 增加新用户
105      * @return
106      */
107     public String add(){
108         if(userDAO.addUser(user)){
109             return SUCCESS;
110         }
111         return ERROR;
112     }
113     /**
114      * 删除一个用户
115      * @return
116      */
117     public String remove(){
118         if(userDAO.deleteUser(user)){
119             return SUCCESS;
120         }
121         else
122             return ERROR;
123     }
124     /**
125      * 获取一个用户
126      * @return
127      */
128     public String load() {
129            user = userDAO.getUserById(id);
130            if(null != user)
131                return SUCCESS;
132            else
133                return ERROR;
134         }
135     
136      public String modify() {
137             if(userDAO.modifyUser(user)){
138                 return SUCCESS;
139             }else
140             return ERROR;
141         }
142     /**
143      * 获取一些用户
144      * @return
145      * @throws Exception
146      */
147     public String list() throws Exception{
148         users = userDAO.getPartOfManager(0, 10);
149         return SUCCESS;
150     }
151 }
View Code
 1 /**
 2  * @author qiaoger 2009-5-16
 3  * @author qiaoger@126.com
 4  * 
 5  */
 6 package shtest.dao;
 7 
 8 /**
 9  * DAO管理工具类
10  * @author qiaoger
11  * @author qiaoger@126.com
12  * @version 2009-5-16
13  *
14  */
15 
16 public class DAOManager {
17     private static DAOManager instance = null;
18     private UserDAO userDAO;
19     //这里申明所有DAO
20     
21     /**
22      * @return the userDAO
23      */
24     public UserDAO getUserDAO() {
25         return userDAO;
26     }
27     /**
28      * @param userDAO the userDAO to set
29      */
30     public void setUserDAO(UserDAO userDAO) {
31         this.userDAO = userDAO;
32     }
33     /**
34      * 使用private 禁止其它类创建该类
35      */
36     private DAOManager(){
37         //这里要事先创建所有的DAO
38         userDAO = new UserDAO();
39     }
40     /**
41      * 获取一个DAOManager工具类
42      * @return DAOManager
43      */
44     public static DAOManager getInstance(){
45         if(instance == null ){
46             instance = new DAOManager();
47         }
48         return instance;
49     }
50 }
DAOManager.java
 1 /**
 2  * @author qiaoger 2009-10-05
 3  * @author qiaoger@126.com
 4  */
 5 package shtest.dao;
 6 
 7 import java.sql.Connection;
 8 import java.sql.ResultSet;
 9 import java.sql.SQLException;
10 import java.sql.Statement;
11 
12 /**
13  * 
14  * 数据库工具类简单实现。
15  * 
16  * @author qiaoger 2009-5-16
17  */
18 public class DBUtil {
19     
20     
21     /**
22      * 获取DAO管理工具
23      * @return  DAOManager DAO管理类
24      */
25     public static DAOManager  getDAOManager(){
26         return DAOManager.getInstance();
27     }
28 
29 }
DBUtil.java
  1 /**
  2  * @author qiaoger 2009-10-05
  3  * @author qiaoger@126.com
  4  */
  5 
  6 package shtest.dao;
  7 
  8 
  9 import java.util.List;
 10 
 11 import shtest.User;
 12 
 13 import shtest.hibernate.HibernateDAO;
 14 
 15 /**
 16  * @author qiaoger
 17  *
 18  */
 19 public class UserDAO extends HibernateDAO {
 20 
 21     /**
 22      * 根据id获取用户
 23      * 
 24      * @author qiaoger
 25      * @param id
 26      *            用户编号
 27      * @return User对像
 28      **/
 29     public User getUserById(int id) {
 30         return (User)getObject(User.class, id);
 31     }
 32 
 33     /**
 34      * 获取一些用户
 35      * 
 36      * @param offset 起始记录
 37      * @param limit  最大记录数
 38      * @return  记录集
 39      * @throws Exception
 40      */
 41     public List<User> getPartOfManager(int offset, int limit)  {
 42         String hsql = "from User " ;
 43         return  getObjects(hsql,offset,limit);  
 44     }
 45 
 46     /**
 47      * 增加新用户
 48      * 
 49      * @param user 
 50      * @return true or false
 51      * @throws  
 52      */
 53     public boolean addUser(User user)  {
 54         if(user == null ){
 55             return false;
 56         }
 57         if( isUserExist(user.getAccount())){
 58             throw new RuntimeException("该账户名已经存在,请使用其他账户名!");
 59         }
 60         saveObject(user);
 61         return true;
 62     }
 63 
 64     /**
 65      * 查找用户存在与否
 66      * 
 67      * @param account 账号
 68      * @return 如果存在 返回true 否则 返回false
 69      */
 70     public boolean isUserExist(String account) {
 71         if (account == null || account.trim().equals("")) {
 72             return false;
 73         }
 74 
 75         account = account.trim();
 76 
 77         User u = (User)getObject("from User u where u.account= '"+account+"'");
 78         if(u != null)
 79             return true;
 80         else
 81             return false;
 82     }
 83 
 84     /**
 85      * 删除用户
 86      * 
 87      * @param id
 88      * @return
 89      */
 90     public boolean deleteUser(User user) {
 91         
 92         deleteObject(user);
 93         
 94         return true;
 95     }
 96 /**
 97  * 修改用户信息
 98  * @param user
 99  * @return
100  */
101     public boolean modifyUser(User user) {
102         updateObject(user);
103         return true;
104     }
105 }
UserDAO.java
 1 /**
 2  * @author qiaoger 2009-5-16
 3  * @author qiaoger@126.com
 4  */
 5 package shtest.exception;
 6 
 7 /**
 8  * @author qiaoger 每个站点都应设计一个专门的异常类
 9  * 
10  */
11 public class WebException extends Exception {
12     public WebException() {
13         super();
14     }
15 
16     public WebException(String message) {
17         super(message);
18     }
19 
20     public WebException(String message, Throwable cause) {
21         super(message, cause);
22     }
23 }
WebException.java
 1 package shtest.hibernate;
 2 
 3 import java.util.List;
 4 
 5 import org.hibernate.Session;
 6 import org.hibernate.Transaction;
 7 
 8 /**
 9  * 使用Hibernate实现DAO的基础类
10  * 包括了持久化操作的一些基础方法
11  */
12 public class HibernateDAO {
13 
14     public Session getCurrentSession() {
15         return HibernateUtil.getSessionFactory().getCurrentSession();
16     }
17 
18     /**
19      * 保存对象信息到数据库
20      * @param obj 需要进行持久化操作的对象
21      */
22     public void saveObject(Object obj) {
23         getCurrentSession().save(obj);
24     }
25 
26     /**
27      * 更新持久化对象
28      * @param obj 需要更新的对象
29      */
30     public void updateObject(Object obj) {
31         getCurrentSession().update(obj);
32     }
33 
34     /**
35      * 使用HQL语句进行查询
36      * @param hsql 查询语句
37      * @return 符合条件的对象集合
38      */
39     public List getObjects(String hsql) {
40         List result = getCurrentSession().createQuery(hsql).list();
41         return result;
42     }
43     /**
44      * 使用HQL语句进行分段查询
45      * @param hsql 查询语句
46      * @param offset 起始记录
47      * @param limit 记录数量
48      * @return 符合条件的对象集合
49      */
50     public List getObjects(String hsql,int offset,int limit) {
51         List result = getCurrentSession().createQuery(hsql).setFirstResult(offset).setMaxResults(limit).list();
52         return result;
53     }
54 
55     /**
56      * 使用HQL语句进行对象的查询
57      * @param hsql 查询语句
58      * @return 符合条件的对象
59      */
60     public Object getObject(String hsql) {
61         Object result = getCurrentSession().createQuery(hsql).uniqueResult();
62         return result;
63     }
64 
65     /**
66      * 根据ID值得到持久化的对象
67      * @param cls 对象的类型
68      * @param id ID值
69      * @return 指定ID的对象
70      */
71     public Object getObject(Class cls, int id) {
72         Object result = getCurrentSession().get(cls, id);
73         return result;
74     }
75 
76     /**
77      * 删除对象信息
78      * @param obj 被删除的对象
79      */
80     public void deleteObject(Object obj) {
81         getCurrentSession().delete(obj);
82     }
83 
84 }
HibernateDAO.java
  1 package shtest.hibernate;
  2 
  3 import javax.naming.InitialContext;
  4 import javax.naming.NamingException;
  5 
  6 import org.apache.commons.logging.Log;
  7 import org.apache.commons.logging.LogFactory;
  8 import org.hibernate.Interceptor;
  9 import org.hibernate.SessionFactory;
 10 import org.hibernate.cfg.Configuration;
 11 import org.hibernate.cfg.Environment;
 12 
 13 /**
 14  * 基础的Hibernate辅助类,用于Hibernate的配置和启动。
 15  * <p>
 16  * 通过静态的初始化代码来读取Hibernate启动参数,并初始化 <tt>Configuration</tt>和
 17  * <tt>SessionFactory</tt>对象。
 18  * <p>
 19  * 
 20  * @author galaxy
 21  */
 22 public class HibernateUtil {
 23 
 24     private static Log log = LogFactory.getLog(HibernateUtil.class);
 25 
 26     // 指定定义拦截器属性名
 27     private static final String INTERCEPTOR_CLASS = "hibernate.util.interceptor_class";
 28 
 29     // 静态Configuration和SessionFactory对象的实例(全局唯一的)
 30     private static Configuration configuration;
 31     private static SessionFactory sessionFactory;
 32 
 33     public static boolean setupSessionFactory() {// 从缺省的配置文件创建SessionFactory
 34 
 35         try {
 36             // 创建默认的Configuration对象的实例
 37             // 如果你不使用JDK 5.0或者注释请使用new Configuration()
 38             // 来创建Configuration()对象的实例
 39         
 40             configuration = new Configuration();
 41 
 42             // 读取hibernate.properties或者hibernate.cfg.xml文件
 43             configuration.configure();
 44 
 45             // 如果在配置文件中配置了拦截器,那么将其设置到configuration对象中
 46             String interceptorName = configuration
 47                     .getProperty(INTERCEPTOR_CLASS);
 48             if (interceptorName != null) {
 49                 Class interceptorClass = HibernateUtil.class.getClassLoader()
 50                         .loadClass(interceptorName);
 51                 Interceptor interceptor = (Interceptor) interceptorClass
 52                         .newInstance();
 53                 configuration.setInterceptor(interceptor);
 54             }
 55 
 56             if (configuration.getProperty(Environment.SESSION_FACTORY_NAME) != null) {
 57                 // 让Hibernate将SessionFacory绑定到JNDI
 58                 configuration.buildSessionFactory();
 59             } else {
 60                 // 使用静态变量来保持SessioFactory对象的实例
 61                 sessionFactory = configuration.buildSessionFactory();
 62             }
 63 
 64         } catch (Throwable ex) {
 65             // 输出异常信息
 66             log.error("Building SessionFactory failed.", ex);
 67             ex.printStackTrace();
 68             throw new ExceptionInInitializerError(ex);
 69         }
 70         return true;
 71     }
 72 
 73     /**
 74      * 返回原始的Configuration对象的实例
 75      * 
 76      * @return Configuration
 77      */
 78     public static Configuration getConfiguration() {
 79         return configuration;
 80     }
 81 
 82     /**
 83      * 返回全局的SessionFactory对象的实例
 84      * 
 85      * @return SessionFactory
 86      */
 87     public static SessionFactory getSessionFactory() {
 88         SessionFactory sf = null;
 89         String sfName = configuration
 90                 .getProperty(Environment.SESSION_FACTORY_NAME);
 91         if (sfName != null) {
 92             log.debug("Looking up SessionFactory in JNDI.");
 93             try {
 94                 sf = (SessionFactory) new InitialContext().lookup(sfName);
 95             } catch (NamingException ex) {
 96                 throw new RuntimeException(ex);
 97             }
 98         } else {
 99             sf = sessionFactory;
100         }
101         if (sf == null)
102             throw new IllegalStateException("SessionFactory not available.");
103         return sf;
104     }
105 
106     /**
107      * 关闭当前的SessionFactory并且释放所有的资源
108      */
109     public static void shutdown() {
110         log.debug("Shutting down Hibernate.");
111         // Close caches and connection pools
112         getSessionFactory().close();
113 
114         // Clear static variables
115         configuration = null;
116         sessionFactory = null;
117     }
118 
119     /**
120      * 使用静态的Configuration对象来重新构建SessionFactory。
121      */
122     public static void rebuildSessionFactory() {
123         log.debug("Using current Configuration for rebuild.");
124         rebuildSessionFactory(configuration);
125     }
126 
127     /**
128      * 使用指定的Configuration对象来重新构建SessionFactory对象。
129      * 
130      * @param cfg
131      */
132     public static void rebuildSessionFactory(Configuration cfg) {
133         log.debug("Rebuilding the SessionFactory from given Configuration.");
134         synchronized (sessionFactory) {
135             if (sessionFactory != null && !sessionFactory.isClosed())
136                 sessionFactory.close();
137             if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null)
138                 cfg.buildSessionFactory();
139             else
140                 sessionFactory = cfg.buildSessionFactory();
141             configuration = cfg;
142         }
143     }
144 
145     /**
146      * 在当前SessionFactory中注册一个拦截器
147      */
148     public static SessionFactory registerInterceptorAndRebuild(
149             Interceptor interceptor) {
150         log.debug("Setting new global Hibernate interceptor and restarting.");
151         configuration.setInterceptor(interceptor);
152         rebuildSessionFactory();
153         return getSessionFactory();
154     }
155 
156     /**
157      * 获得拦截器对象
158      * 
159      * @return Interceptor
160      */
161     public static Interceptor getInterceptor() {
162         return configuration.getInterceptor();
163     }
164 
165     /**
166      * 提交当前事务,并开始一个新的事务
167      */
168     public static void commitAndBeginTransaction() {
169         sessionFactory.getCurrentSession().getTransaction().commit();
170         sessionFactory.getCurrentSession().beginTransaction();
171     }
172 }
HibernateUtil.java
 1 package shtest.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12 
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15 import org.hibernate.SessionFactory;
16 
17 import shtest.hibernate.HibernateUtil;
18 
19 
20 
21 
22 /**
23  * 用于进行Hibernate事务处理的Servlet过滤器
24  *
25  * @author galaxy
26  */
27 public class HibernateFilter implements Filter {
28 
29     private static Log log = LogFactory.getLog(HibernateFilter.class);
30 
31     /**
32      * 过滤器的主要方法
33      * 用于实现Hibernate事务的开始和提交
34      */
35     public void doFilter(ServletRequest request,
36                          ServletResponse response,
37                          FilterChain chain)
38             throws IOException, ServletException 
39     {
40         // 得到SessionFactory对象的实例
41         SessionFactory sf = HibernateUtil.getSessionFactory();
42 
43         try 
44         {
45             // 开始一个新的事务
46             log.debug("Starting a database transaction");
47             sf.getCurrentSession().beginTransaction();
48 
49             log.debug( "Request Path:\t" + ((HttpServletRequest)request).getServletPath() );
50             // Call the next filter (continue request processing)
51             chain.doFilter(request, response);
52 
53             // 提交事务
54             log.debug("Committing the database transaction");
55             sf.getCurrentSession().getTransaction().commit();
56 
57         } 
58         catch (Throwable ex) 
59         {
60             ex.printStackTrace();
61             try 
62             {
63                 // 回滚事务
64                 log.debug("Trying to rollback database transaction after exception");
65                 sf.getCurrentSession().getTransaction().rollback();
66             } 
67             catch (Throwable rbEx) 
68             {
69                 log.error("Could not rollback transaction after exception!", rbEx);
70             }
71 
72             // 抛出异常
73             throw new ServletException(ex);
74         }
75     }
76 
77     /**
78      * Servlet过滤器的初始化方法
79      * 可以读取配置文件中设置的配置参数
80      */
81     public void init(FilterConfig filterConfig) throws ServletException {}
82 
83     /**
84      * Servlet的销毁方法
85      * 用于释放过滤器所申请的资源
86      */
87     public void destroy() {}
88 
89 }
HibernateFilter.java
 1 /**
 2  * @author qiaoger 2009-10-05
 3  * @author qiaoger@126.com
 4  */
 5 package shtest.servlet;
 6 
 7 import java.io.FileInputStream;
 8 import java.io.InputStream;
 9 import java.util.Properties;
10 
11 import javax.servlet.ServletException;
12 import javax.servlet.http.HttpServlet;
13 
14 import shtest.exception.WebException;
15 import shtest.hibernate.HibernateUtil;
16 
17 
18 
19 /**
20  * @author qiaoger 2009-10-05 网站配置工具类 负责 初始化配置 网站关闭处理
21  */
22 
23 public class LauncherServlet extends HttpServlet {
24     public void init() throws ServletException {
25         super.init();
26         InputStream is = null;
27         try {
28             System.err.println("开始启动Struts2_Hibernate_Test测试网站......");
29             // 这里可以进行一些初始化的操作
30             System.err.println("进行初始化操作:");
31             System.err.println("读取配置文件示例:");
32             // *******************以下进行简单的读取配置文件示例操作********************************
33             try {
34                 String path = this.getServletContext().getRealPath(
35                         "WEB-INF/web.properties");
36                 is = new FileInputStream(path);
37                 if (is == null)
38                     throw new WebException("不能打开web.properties");
39                 Properties p = new Properties();
40                 p.load(is);
41                 String web_name = p.getProperty("web_name");
42                 String author = p.getProperty("author");
43                 String date = p.getProperty("date");
44                 System.err.println("-----以下是配置文件web.properties信息:-----");
45                 System.err.println("网站名称:" + web_name);
46                 System.err.println("作者:" + author);
47                 System.err.println("日期:" + date);
48                 System.err.println("-----------------------------------------");
49             } catch (Exception e) {
50                 e.printStackTrace();
51 
52                 throw new ServletException(e);
53             } finally {
54                 if (is != null)
55                     try {
56                         is.close();
57                     } catch (Exception e) {
58                     }
59             }
60             // *******************************************************************
61             
62             System.err.println("使用Hibernate获取数据源(配置SessionFactory)....");
63             
64             //**************
65             if(HibernateUtil.setupSessionFactory()){
66             System.err.println("成功获取数据源,OK !");
67             System.err.println("初始化工作完毕,OK !");
68             }
69             else{
70                 System.err.println("获取数据源失败,Sorry !");
71             }
72         } catch (Exception e) {
73             e.printStackTrace();
74             throw new ServletException("Launch system error: " + e, e);
75         }
76     }
77 
78     public void destroy() {
79         System.out.println("准备关闭Struts2_Hibernate_Test网站......");
80         System.out.println("进行关闭前的清理操作(模拟)......");
81         
82         //加入关闭数据源的操作
83         System.out.println("关闭数据源(关闭当前的SessionFactory并且释放所有的资源)....");
84         HibernateUtil.shutdown();
85         
86         super.destroy();
87         
88         System.out.println("关闭成功  OK !");
89     }
90 }
LauncherServlet.java
 1 /**
 2  * 
 3  */
 4 package shtest;
 5 
 6 /**
 7  * @author qiaoger
 8  * 用户模型类
 9  */
10 public class User {
11     private int id; // id号
12     private String account; // 账号(唯一)
13     private String name;// 真实姓名
14     private boolean active; // 是否是活动帐户
15 
16     /**
17      * @return the id
18      */
19     public int getId() {
20         return id;
21     }
22 
23     /**
24      * @param id
25      *            the id to set
26      */
27     public void setId(int id) {
28         this.id = id;
29     }
30 
31     /**
32      * @return the account
33      */
34     public String getAccount() {
35         return account;
36     }
37 
38     /**
39      * @param account
40      *            the account to set
41      */
42     public void setAccount(String account) {
43         this.account = account;
44     }
45 
46     /**
47      * @return the name
48      */
49     public String getName() {
50         return name;
51     }
52 
53     /**
54      * @param name
55      *            the name to set
56      */
57     public void setName(String name) {
58         this.name = name;
59     }
60 
61     /**
62      * @return the active
63      */
64     public boolean isActive() {
65         return active;
66     }
67 
68     /**
69      * @param active
70      *            the active to set
71      */
72     public void setActive(boolean active) {
73         this.active = active;
74     }
75 
76 }
User.java
 1 <?xml version='1.0' encoding='UTF-8'?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 
 6 <hibernate-configuration>
 7 
 8     <session-factory>
 9     <!-- Hibernate使用JDBC配置 -->
10         <!-- 数据库的URL -->
11         <!-- property name="hibernate.connection.url">jdbc:oracle:thin:@192.168.10.121:1521:HiFinance</property-->
12         <property name="hibernate.connection.url">
13             jdbc:postgresql://localhost:5432/test?useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;autoReconnectForPools=true
14         </property>
15         
16         <!-- 数据库的驱动程序 -->
17     
18         <property name="hibernate.connection.driver_class">org.postgresql.Driver    </property>
19         <!-- 数据库的用户名 -->
20         <property name="hibernate.connection.username">test</property>
21         <!-- 数据库的密码 -->
22         <property name="hibernate.connection.password">123</property>
23         <!-- 数据库的Dialet -->
24         <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
25         <!-- 输出执行的SQL语句 -->
26         <property name="hibernate.show_sql">true</property>
27         
28         <property name="hibernate.current_session_context_class">thread</property >
29 
30         <!-- HBM文件列表 -->
31         <mapping resource="shtest/User.hbm.xml" />
32 
33     </session-factory>
34 
35 </hibernate-configuration>
复件 hibernate.cfg.xml
 1 <?xml version='1.0' encoding='UTF-8'?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 
 6 <hibernate-configuration>
 7 
 8     <session-factory>
 9     <!-- Hibernate使用JNDI(tomcat连接池)配置 -->
10    <property name="connection.datasource">java:/comp/env/jdbc/test</property>   
11  
12         <!-- 数据库的Dialet -->
13         <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
14         <!-- 输出执行的SQL语句 -->
15         <property name="hibernate.show_sql">true</property>
16         
17         <property name="hibernate.current_session_context_class">thread</property >
18 
19         <!-- HBM文件列表 -->
20         <mapping resource="shtest/User.hbm.xml" />
21 
22     </session-factory>
23 
24 </hibernate-configuration>
hibernate.cfg.xml
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 4     "http://struts.apache.org/dtds/struts-2.0.dtd">
 5 <struts>
 6     <include file="struts-default.xml" />
 7     <package name="dbtest" extends="struts-default">
 8 
 9         <action name="adduser" class="shtest.action.UserAction" method="add">
10             <result name="success" type="dispatcher">success.jsp</result>
11             <result name="error" type="dispatcher">error.jsp</result>
12         </action>
13         <action name="loaduser" class="shtest.action.UserAction" method="load">
14             <result name="success" type="dispatcher">edituser.jsp</result>
15             <result name="error" type="dispatcher">error.jsp</result>
16         </action>
17         <action name="edituser" class="shtest.action.UserAction" method="modify">
18             <result name="success" type="dispatcher">success.jsp</result>
19             <result name="error" type="dispatcher">error.jsp</result>
20         </action>
21         <action name="deleteuser" class="shtest.action.UserAction"
22             method="remove">
23             <result type="redirect">listusers.action</result>
24         </action>
25         <action name="listusers" class="shtest.action.UserAction"
26             method="list">
27             <result>listusers.jsp</result>
28         </action>
29 
30     </package>
31 
32 </struts>
struts.xml
cocoyoona的主页 cocoyoona | 初学一级 | 园豆:20
提问于:2016-05-17 10:57
< >
分享
最佳答案
0

说是没有找到数据源,是不是你的Hibernate配置错误了

 

还有就是,你这是用的什么数据库啊?

没有见过这个驱动,>_<

奖励园豆:5
NiceCatch90 | 初学一级 |园豆:72 | 2016-05-17 13:54

我也不懂...csdn找到的一个struts2+hibernate的例子

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 09:15

@眉间剪水泛千愁: 你现在用的是什么数据库?oracle?sql server?DB2?mysql?你告诉我你用的数据库,我才能帮你改一下!

O(∩_∩)O~

他上面这个数据库好像是一个很小型的数据库,不常见。我是没有见过!

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 09:47

@花落无声1991: mysql呀

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 09:48

你都会改...我看hibernate都看不懂

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 09:49

@眉间剪水泛千愁: 我最近才学的SSH(Struts2 + Spring + Hibernate)框架,这方面还是知道些许的!O(∩_∩)O~

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 09:50

@花落无声1991: 我刚学会点struts2,hibernate我真是不懂,现在映射差不多应该知道点了,但是用hibernate不是就不需要jdbc了么?不需要jdbc然后就茫然了Dao里就不知道怎么写

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 09:51

@眉间剪水泛千愁: hibernate是管理实体类与数据库的映射的(orm框架,object-relation-mapping),dao里面访问数据库可以直接调用hibernate的方法,或者是使用方法直接执行Hql & sql 语句进行数据库交互。

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 09:55

@眉间剪水泛千愁: 

DriverClass直接照抄下来,jdbc根据那个格式写一下数据库地址。

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:02

@花落无声1991: 也就是说使用hibernate之后,就不需要在写jdbc了,然后直接映射实体类呗.但是这样不写jdbc的话,Dao里面怎么写呢?

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:04

@花落无声1991: 你扣扣.我截图给你看这样子太慢啦宝宝

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:05

@眉间剪水泛千愁: 我们上班不让用丘丘,代理屏蔽了丘丘,嘿嘿。

Dao里面就是这样简单的实现了按照id来获得User实例化对象的,

里面的getObject()方法是继承的HibernateDAO里面的方法,应该是这样的,因为我使用的SSH框架和这个还有点不同,我那里是这样的

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:12

@花落无声1991: 还是不懂...我感觉就不理解这个东西了

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:14

@眉间剪水泛千愁: 

也可以是这样,

这个是我使用Spring管理SessionFactory之后,你看那个应该是早起的Hibernate里面的方法吧!我看的是最新的学习资料。

上面这个例子里面是直接使用的HQL(Hibernate自己的查询语言)来进行查询User类。

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:17

@花落无声1991: hibernate它自己不需要spring么?就是说如果我只用struts2+hibernate做,然后映射完成后需要写Dao,听他们说写dao还需要hibernate的工具类,但是hibernate的工具类又需要spring

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:20

@眉间剪水泛千愁: 你还是看看这方面的资料吧!要不然看代码会什么都不懂!我也是自学了两三个月了,才到这点程度,我给你一个系统,也是在CSDN上下载的,我现在感觉那个系统写的很全面。你的丘丘是多少?我直接发邮件给你。

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:21

@花落无声1991: 728699398..为什么叫丘丘而不是扣扣呢?

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:22

@眉间剪水泛千愁: 小孩子小的时候说话说不清楚,就说丘丘,我外甥经常这样说,咕~~(╯﹏╰)

网上面也有很多人这样说啊!你不知道!

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:25

@花落无声1991: 不晓得呢

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:25

@眉间剪水泛千愁: 发给你了!请接收!

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:40

@花落无声1991: 这就是你的丘丘邮箱哈?

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:41

@眉间剪水泛千愁: 对

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:41

@花落无声1991: 那我+你呐

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:42

@眉间剪水泛千愁: 恩,好的!

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:43

@花落无声1991: 发过去啦..

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:43

@眉间剪水泛千愁: 锦袖?

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:45

@花落无声1991: 不好听么?

cocoyoona | 园豆:20 (初学一级) | 2016-05-18 10:45

@眉间剪水泛千愁: 没有只是确认一下名字

NiceCatch90 | 园豆:72 (初学一级) | 2016-05-18 10:50
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册