spring系列(九):SSH整合四_采用泛型方式

环境:jdk1.7    spring3.2.2    struts2.3.15   hibernate3.3.2  druid1.0.9.jar

上一篇我们讲解了ssh的整合。这一篇继续深入ssh的整合之采用泛型方式。采用泛型能使用我们节省大量代码。

下面来看工程的建立及相关代码

导入包


目录结构


============web.xml配置=========================

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  
  <error-page>
  	<error-code>404</error-code>
  	<location>/Err404.html</location>
  </error-page>
  <error-page>
  	<error-code>500</error-code>
  	<location>/Err500.html</location>
  </error-page>
  
  <!-- 解决延迟加载的问题start -->
  <filter>
  	<filter-name>OpenSessionInView</filter-name>
  	<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>OpenSessionInView</filter-name>
  	<url-pattern>*.php</url-pattern>
  </filter-mapping>
  <!-- 解决延迟加载的问题end -->
  
  <!--struts2 config start  -->
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  	<init-param>
  		<param-name>config</param-name>
  		<param-value>struts-default.xml,struts-plugin.xml,configs/struts.xml</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--struts2 config end  -->
  
  
  <!-- druid pool -->
  <filter>
     <filter-name>DruidWebStatFilter</filter-name>
     <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
     <init-param>
         <param-name>exclusions</param-name>
         <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
     </init-param>
  </filter>
  <filter-mapping>
     <filter-name>DruidWebStatFilter</filter-name>
     <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
  </servlet>
  <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
  </servlet-mapping>
  <!--http://localhost:8080/SSHFinal/druid/index.html  -->
   
   
  <!--spring config start -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:configs/context.xml</param-value>
  </context-param>
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- spring config end -->
  
  <!-- 加载日志start -->
  <context-param>
  	<param-name>log4jConfigLocation</param-name>
  	<param-value>classpath:configs/log4j.properties</param-value>
  </context-param>
  <listener>
  	<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <!-- 加载日志end -->
  
  <welcome-file-list>
    <welcome-file>Login.jsp</welcome-file>
  </welcome-file-list>
</web-app>
================druid连接池配置druid.properties==================

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/studentdb
username=root
password=sasa
#配置监控统计拦截的filters,去掉后监控界面sql无法统计
filters=stat
#配置初始化大小 
initialSize=6
#配置初始化最大连接数 
maxActive=20
#配置初始化最小连接数 
minIdle=3
#配置获取连接等待超时的时间,1分钟 
maxWait=60000
#检测连接是否有效的SQL 
validationQuery=SELECT 'x'
#空闲的连接是否进行有效性检查
testWhileIdle=true
#申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 
testOnBorrow=false
#归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 
testOnReturn=false
#启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true 
maxPoolPreparedStatementPerConnectionSize=20
#对于长时间不使用的连接强制关闭 
removeAbandoned=true
#超过60秒的空闲连接就可以被关闭了,单位是秒 
removeAbandonedTimeout=60
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 
timeBetweenEvictionRunsMillis=10000
#配置一个连接在池中最小生存的时间,单位是毫秒 
minEvictableIdleTimeMillis=30000
===============hibernate核心配置文件hibernate.cfg.xml========================

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="show_sql">true</property>
	<property name="format_sql">true</property>
	<property name="current_session_context_class">thread</property>

	<property name="hibernate.cache.provider_class">
		org.hibernate.cache.EhCacheProvider
	</property>
	<property name="cache.provider_configuration_file_resource_path">
	     configs/ehcache.xml
	</property>
	<property name="hibernate.cache.use_second_level_cache">true</property>
	<property name="hibernate.cache.use_query_cache">true</property>
