实战Struts+Spring+Hibernate
经过几天在网上的搜索,查看了关于Struts、Spring、Hibernate的文章,在实际的使用后得到了一些体会。鉴于很多资料不全或较旧,特写下一篇较为完整的实战指南,包括主要程序类和配置文件。
一、准备篇
实战前需准备以下开发组件(都是目前最新版本)。
1、Struts 1.2.9,从www.apache.org网站可下载。
2、spring-framework-1.2.8,从www.springframework.org网站可下载。
3、Hibernate 3.1.3,从www.hibernate.org网站可下载。
4、Tomcat 5.0.28,从www.apache.org网站可下载。
二、程序篇
java包我们建立如下结构
hibernate存放hibernate相关类
impl存放service实现类
interfaces存放接口类
player存放struts相关类
1、Hiberate相关类(HBM、PO)可以使用工具直接生成,这里不再列出
2、IPlayerDAO.java 持久层的接口类
public interface IPlayerDAO
{
public abstract List findTop(final int count);
public abstract TblPlayer findById(String id);
}
3、TblPlayerDAO.java 持久层的接口的实现类,HibernateDaoSupport提供了对Hibernate良好的支持,下例的两个方法显示了HibernateTemplate的两种最常用的方法。
public class TblPlayerDAO extends HibernateDaoSupport implements IPlayerDAO
{
public List findTop(final int count)
{
return (List) getHibernateTemplate().execute(new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException
{
Query q = session.createQuery("select player from TblPlayer player order by player.Id");
q.setFirstResult(0);
q.setMaxResults(count);
return q.list();
}
});
}
public TblPlayer findById(String id)
{
return (TblPlayer) getHibernateTemplate().get(TblPlayer.class, id);
}
}
4、IPlayerService 业务层接口类
public interface IPlayerService
{
public abstract void setPlayerDAO(IPlayerDAO playerDAO);
public abstract List findTop(final int count);
public abstract TblPlayer findById(String id);
}
5、PlayerServiceImpl 业务层接口实现类
public class PlayerServiceImpl implements IPlayerService
{
IPlayerDAO playerDAO = null;
public void setPlayerDAO(IPlayerDAO playerDAO)
{
this.playerDAO = playerDAO;
}
public List findTop(final int count)
{
return playerDAO.findTop(count);
}
public TblPlayer findById(String id)
{
TblPlayer player = playerDAO.findById(id);
return player;
}
}
6、PlayerAction.java
public class PlayerAction extends Action
{
private IPlayerService playerService;
public void setPlayerService(IPlayerService playerService)
{
this.playerService = playerService;
}
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response)
{
PlayerForm form = (PlayerForm)actionForm;
try
{
TblPlayer player = playerService.findById(form.getPlayer().getId());
request.setAttribute("player",player);
}
catch(Exception e)
{
request.setAttribute("errorMsg","选手未找到");
log.error(e,e);
}
return mapping.findForward("ViewDetail");
}
}
7、PlayerForm
public class PlayerForm extends ActionForm
{
static final long serialVersionUID = -9073943177741915925L;
TblPlayer player = new TblPlayer();
public TblPlayer getPlayer()
{
return player;
}
public void setPlayer(TblPlayer player)
{
this.player = player;
}
}
三、配置篇
1、web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<display-name>Tour Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-hibernate.xml</param-value>
</context-param>
<filter>
<filter-name>CharacterEncoding</filter-name>
<filter-class>com.lutong.CharsetFilter</filter-class>
</filter>
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>WebLog</servlet-name>
<servlet-class>com.kehaoinfo.log.WebLog</servlet-class>
<init-param>
<param-name>log4j-init-file</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>SpringContextServlet</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Configuration (with debugging) -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/tags/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-logic</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-nested</taglib-uri>
<taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-tiles</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
2、applicationContext-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!--
- Root application context for the Countries application.
- Web-specific beans are defined in "countries-servlet.xml".
-->
<beans>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="url" value="jdbc:jtds:sqlserver://192.167.0.107:1433/tour;charset=gb2312"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>com/lutong/tour/hibernate/hbm/TblPlayer.hbm</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
</props>
</property>
<property name="dataSource"><ref bean="myDataSource"/></property>
</bean>
<bean id="myTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory"><ref local="mySessionFactory"/></property>
</bean>
<!-- ExceptionTranslator -->
<bean id="jdbcExceptionTranslator" class="org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator">
<property name="dataSource"><ref bean="myDataSource"/></property>
</bean>
<!-- Hibernate Template -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory"><ref bean="mySessionFactory"/></property>
<property name="jdbcExceptionTranslator"><ref bean="jdbcExceptionTranslator"/></property>
</bean>
<!-- baseTransactionProxy -->
<bean id="baseTransactionProxy" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref bean="myTransactionManager"/></property>
<property name="proxyTargetClass"><value>true</value></property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="submit*">PROPAGATION_REQUIRED</prop>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<!-- DAO implements -->
<bean id="playerDAO" class="com.lutong.tour.hibernate.dao.TblPlayerDAO">
<property name="sessionFactory"><ref bean="mySessionFactory"/></property>
</bean>
<!-- Service implements -->
<bean id="playerService" class="com.lutong.tour.impl.PlayerServiceImpl">
<property name="playerDAO"><ref bean="playerDAO"/></property>
</bean>
<!-- ProxyFaction -->
<bean id="playerManager" parent="baseTransactionProxy">
<property name="target"><ref local="playerService"/></property>
</bean>
</beans>
3、applicationContext-struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean name="/player" class="com.lutong.tour.player.PlayerAction" singleton="false">
<property name="playerService"><ref bean="playerManager"/></property>
</bean>
</beans>
4、struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<!-- ================================================ Form Bean Definitions -->
<form-beans>
<form-bean name="playerForm" type="com.lutong.tour.player.PlayerForm" />
</form-beans>
<!-- ========================================= Global Exception Definitions -->
<global-exceptions>
<!-- sample exception handler
<exception
key="expired.password"
type="app.ExpiredPasswordException"
path="/changePassword.jsp"/>
end sample -->
</global-exceptions>
<!-- =========================================== Global Forward Definitions -->
<global-forwards>
<!-- Default forward to "Welcome" action -->
<!-- Demonstrates using index.jsp to forward -->
<forward name="error" path="/message.jsp" />
<forward name="message" path="/message.jsp" />
<forward name="PlatLogout" path="/web/logout.jsp" />
</global-forwards>
<!-- =========================================== Action Mapping Definitions -->
<action-mappings>
<action
name="playerForm"
path="/player"
type="org.springframework.web.struts.DelegatingActionProxy"
scope="request"
validate="true">
<forward
name="ViewDetail"
path="/playerDetail.jsp"/>
</action>
</action-mappings>
<controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
<message-resources parameter="MessageResources" />
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
<!-- Path to XML definition file -->
<set-property property="definitions-config"
value="/WEB-INF/tiles-defs.xml" />
<!-- Set Module-awareness to true -->
<set-property property="moduleAware" value="true" />
</plug-in>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property
property="contextConfigLocation"
value="/WEB-INF/applicationContext-struts.xml"/>
</plug-in>
</struts-config>