SSH框架整合——基于XML配置文件

@(Spring)[spring, struts2, hibernate, 框架整合, ssh, Spring]

  • SSH框架整合基于XML配置文件

    • SSH框架整合

      • SSH框架整合的基本环境准备

        • 第一步创建web项目引入jar包
        • 第二步引入框架的配置文件
        • 第三步创建包结构和类
        • 第四步将Service和DAO交给Spring管理
        • 第五步引入页面
      • SSH整合Struts2和Spring的整合
        • 第六步修改页面链接为Struts2所能匹配的格式
        • 第七步编写Action中的listCustomer方法
        • 第八步Struts2和Spring整合方式一Action由Struts2自身创建
        • 第八步Struts2和Spring整合方式二Action交给Spring管理推荐
        • 第九步在客户Service中使用客户Dao
      • SSH整合Hibernate和Spring的整合
        • 第十步Hibernate和Spring整合方式一带hibernate的配置文件
        • 第十步Hibernate和Spring整合方式二不带hibernate的配置文件推荐
        • 第十一步添加事务管理
    • Hibernate的模板的API
      • 使用Hibernate的模板完成CRUD的操作

        • 完成增删改的操作
        • 完成查询的操作
    • 配置openSessionInView过滤器解决Hibernate懒加载问题
    • 配置全站编码过滤器

SSH框架整合

该SSH整合是基于Spring4、Struts2、Hibernate5的。

SSH框架整合的基本环境准备

第一步:创建web项目,引入jar包

标红为整合必须引入的

  • Struts2

    • struts-2.3.24\apps\struts2-blank\WEB-INF\lib*.jar —Struts2基本开发包

    • struts2-convention-plugin-2.3.24.jar —Struts2的注解开发包
    • struts2-spring-plugin-2.3.24.jar —Struts2整合Spring的开发包
    • struts2-json-plugin-2.3.24.jar —Struts2整合AJAX的开发包
    • javax.servlet.jsp.jstl-1.2.1.jar — java标准标签库
  • Hibernate

    • mysql-connector-java-5.1.7-bin.jar —数据库驱动
    • hibernate-release-5.0.7.Final\lib\required*.jar —Hibernate必须包
    • 日志记录
    • c3p0连接池

注意:在struts2基础包和Hibernate5基础包中javassist-x.jar这个包会有冲突,搭环境时请使用Hibernate中的高版本javassist的包

  • Spring

    • Spring的基本开发包

    • Spring的AOP的开发包
    • Spring整合web项目包:spring-web-4.2.4.RELEASE.jar
    • Spring整合Junit项目包
      • spring-test-4.2.4.RELEASE.jar
      • junit-4.9.jar
    • Spring的JDBC模板包:spring-jdbc-4.2.4.RELEASE.jar
    • Spring事务管理包:spring-tx-4.2.4.RELEASE.jar
    • Spring整合Hibernate:spring-orm-4.2.4.RELEASE.jar
    • 整合c3p0连接池:com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar,需要使用c3p0连接池,可以导入。

如果使用有hibernate配置文件的ssh整合,使用c3p0连接池,需要使用hibernate中c3p0可选包中的三个jar包;
如果使用没有hibernate配置文件的ssh整合,使用c3p0连接池,需要使用spring整合c3p0连接池中的jar包。
两者不可同用,否则会有冲突。

第二步:引入框架的配置文件

  • Struts2

    • web.xml
<!-- Struts核心过滤器 -->
<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>
  • struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd">
<struts></struts>
  • Hibernate

    • hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration><session-factory></session-factory>
</hibernate-configuration>
  • 映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package=""></hibernate-mapping>
  • Spring

    • web.xml
<!-- 配置Spring上下文环境 -->
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  • 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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"></beans>
  • log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
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 mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.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=info, stdout

第三步:创建包结构和类

