一、分层结构
javabean
通用dao 接口(增删改查的方法 方法权限为默认) 使用反射
通用daoImpl 一个实现通用dao接口的抽象方法 主要实现 dao接口各方法的具体操作 使用反射 注解@Transactional
service 一个继承通用dao接口的接口类(可以添加扩展功能)
serviceImpl 继承通用daoImpl实现service接口的方法 注解@Service @Transactional
通用action 继承ActionSupport实现ModelDriven<T>接口 方法权限protected
注解@Resource 注入所有要使用的service业务接口
action 继承通用action 注解@Controller @Scope("prototype")
通用action代码 如下
public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T>{
///////////注入所有业务接口/////////
@Resource
protected XinZhongSiService xinZhongSiService;
@Resource
protected MessageService messageService;
@Resource
protected AdminLoginService adminLoginService;
protected T model;
public BaseAction(){
try{
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
Class<T> clazz = (Class<T>) pt.getActualTypeArguments()[0];
model = clazz.newInstance();
}catch(Exception e){
throw new RuntimeException(e);
}
}
public T getModel(){
return model;
}
}
通用DAO
public interface BaseDao<T> {
void save(T entity);
void delete(Integer id);
void update(T entity);
T getById(Integer id);
List<T> getByIds(Integer[] ids);
List<T> findAll();
}
通用daoImpl
@Transactional
public abstract class BaseDaoImpl<T> implements BaseDao<T> {
@Resource
private SessionFactory sessionFactory;
private Class<T> clazz;
public BaseDaoImpl(){
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
this.clazz =(Class<T>) pt.getActualTypeArguments()[0];
}
/*获取当前可用session*/
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
@Override
public void save(T entity) {
getSession().save(entity);
}
@Override
public void delete(Integer id) {
Object obj = getById(id);
if(obj!=null){
getSession().delete(obj);
}
}
@Override
public void update(T entity) {
getSession().update(entity);
}
@Override
public T getById(Integer id) {
if(id==null){
return null;
}else{
return (T) getSession().get(clazz, id);
}
}
@Override
public List<T> getByIds(Integer[] ids) {
if(ids==null||ids.length==0){
return Collections.EMPTY_LIST;
}else{
return getSession().createQuery(//
"FROM"+clazz.getSimpleName()+"WHERE id IN (:ids)")//
.setParameterList("ids", ids)//
.list();
}
}
@Override
public List<T> findAll() {
return getSession().createQuery(//
"FROM " + clazz.getSimpleName() +" m order by m.id desc")//
.list();
}
}
applicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" http://www.springframework.org/schema/beans"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xmlns:context=" http://www.springframework.org/schema/context"
xmlns:aop=" http://www.springframework.org/schema/aop"
xmlns:tx=" http://www.springframework.org/schema/tx"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 自动装配 -->
<!-- <context:component-scan base-package="com.edu.zzuli.oracle.lesson"></context:component-scan> -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}" />
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置外部数据库连接信息-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<value>
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
current_session_context_class=thread
javax.persistence.validation.mode=none
</value>
</property>
<property name="mappingLocations">
<list>
<value>classpath:blog/zzq/orm/*.hbm.xml</value>
</list>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--自动扫描 -->
<tx:annotation-driven transaction-manager="txManager"/>
<context:component-scan base-package="blog.zzq"></context:component-scan>
</beans>
db.properties
jdbc.url=jdbc\:mysql\:///blog?createDatabaseIfNotExist\=true&useUnicode\=true&characterEncoding\=utf8
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %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=error, stdout
log4j.logger.com.edu.zzuli.oracle.lesson=debug
#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
" http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="i18n.encoding" value="utf-8"/>
<!-- 配置为开发模式 -->
<constant name="struts.devMode" value="true"/>
<constant name="struts.locale" value="zh_CN" />
<constant name="struts.ui.theme" value="simple" />
<constant name="struts.ognl.allowStaticMethodAccess" value="true" />
<constant name="struts.multipart.maxSize" value="1048576000"/>
<constant name="struts.custom.i18n.resources" value="globalMessages" />
<package name="test" extends="struts-default" namespace="/">
<action name="XinZhongSi_*" class="blog.zzq.action.view.XinZhongSiAction" method="{1}">
<result name="index">/WEB-INF/jsp/client/XinZhongSi.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns=" http://java.sun.com/xml/ns/javaee"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- 解决懒加载的问题 -->
<!-- struts2的主要拦截器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 清除缓存监听防止内存泄漏 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>
<!-- 字符编码过滤器 -->
<filter>
<filter-name>encoding</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
</web-app>