总论:在这一节我们要配置一个完整的应用配置。其实每一个单独拿出来都能写本书,不过我只是侧重对自己总结,在以后我会不断地把学习的经验教训写下来。
一,Log4j 的初始化
配置log4j.properties
log4j.logger.seerlog=DEBUG,A2
log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A2.file=d:\\log\\applog.txt
log4j.appender.A2.DatePattern='.'yyyy-MM-dd
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss} %m%n
#log4j.logger.ALL=DEBUG,A1
log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A1.file=d:\\log\\all.log
log4j.appender.A1.DatePattern='.'yyyy-MM-dd
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss} %l%n%m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
###log4j.rootLogger=warn, stdout
log4j.rootLogger=info, A1
#以下是hibernate API需要的配置
log4j.logger.net.sf.hibernate=info
### log just the SQL
#log4j.logger.net.sf.hibernate.SQL=debug
### log JDBC bind parameters ###
log4j.logger.net.sf.hibernate.type=info
### log schema export/update ###
log4j.logger.net.sf.hibernate.tool.hbm2ddl=debug
### log cache activity ###
#log4j.logger.net.sf.hibernate.cache=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.net.sf.hibernate.connection.DriverManagerConnectionProvider=trac
关于 log4j 的完全使用方法,偶会在以后做详细的说明!
二,hibernate 的初始化
首先我们要把hibernate.cfg.xml 放到应用的 classes 目录中,然后可以使用hibernate参考文档提供的例子来封装对后台的使用。
public class Hi{
private static final SessionFactory sessionFactory;
private static Connection conn;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("Exception building SessionFactory: " + ex.getMessage(), ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session getSession() throws HibernateException {
Session s = (Session) session.get();
// 假如没有一个可用的线程,开启一个新 Session,
if (s == null) {
conn=DBConnectionManager.getConnection();
s = sessionFactory.openSession(conn);
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
if(conn!=null)
DBConnectionManager.returnConnection(conn);
}
}
try{
//开启一个会话,并启动事务回滚能力
Session session = Hi.getSession();
Transaction tx= session.beginTransaction();
//查询数据库,使用HQL
Query q = session.createQuery("from Topic as topic order by topic.id desc");
q.setFirstResult(0);
q.setMaxResults(5);
//得到一个List类型的数据
List newTopicList = q.list();
// 业务处理
NewTopicList ntlBean=new NewTopicList();
ntlBean.setList(newTopicList);
req.setAttribute("newtopiclist",ntlBean);
//事务提交,记得关闭会话!
tx.commit();
Hi.closeSession();
}//因为整个会话会抛出异常,所以需要用try--catch来包裹
catch(HibernateException e){
//日志记录
Log.error(e.toString());
}
其中的HQL 可以参考 hibernate 官方文档来学习。
三,Struts
struts 的配置文件 struts-config.xml 放在 应用的 /WEB-INF/目录下面,大致的配置如下
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
<struts-config>
<form-beans>
<form-bean name="loginForm" type="net.seerlog.vo.LoginForm"/>
<form-bean name="replyForm" type="net.seerlog.vo.ReplyForm"/>
</form-beans>
<global-forwards>
<forward name="index" path="/first.jsp"/>
</global-forwards>
<action-mappings>
<action path="/login" type="net.seerlog.action.LoginAction" scope="request" name="loginForm" input="/login.jsp">
<forward name="success" path="/success.jsp"/>
</action>
<action path="/blog" type="net.seerlog.action.BlogAction" scope="request">
<forward name="success" path="/sublog.jsp"/>
</action>
<action path="/topic" type="net.seerlog.action.TopicAction" scope="request">
<forward name="success" path="/sutopic.jsp"/>
</action>
<action path="/posttopic" type="net.seerlog.action.PostTopicAction" scope="request" >
</action>
<action path="/postreply" type="net.seerlog.action.PostReplyAction" scope="request" name="replyForm" input="/sublog.jsp">
</action>
<action path="/index" type="net.seerlog.action.IndexAction" scope="request">
</action>
</action-mappings>
<message-resources parameter="resouse.application">
</message-resources>
</struts-config>
package net.seerlog.action;
//导入所有用的到的包
import java.util.List;
import net.seerlog.po.*;
import net.seerlog.vo.*;
import net.seerlog.util.*;
import net.sf.hibernate.*;
import org.apache.struts.action.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import javax.servlet.ServletException;
public class IndexAction extends Action{
//action的主体方法 execute ,注意要抛出异常
public ActionForward execute (ActionMapping mapping,
ActionForm form,
HttpServletRequest req,
HttpServletResponse res) throws IOException, ServletException{
try{
//开启会话
Session session = Hi.getSession();
Transaction tx= session.beginTransaction();
//查询
Query q = session.createQuery("from Topic as topic order by topic.id desc");
q.setFirstResult(0);
q.setMaxResults(5);
List newTopicList = q.list();
NewTopicList ntlBean=new NewTopicList();
ntlBean.setList(newTopicList);
req.setAttribute("newtopiclist",ntlBean);
//事务提交,关闭session
tx.commit();
Hi.closeSession();
//捕获异常
}catch(HibernateException e){
Log.error(e.toString()); //日志记录
}
//返回一个 actionForward 对象
return mapping.findForward("index");
}
}
本文地址:http://com.8s8s.com/it/it11679.htm