# Database URL
jdbc.url=jdbc:mysql://192.168.0.25"3306/db
# Database login information
jdbc.username=root
jdbc.password=
# Time to wait for an open connection before timing out
# (in milliseconds)
cpool.checkoutTimeout=5000
# Connection pool size
cpool.minPoolSize=5
cpool.maxPoolSize=40
# How long to keep unused connections around(in seconds)
# Note: MySQL times out idle connections after 8 hours(28,800 seconds)
# so ensure this value is below MySQL idle timeout
cpool.maxIdleTime=25200
# How long to hang on to excess unused connections after traffic spike
# (in seconds)
cpool.maxIdleTimeExcessConnections=1800
# Acquiring new connections is slow, so eagerly retrieve extra connections
# when current pool size is reached
cpool.acquireIncrement=5
或者將上面的3部分寫成一個:
<bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass">
<value>${jdbc.driverClassName}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<property name="initialPoolSize"><value>10</value></property>
<property name="minPoolSize"><value>5</value></property>
<property name="maxPoolSize"><value>30</value></property>
<property name="acquireIncrement"><value>5</value></property>
<property name="maxIdleTime"><value>10</value></property>
<property name="maxStatements"><value>0</value></property>
</bean>
如果使用的是受管理的J2EE服務器,則在spring中配置為JNDI連接:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jndi/xxx</value>
</property>
</bean>
如果在應用里有獨自使用hibernate,則在spring中配置hibernate連接池,使用C3P0如下:
<bean id="DataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@172.16.20.241:1521:dbsvr</value>
</property>
<property name="username">
<value>hl3000</value>
</property>
<property name="password">
<value>hldw3101</value>
</property>
</bean>
<bean id="SessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="DataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- C3P0連接池配置 -->
<prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.timeout">120</prop>
<prop key="hibernate.c3p0.max_statements">100</prop>
<prop key="hibernate.c3p0.idle_test_period">120</prop>
<prop key="hibernate.c3p0.acquire_increment">2</prop>
<prop key="myeclipse.connection.profile">hl3000</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/hl3000/DBLogic/POJO/PermUserAccount.hbm.xml</value>
</list>
</property>
</bean>
spring中配置獨立使用hibernate時使用jndi的配置:
hibernate.dialect = net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.datasource=java:comp/env/jdbc/SAMPLEDB
hibernate.show_sql=true
如果是使用不受管理的Servlet容器如Tomcat,也可以使用jndi的方式配置,需要在tomcat中配置數(shù)據(jù)源,在server.xml中增改大致如下:
<Resource name="jdbc/testDb" auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/testDB">\\數(shù)據(jù)源的名稱
<parameter><name>username</name><value>root</value></parameter>數(shù)據(jù)庫的名稱
<parameter><name>password</name><value>password</value></parameter>數(shù)據(jù)庫密碼
<parameter><name>driverClassName</name>
<value>org.gjt.mm.mysql.Driver</value></parameter>\\要加載的驅(qū)動
<parameter><name>url</name>
<value>jdbc:mysql://172.20.0.73/rk?</value></parameter>\\要連接的URL
</ResourceParams>
public class UpfileAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
DynaActionForm upfileForm = (DynaActionForm) form;// TODO Auto-generated method stub
Image image = new Image();
String strimgname = upfileForm.getString("filename");
image.setImgname(strimgname);
imageDAO.save(image);
FormFile filedata = (FormFile)upfileForm.get("filedata");
ServletContext servletContext = this.getServlet().getServletContext();
String filePath = servletContext.getRealPath("/");
try {
InputStream stream = filedata.getInputStream();
OutputStream bos = new FileOutputStream(filePath + "/image/" + filedata.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapping.findForward("ok");
}
private ImageDAO imageDAO;
public void setImageDAO(ImageDAO dao){
this.imageDAO = dao;
}
}
public class DisplayimgAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
List results = imageDAO.findAll();
if(results!=null){
HttpSession session=request.getSession();
session.setAttribute("results",results);
return mapping.findForward("ok");
}return mapping.findForward("fail");
}
private ImageDAO imageDAO;
public void setImageDAO(ImageDAO dao){
this.imageDAO = dao;
}
}
ImageDAO.java
public void save(Image transientInstance) {
Session session =this.getSession();
Transaction tx = null;
tx = session.beginTransaction();
session.save(transientInstance);
tx.commit();
session.evict(transientInstance);
}
public List findAll() {
Session session =this.getSession();
Query query = session.createQuery("from Image");
return query.list();
}
displayimg.jsp
<logic:iterate id="element" name="results">
<tr>
<td width="100"><bean:write name="element" property="id"/> </td>
<td width="100"><img src="image/<bean:write name='element' property='imgname'/>"/></td>
</tr>
</logic:iterate>
uploadfile.jsp
<html:form action="/upfile" enctype = "multipart/form-data">
filename : <html:text property="filename"/><html:errors property="filename"/><br/>
filedata : <html:file property="filedata"/><html:errors property="filedata"/><br/>
<html:submit/><html:cancel/>
</html:form>
<!-- u-f8 filter -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<logic:iterate id="element" name="results"> <tr>
<td width="100"><input type="checkbox" name="select" value="<bean:write name="element" property="id"/>"><bean:write name="element" property="id"/></td>
<td width="100"><bean:write name="element" property="name"/> </td>
<td width="100"><bean:write name="element" property="password"/></td>
</tr></logic:iterate>
顯示頁碼的代碼:
<%
int i;
int a=Integer.parseInt(session.getAttribute("amountPage").toString());
for (i=1;i<=a;i++){
out.println("<tr>");
out.println("<td><a href='display.do?pagenum="+ i +"'>"+ i +"</a></td>");
out.println("</tr>");
}
%>
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
然后調(diào)用:
Session session = sessionFactory.openSession();
Query query = session.createQuery("from Login");
類似這樣的單獨使用hibernate時的用法,是需要手工去關閉session的。沒有關閉的話就會收到那樣的警告。
所以最好是使用spring管理的session,和OpenSessionInViewFilter,比如:
Session session =this.getSession();
然后在web.xml里加入
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
其中在spring里注冊的sessionfactory必須是id="sessionFactory",如果是id="SessionFactory"或者其他,會提示sessionFactory沒有注冊的錯誤,因為OpenSessionInViewFilter里注冊的名必須為sessionFactory。