package com.pc.crm.domain;
import java.io.Serializable;
/*** 客户实体类* @author Switch*/
public class Customer implements Serializable {private static final long serialVersionUID = 8501538130746309236L;
}
package com.pc.crm.web.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.pc.crm.domain.Customer;
/*** 客户Action* @author Switch*/
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {private static final long serialVersionUID = 7878143682430064108L;Customer customer = new Customer();@Overridepublic Customer getModel() {return this.customer;}
}
package com.pc.crm.service;
/*** 客户服务接口* @author Switch*/
public interface CustomerService {}
package com.pc.crm.service.impl;
import com.pc.crm.service.CustomerService;
/*** 客户服务实现类* @author Switch*/
public class CustomerServiceImpl implements CustomerService {}
package com.pc.crm.dao;
/*** 客户持久层接口* @author Switch*/
public interface CustomerDao {}
package com.pc.crm.dao.impl;
import com.pc.crm.dao.CustomerDao;
/*** 客户持久层接口实现类* @author Switch*/
public class CustomerDaoImpl implements CustomerDao {}

第四步:将Service和DAO交给Spring管理

<!-- 配置客户服务bean -->
<bean id="customerService" class="com.pc.crm.service.impl.CustomerServiceImpl"></bean>
<!-- 配置客户持久层bean -->
<bean id="customerDao" class="com.pc.crm.dao.impl.CustomerDaoImpl"></bean>

第五步:引入页面

这里只给出一个访问链接,基于JSP的。

<a href="${pageContext.request.contextPath}/customer/listCustomer">客户列表</a>

SSH整合:Struts2和Spring的整合

第六步:修改页面链接为Struts2所能匹配的格式

<a href="${pageContext.request.contextPath}/customer/list_Customer.action">客户列表</a>

第七步:编写Action中的listCustomer方法

package com.pc.crm.web.action;import java.util.List;import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.pc.crm.domain.Customer;
import com.pc.crm.service.CustomerService;/*** 客户Action* @author Switch*/
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {private static final long serialVersionUID = 7878143682430064108L;// 客户服务类CustomerService customerService;// 用于使用值栈特性,在页面中使用List<Customer> customers = null;public List<Customer> getCustomers() {return customers;}public void setCustomers(List<Customer> customers) {this.customers = customers;}// 模型驱动Customer customer = new Customer();@Overridepublic Customer getModel() {return this.customer;}/*** 显示客户列表* @return*/public String listCustomer() {// 从数据库中获客户列表customers = customerService.findAllCustomer();// 转发到客户列表视图return "list";}
}

第八步:Struts2和Spring整合方式一:Action由Struts2自身创建

  • 引入Struts2和Spring整合的插件包

    • struts2-spring-plugin-2.3.24.jar

该jar包下有一个struts-plugin.xml的文件,在该文件中开启了Spring工厂对Action中的属性按照名称自动装配等功能。

<!--  Make the Spring object factory the automatic default -->
<constant name="struts.objectFactory" value="spring" />

该常量在struts2核心包的default.properties文件中,有如下配置

### if specified, the default object factory can be overridden here
### Note: short-hand notation is supported in some cases, such as "spring"
###       Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here
# struts.objectFactory = spring### specifies the autoWiring logic when using the SpringObjectFactory.
### valid values are: name, type, auto, and constructor (name is the default)
struts.objectFactory.spring.autoWire = name### indicates to the struts-spring integration if Class instances should be cached
### this should, until a future Spring release makes it possible, be left as true
### unless you know exactly what you are doing!
### valid values are: true, false (true is the default)
struts.objectFactory.spring.useClassCache = true### ensures the autowire strategy is always respected.
### valid values are: true, false (false is the default)
struts.objectFactory.spring.autoWire.alwaysRespect = false### By default SpringObjectFactory doesn't support AOP
### This flag was added just temporally to check if nothing is broken
### See https://issues.apache.org/jira/browse/WW-4110
struts.objectFactory.spring.enableAopSupport = false

struts.objectFactory常量启用时,开启对Spring的一系列支持。比如说按名自动装配。

  • 在Action中不需要使用原来的工厂获取,提供set方法即可。
// 注入客户服务类
CustomerService customerService;public void setCustomerService(CustomerService customerService) {this.customerService = customerService;
}/*** customerService未优化*/
/* public CustomerAction() {ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());customerService = context.getBean("customerService", CustomerService.class);
}
*/
  • 配置Action:Action是Struts2自身创建
