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

来源:互联网 发布:php 正则获取href 编辑:程序博客网 时间:2024/05/24 06:26

环境: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.Driverurl=jdbc:mysql://localhost:3306/studentdbusername=rootpassword=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
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 早上不能晨勃怎么办 阴茎勃起8厘米怎么办 怀孕一周不想要怎么办 表皮囊肿破了怎么办 阴茎勃起很弯曲怎么办 大腿肌肉酸痛是怎么办 大腿根筋拉伤怎么办 大腿后侧拉伤怎么办 腿筋拉伤了怎么办 右臂外侧筋拉伤怎么办 大腿内侧肥胖纹怎么办 孕妇大腿根疼怎么办 乳房胀痛有结节怎么办 乳房按压有痛感怎么办 乳房长期疼痛是怎么办 月经前乳房胀痛怎么办 耳朵进水怎么办嗡嗡响 耳朵进水好几天怎么办 长期耳鸣怎么办小妙招 感觉耳朵有风怎么办 右耳耳鸣几天了怎么办 突然耳鸣怎么办 小妙招 右侧额叶缺血灶怎么办 大腿根部筋疼痛怎么办 大手指根部痛怎么办 塞牙引起牙疼怎么办 左面耳朵旁边疼怎么办 跑步后髋关节痛怎么办 肠系膜淋巴结炎发烧怎么办 小孩肠系膜淋巴结肿大怎么办 耳朵后淋巴结肿大怎么办 耳朵进水聋了怎么办 耳朵一直闷着怎么办 一觉睡醒耳朵疼怎么办 起床耳朵嗡嗡响怎么办 耳朵内有响声怎么办? 耳朵里面进水了怎么办 耳朵进水一直疼怎么办 耳朵鼓鼓的响怎么办 孕妇耳朵嗡嗡响怎么办 小孩眼睛长针眼怎么办