如何整合S1SH(三)

来源:互联网 发布:windows 私有云 软件 编辑:程序博客网 时间:2024/06/07 23:14

第七步(解决中文乱码问题):
1.思路1:自己配置过滤器,同时在web.xml中做如下配置:

    <filter>        <filter-name>MyFilter</filter-name>        <filter-class>com.ssh.web.filter.MyFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>MyFilter</filter-name>        <url-pattern>/*</url-pattern>           </filter-mapping>

2.思路2:使用spring框架提供的处理中文乱码的过滤器,在web.xml中添加如下配置:

<!-- spring提供的编码过滤器 -->    <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>    </filter>    <filter-mapping>        <filter-name>encoding</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>

第八步(S1SH整合特别说明):
1.Spring可以启用注解的方式来配置属性:
首先,重新在applicationContext.xml中配置bean:

<!-- 配置struts -->    <bean name="/login" scope="prototype" class="com.ssh.web.action.LoginAction"/>    <!-- 配置dao -->    <bean id="employeeDao" class="com.ssh.dao.EmployeeDao"/>    <!-- 配置Service -->    <bean id="employeeManager" class="com.ssh.service.EmployeeManager"/>

其次,在EmployeeDao.java,EmployeeManager.java,LoginAction.java中做如下修改:

//EmployeeDao.java中@Resourceprivate SessionFactory sessionFactory;//EmployeeManager.java中@Resourceprivate IEmployeeDao employeeDao;//LoginAction.java中@Resourceprivate IEmployeeManager employeeManager;

然后,在applicationContext.xml中添加如下配置:

<!-- 启用注解扫描 --><context:annotation-config/>

最后,测试,依然通过。


2.2. ssh整合的时候,如何解决懒加载问题?
问题?如果我们的雇员都属于一个部门,
employee表:
这里写图片描述
department表:
这里写图片描述

具体问题?如果我们在mainFrame.jsp中要求显示该雇员所在部门的时候,通过${employee.department.name},懒加载问题就会出现。
特别说明:如果对Entity采用Annotation的方式,在一对多映射时,以多方为主导,通过多方导航到一方,不会出现延迟加载。对于Employee和Department,当你对Entity采用Xml的方式,会出现延迟加载,错误如下:

错误:org.hibernate.LazyInitializationException: could not initialize proxy - no Session

解决方式:
a)明确初始化(没测试)
在session还没有关闭时,访问一次xxx.getXxx,强制访问数据库,或者Hibernate.initialize(Xxx.class)
b) 在对象映射文件中,即Employee.hbm.xml和Department.hbm.xml中,要取消懒加载,需要添加属性设置:

<lazy=”false/>

特别说明:上面两种方法问题是,不管你在jsp中使不使用部门名称,它都有向数据库发出select请求。
c) Spring专门提供了openSessionView的方法来解决懒加载,需要在web.xml中做如下配置:

<!-- 配置openSessionView解决懒加载,本质是一个过滤器 -->  <filter>    <filter-name>OpenSessionInViewFilter</filter-name>    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>OpenSessionInViewFilter</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>

特别说明:该方法可以有效减少对数据库的查询,缺点是和数据库保持的session时间延长。


总结,好了,对于”如何整合S1SH”更多的是提供了一种思路,使得我们对于如何做整合,提供了一种途径,接下来,也会尝试着对S2SH整进行整合,非常感谢韩顺平sir。


最后是关于代码,见链接(源码地址)

0 0