<package name="customer" extends="struts-default" namespace="/customer"><!-- 形如list_Customer --><action name="*_*" class="com.pc.crm.web.action.CustomerAction" method="{1}{2}"><!-- 转发到客户列表视图 --><result name="list" type="dispatcher">/jsp/customer/list.jsp</result></action>
</package>

第八步:Struts2和Spring整合方式二:Action交给Spring管理(推荐)

  • 引入Struts2和Spring整合的插件包

    • struts2-spring-plugin-2.3.24.jar
  • 将Action交给Spring创建

<!-- 配置Action,Action注入属性,必须手工注入,且必须声明为多例 -->
<!-- 客户Action -->
<bean id="customerAction" class="com.pc.crm.web.action.CustomerAction" scope="prototype"><property name="customerService" ref="customerService" />
</bean>
  • 注意的事项

    • 一定要将Action配置为多例的
    • 属性的注入必须手动完成
  • struts.xml文件中对应actionclass属性为beanid属性

<package name="customer" extends="struts-default" namespace="/customer"><!-- 形如list_Customer --><action name="*_*" class="customerAction" method="{1}{2}"><!-- 转发到客户列表视图 --><result name="list" type="dispatcher">/jsp/customer/list.jsp</result></action>
</package>

第九步:在客户Service中使用客户Dao

package com.pc.crm.service.impl;
import java.util.List;
import com.pc.crm.dao.CustomerDao;
import com.pc.crm.domain.Customer;
import com.pc.crm.service.CustomerService;
/*** 客户服务实现类* @author Switch*/
public class CustomerServiceImpl implements CustomerService {// 注入客户Daoprivate CustomerDao customerDao;public void setCustomerDao(CustomerDao customerDao) {this.customerDao = customerDao;}@Overridepublic List<Customer> findAllCustomer() {// 查找客户列表return customerDao.findAllCustomer();}
}
<!-- 配置客户服务bean -->
<bean id="customerService" class="com.pc.crm.service.impl.CustomerServiceImpl"><property name="customerDao" ref="customerDao"/>
</bean>

SSH整合:Hibernate和Spring的整合

第十步:Hibernate和Spring整合方式一:带hibernate的配置文件

  • 创建实体类和映射文件Customer.hbm.xml
package com.pc.crm.domain;
import java.io.Serializable;
/*** 客户实体类* @author Switch*/
public class Customer implements Serializable {private static final long serialVersionUID = 8501538130746309236L;private Long custId;private String custName;private String custSource;private String custIndustry;private String custLevel;private String custAddress;private String custPhone;......
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.pc.crm.domain"><class name="Customer" table="cst_customer" lazy="true" batch-size="3"><id name="custId" column="cust_id" type="java.lang.Long"><generator class="native"/></id><property name="custName" column="cust_name" type="java.lang.String" length="32"/><property name="custSource" column="cust_source" type="java.lang.String" length="32"/><property name="custIndustry" column="cust_industry" type="java.lang.String" length="32"/><property name="custLevel" column="cust_level" type="java.lang.String" length="32"/><property name="custAddress" column="cust_address" type="java.lang.String" length="128"/><property name="custPhone" column="cust_phone" type="java.lang.String" length="64"/></class>
</hibernate-mapping>
  • 配置hibernate.cfg.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration><session-factory><!-- 1、连接数据库的基本信息 --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mycrm</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">123456</property><!-- 数据库的方言 --><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><!-- 2、hibernate的基本配置 --><!-- 是否显示SQL语句 --><property name="hibernate.show_sql">true</property><!-- 是否格式化显示SQL语句 --><property name="hibernate.format_sql">true</property><!-- 采用何种策略来创建表结构: --><!-- update:检查表结构和实体类映射文件的变化,如果发现映射文件和表结构不一致,更新表结构。 --><property name="hibernate.hbm2ddl.auto">update</property><!-- 配置hibernate使用连接池:告知Hibernate使用连接池的厂商 --><property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property><!-- 3、映射文件的位置 --><mapping resource="com/pc/crm/domain/Customer.hbm.xml" /><mapping resource="com/pc/crm/domain/LinkMan.hbm.xml" /></session-factory>
</hibernate-configuration>
  • 在Spring中引入Hibernate的配置文件
<!-- 配置Hibernate的SessionFactory,有hibernate配置文件 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"><property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
  • Spring为了简化Hibernate的开发,提供了Hibernate的模板
package com.pc.crm.dao.impl;
import java.util.List;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.pc.crm.dao.CustomerDao;
import com.pc.crm.domain.Customer;
/*** 客户持久层接口实现类* @author Switch*/
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {@Overridepublic List<Customer> findAllCustomer() {}
}
<!-- 配置客户持久层bean -->
<bean id="customerDao" class="com.pc.crm.dao.impl.CustomerDaoImpl"><!-- 该bean继承了HibernateDaoSupport,则可以直接注入sessionFactory --><property name="sessionFactory" ref="sessionFactory"/>
</bean>
  • 在客户Dao中使用Hibernate的模板
package com.pc.crm.dao.impl;
import java.util.List;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.pc.crm.dao.CustomerDao;
import com.pc.crm.domain.Customer;/*** 客户持久层接口实现类* @author Switch*/
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {@Overridepublic List<Customer> findAllCustomer() {return (List<Customer>) this.getHibernateTemplate().find("from Customer");}
}

第十步:Hibernate和Spring整合方式二:不带hibernate的配置文件(推荐)