</session-factory>
</hibernate-configuration>
===============spring核心配置文件context.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: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/aop
	                    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	                    http://www.springframework.org/schema/tx
	                    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<!-- 导入其它sping配置文件 -->
	<import resource="classpath:configs/spring/context-*.xml"/>
	<!-- durid连接池配置start -->
	<bean id="duridConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
		<property name="locations">
		    <list>
				<value>classpath:configs/druid.properties</value>
			</list>
		</property>
    </bean>
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" 
		init-method="init" destroy-method="close">
		<property name="driverClassName" value="${driverClassName}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<property name="filters" value="${filters}" />
		<property name="initialSize" value="${initialSize}" />
		<property name="maxActive" value="${maxActive}" />
		<property name="minIdle" value="${minIdle}" />
		<property name="maxWait" value="${maxWait}" />
		<property name="validationQuery" value="${validationQuery}" />
		<property name="testWhileIdle" value="${testWhileIdle}" />
		<property name="testOnBorrow" value="${testOnBorrow}" />
		<property name="testOnReturn" value="${testOnReturn}" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="${maxPoolPreparedStatementPerConnectionSize}" />
		<property name="removeAbandoned" value="${removeAbandoned}" />
		<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
		<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
		<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
	</bean>
    <!-- durid连接池配置end -->
    
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="druidDataSource"></property>
		<property name="configLocation">
			<value>classpath:configs/hibernate.cfg.xml</value>
		</property>
		<property name="mappingLocations">
			<list>
				<value>classpath:configs/mappers/*.hbm.xml</value>
			</list>
		</property>
	</bean>
	
	<!-- 事务配置start -->
	<bean id="txManger" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<tx:advice id="txAdvise" transaction-manager="txManger">
		<tx:attributes>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="search*" read-only="true"/>
			<tx:method name="load*" read-only="true"/>
			<tx:method name="query*" read-only="true"/>
			<tx:method name="get*" read-only="true"/>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="modify*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="del*" propagation="REQUIRED"/>
			<tx:method name="do*" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice>
	
	<aop:config>
		<aop:pointcut id="mycut" expression="execution(* com.obtk.biz.*.*(..))"/>
		<aop:advisor advice-ref="txAdvise" pointcut-ref="mycut"/>
	</aop:config>
	<!-- 事务配置end -->
</beans>
==============dao层配置context-dao.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: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/aop
	                    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	                    http://www.springframework.org/schema/tx
	                    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	
	<!-- 根据名称自动装配 -->
	<bean id="userDao" class="com.obtk.dao.user.UserDaoImpl" autowire="byName">
	</bean>
	<!-- 根据类型自动装配 -->
	<bean id="stuDao" class="com.obtk.dao.stu.StudentDaoImpl" autowire="byType">
	</bean>
	<!-- 不进行自动装配 -->
	<bean id="acctDao" class="com.obtk.dao.acct.AcctDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
</beans>
====================struts核心配置文件struts.xml=====================

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"struts-2.3.dtd">
<struts>
    <constant name="struts.action.extension" value="php"></constant>
    <constant name="struts.multipart.saveDir" value="C:\tmp"></constant>
    <!-- 最大只能传1m上来 -->
    <constant name="struts.multipart.maxSize" value="1048576"></constant>
    <!-- 导入其它struts配置 -->
	<include file="configs/struts/struts-*.xml"></include>
</struts>
==============用户模块的struts配置struts-user.xml======================

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"struts-2.3.dtd">
<struts>
    
	<package name="user" extends="struts-default">
		<action name="Login" class="com.obtk.actions.user.LoginAction">
			<result name="success">index.jsp</result>
			<result name="input">Login.jsp</result>
		</action>
		
		<action name="CheckUser" class="com.obtk.actions.user.CheckUserAction">
			<result name="success" type="stream">
				<param name="contentType">text/html</param>
				<param name="inputName">bis</param>
			</result>
		</action>
		
		<action name="Register" class="com.obtk.actions.user.RegisterAction">
			<result name="success">Login.jsp</result>
			<result name="input">Register.jsp</result>
		</action>
		
		<action name="ShowWeather" class="com.obtk.actions.user.WeatherAction">
			<result name="success">ShowWeather.jsp</result>
		</action>
	</package>
</struts>
===============关键代码GernericDao====================

package com.obtk.dao;

import java.io.Serializable;
import java.util.List;

public interface GernericDao<T> {
	T getById(Class<T> entityCla,Object id);
	
	List<T> getAll(T t);
	
	Serializable save(T t);
	
	void deleteById(Class<T> entityCla,Object id);
	
	void update(T t);
}
==============GernericDaoImpl====================

package com.obtk.dao;

import java.io.Serializable;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class GernericDaoImpl<T> extends HibernateDaoSupport implements GernericDao<T> {

	public void deleteById(Class<T> entityCla,Object id) {
		this.getHibernateTemplate().delete(this.getById(entityCla,id));
	}

	public List<T> getAll(T t) {
		return (List<T>)this.getHibernateTemplate().loadAll(t.getClass());
	}

	public T getById(Class<T> entityCla,Object id) {
		T t1=null;
		if(id instanceof String){
			t1=(T)this.getHibernateTemplate().load(entityCla, (String)id);
		}else if(id instanceof Integer){
			t1=(T)this.getHibernateTemplate().load(entityCla, (Integer)id);
		}else if(id instanceof Long){
			t1=(T)this.getHibernateTemplate().load(entityCla, (Long)id);
		}else{
			throw new RuntimeException("id类型错误");
		}
		return t1;
	}

	public Serializable save(T t) {
		return this.getHibernateTemplate().save(t);
	}

	public void update(T t) {
		this.getHibernateTemplate().update(t);
	}
	
}
===============IUserDao================

package com.obtk.dao.user;

import com.obtk.dao.GernericDao;
import com.obtk.entitys.UserEntity;;

public interface IUserDao<UserEntity> extends GernericDao<UserEntity> {
	boolean isLogin(String userName,String passWord);
}
=====================UserDaoImpl==================

package com.obtk.dao.user;

import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;

import com.obtk.dao.GernericDaoImpl;
import com.obtk.entitys.UserEntity;;

public class UserDaoImpl extends GernericDaoImpl<UserEntity> implements IUserDao<UserEntity> {
	public boolean isLogin(String userName, String passWord) {
		boolean flag = false;
		HibernateTemplate hiberUtil = this.getHibernateTemplate();
		Object[] params = new Object[] { userName, passWord };
		hiberUtil.setCacheQueries(true);
		List<UserEntity> userList = hiberUtil.find(
				"from Users where userName=? and passWord=?", params);
		if (userList.size() == 1) {
			flag = true;
		}
		return flag;
	}
	
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

御前两把刀刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值