  • 创建实体类和映射文件Customer.hbm.xml
package com.pc.crm.domain;
import java.io.Serializable;
/*** 客户实体类* @author Switch*/
public class Customer implements Serializable {private static final long serialVersionUID = 8501538130746309236L;private Long custId;private String custName;private String custSource;private String custIndustry;private String custLevel;private String custAddress;private String custPhone;......
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.pc.crm.domain"><class name="Customer" table="cst_customer" lazy="true" batch-size="3"><id name="custId" column="cust_id" type="java.lang.Long"><generator class="native"/></id><property name="custName" column="cust_name" type="java.lang.String" length="32"/><property name="custSource" column="cust_source" type="java.lang.String" length="32"/><property name="custIndustry" column="cust_industry" type="java.lang.String" length="32"/><property name="custLevel" column="cust_level" type="java.lang.String" length="32"/><property name="custAddress" column="cust_address" type="java.lang.String" length="128"/><property name="custPhone" column="cust_phone" type="java.lang.String" length="64"/></class>
</hibernate-mapping>
  • 替换hibernate.cfg.xml中的相关内容,将其配置在spring中

    • 提供数据库属性文件db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mycrm
jdbc.user=root
jdbc.password=123456
  • 配置属性持有对象
<!-- 配置属性持有对象 -->
<context:property-placeholder location="classpath:db.properties"/>
  • 配置数据源
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driverClass}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="user" value="${jdbc.user}"/><property name="password" value="${jdbc.password}"/>
</bean>
  • 替换hibernate配置信息
<!-- 配置Hibernate的SessionFactory,无hibernate配置文件 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"><!-- 配置数据源 --><property name="dataSource" ref="dataSource"/><!-- 配置hibernate属性--><property name="hibernateProperties"><props><!-- 数据库的方言 --><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><!-- 是否显示SQL语句 --><prop key="hibernate.show_sql">true</prop><!-- 是否格式化显示SQL语句 --><prop key="hibernate.format_sql">true</prop><!-- 采用何种策略来创建表结构: --><prop key="hibernate.hbm2ddl.auto">update</prop></props></property><!-- 配置映射文件 --><property name="mappingLocations" value="classpath:com/pc/crm/domain/*.hbm.xml"/>
</bean>
  • Spring为了简化Hibernate的开发,提供了Hibernate的模板
package com.pc.crm.dao.impl;
import java.util.List;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.pc.crm.dao.CustomerDao;
import com.pc.crm.domain.Customer;
/*** 客户持久层接口实现类* @author Switch*/
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {@Overridepublic List<Customer> findAllCustomer() {}
}
<!-- 配置客户持久层bean -->
<bean id="customerDao" class="com.pc.crm.dao.impl.CustomerDaoImpl"><!-- 该bean继承了HibernateDaoSupport,则可以直接注入sessionFactory --><property name="sessionFactory" ref="sessionFactory"/>
</bean>
  • 在客户Dao中使用Hibernate的模板
package com.pc.crm.dao.impl;
import java.util.List;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.pc.crm.dao.CustomerDao;
import com.pc.crm.domain.Customer;/*** 客户持久层接口实现类* @author Switch*/
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {@Overridepublic List<Customer> findAllCustomer() {return (List<Customer>) this.getHibernateTemplate().find("from Customer");}
}

第十一步:添加事务管理

  • 配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"/>
</bean>
  • 配置事务通知
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><!-- 事务管理策略,查为只读 --><!-- 事务隔离级别:mysql为可重复读,事务传播行为:默认值required --><tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/><tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/><tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>          <tx:method name="*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/></tx:attributes>
</tx:advice>
  • 配置事务AOP
<!-- 配置事务AOP -->
<aop:config><aop:pointcut expression="execution(* com.pc.crm.service.impl.*.*(..))" id="pointcut1"/><aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut1"/>
</aop:config>

PS:如果需要配置基于注解的事务,请参考之前的博文《Spring事务管理》。

Hibernate的模板的API

使用Hibernate的模板完成CRUD的操作

完成增删改的操作

  • Serializable save(Object obj);
  • void update(Object obj);
  • void delete(Object obj);
package com.pc.crm.dao.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.pc.crm.dao.CustomerDao;
import com.pc.crm.domain.Customer;
/*** 客户持久层接口实现类* @author Switch*/
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {@Overridepublic void save(Customer customer) {this.getHibernateTemplate().save(customer);}@Overridepublic void update(Customer customer) {this.getHibernateTemplate().update(customer);}@Overridepublic void delete(Customer customer) {this.getHibernateTemplate().delete(customer);}
}

完成查询的操作

  • T get(Class c,Serializable id); / T load(Class c,Serializable id);
  • List
package com.pc.crm.dao.impl;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import com.pc.crm.dao.CustomerDao;
import com.pc.crm.domain.Customer;
/*** 客户持久层接口实现类* @author Switch*/
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {@Overridepublic Customer findById(Long id) {return this.getHibernateTemplate().load(Customer.class, id);}@Overridepublic List<Customer> findAll() {// 使用HQL查询:// List<Customer> list = (List<Customer>) this.getHibernateTemplate().find("from Customer ");// 使用QBC查询:使用DetchedCriteria// DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);// List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByCriteria(detachedCriteria);// 命名查询:List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByNamedQuery("queryAll");return list;}@Overridepublic List<Customer> findByPage() {DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByCriteria(detachedCriteria, 0, 3);return list;}
}

配置openSessionInView过滤器,解决Hibernate懒加载问题

<!-- 配置openSessionInView,解决Hibernate懒加载问题 -->
<filter><filter-name>OpenSessionInViewFilter</filter-name><filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping><filter-name>OpenSessionInViewFilter</filter-name><url-pattern>*.action</url-pattern>
</filter-mapping>

PS:将该过滤器放在Struts2核心过滤器上面。

配置全站编码过滤器

<!-- 配置全站编码过滤器 -->
<filter><filter-name>CharacterEncodingFilter</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>
<filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>

PS:将该过滤器放在Struts2核心过滤器上面。

SSH框架整合——基于XML配置文件相关推荐

  1. SSH框架整合——基于注解

    SSH框架整合--基于注解 @(Spring)[Spring, hibernate, struts2, 框架整合] SSH框架整合基于注解 SSH框架整合 第一步导入Jar包 第二步导入配置文件 第三 ...

  2. MyBatis框架基于XML配置文件开发

    MyBatis框架基于XML配置文件开发 本文内容涉及MyBatis框架开发的传参,多表查询,结果封装: 说明: 当前使用的是mysql数据库, 测试在maven工程下: 数据库表: book表: k ...

  3. SSH框架整合-慕课课程

    SSH框架整合-慕课课程 学习时间:2018年12月3日 慕课链接:基于SSH实现员工管理系统之框架整合篇 内容:Struts2+Hibernate+Spring框架整合,分为Struts2整合Spr ...

  4. 【struts2+spring+hibernate】ssh框架整合开发

    SSH框架整合 1 Struts2+Spring+Hibernate导包 Struts2导入jar包: * struts2/apps/struts2-blank.war/WEB-INF/lib/*.j ...

  5. 6.SSH框架整合及简单使用示例

    6.SSH框架整合 ssh:spring+spring-mvc+hibernate 6.1 整合的场所 :web.xml 跟 5.ssm框架 整合类似,可以对照学习,通过监听器配置hibernate, ...

  6. SSM框架整合:各种配置文件的整合和详解

    SSM框架整合:各种配置文件的整合和详解 前言 学习了ssm框架的整合之后,对于数量众多的配置文件,和各种不同的配置方式感到甚是头疼,接下来教给大家一个清晰明白的配置,分门别类的配置不同的xml文件. ...

  7. SSH框架整合开发(SSH框架整合过程)

    SSH框架整合过程 第一步 导入需要用到的jar包 第二步 搭建struts2环境 (1) 创建action ,创建struts.xml配置文件,配置action (2) 配置struts2 的过滤器 ...

  8. Java解析xml文件dom4j篇(基于xml配置文件完成Excel数据的导入、导出功能完整实现)

    DOM4J解析XML文件 dom4j是一个Java的XML API,是jdom的升级产品,用来读写XML文件.另外对比其他API读写XML文件,dom4j是一个十分优秀的JavaXML API,具有性 ...

  9. Spring中Bean管理操作基于XML配置文件方法实现

    Spring中Bean管理操作基于XML配置文件方法实现 基于XML配置文件方式实现 1.基于`xml`方式创建对象 2.基于`xml`方式注入属性 1.创建类,定义属性和对应的set方法 2.在Sp ...

最新文章

  1. 吴恩达新书《Machine Learning Yearning》完整中文版 PDF 下载!
  2. oracle散列,在Python中散列一个整数,以匹配Oracle的标准_散列
  3. 数据算法——Spark的TopN实现
  4. redmine 贴图操作
  5. k近邻回归算法python_K近邻算法用作回归的使用介绍(使用Python代码)
  6. pycharm报黄提示(黄色高亮警告):non-default parameter follows default parameter(定义时将没有默认值的参数放到了有默认值参数的后面)
  7. 聊聊《战魂铭人》的游戏设计
  8. datagridview 动态插入图片_挑战一张照片制作动态PPT背景
  9. sklearn保存svm分类模型_【菜菜的sklearn】07 支持向量机(上)
  10. MySQL基础篇(05):逻辑架构图解和InnoDB存储引擎详解
  11. 4399ATAPI讲解操作事件篇
  12. ThinkPHP多语言包功能使用
  13. 基于大型数字视频监控系统解决方案
  14. 清除当前目录下的.svn文件 linux/windows
  15. 学Web的第二十一天
  16. The requirements of using provenance in e-Science experiments(论文阅读)
  17. Qt窗口组件实现动态背景功能
  18. 功放限幅保护_【干货】如何利用限幅器保护音箱√
  19. 如何使用AE制作文字破碎动画?制作ae破碎文字特效教程分享
  20. 北航计算机考博经验,最新的北航考博经验

热门文章

  1. Docker快速搭建Oracle12c
  2. 解决后台json数据返回的字段需要替换的问题
  3. servlet url-pattern配置中 / 和 /* 的区别 记录
  4. 【Java】用for循环实现1+2+3......+100 =
  5. 有哪些好的刷题网站?2018年最受欢迎的编程挑战网站
  6. 使用dockerfile自动化构建镜像
  7. azure考试_我如何通过AZ-900 Microsoft Azure基础考试
  8. 怎么让前端项目运行起来_如何立即使您的前端项目看起来更好
  9. pr下雪下雨_图像增强:下雨,下雪。 如何修改照片以训练自动驾驶汽车
  10. react 组件名称重复_设计可重复使用的React组件