Sping学习笔记

Sping学习笔记

基于尚学堂马士兵老师的Spring教学视频,学习了两遍,自己总结了下学习笔记,方便日后查阅,相关视频大家可以自己去尚学堂下载

一,单元测试JUnit4

(一般情况下)

测试类一般重新创建一个新的SourceFolder文件夹里面装测试类

测试什么类就基本上命名为xxTest  比如:userServiceTest.java

在需要测试的类创建测试类如:userService右键创建JUnit Test Case然后选择要测试的方法,下一步之后会询问是否加入JUnit4的jar包,导入jar包即可

二,spring的配置文件beans.xml

1,使用beans.xml这个文件来存放各种bean,存放在和src目录同一级别,格式如下:

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 

 <beanid="userDao"class="com.bjsxt.dao.impl.UserDAOImpl"></bean>

      

 <beanid="userService"class="com.bjsxt.service.UserService">

     <propertyname="userDAO"ref="userDao"/>

            <!-- 第二种写法 -->

            <!-- <ref bean="u"</ref>-->

 </bean>

</beans>

2,在spring的bean.xml文件可以将一个类的属性注入到这个类中,比如:

<propertyname="userDAO"ref="userDao"/>这种类型

这里的proerty相当于set方法

三,控制反转IOC(DI)

1,把自己new的对象改为由容器提供

a)        初始化具体bean

b)       动态装配

好处:灵活装配

项目名称:Spring_0200_IOC_Introduction

环境搭建

c)        单独Spring框架需要的jar包

                       i.             spring.jar

                     ii.             commons-loggin.jar

                   iii.             aspectjrt.jar

                    iv.             aspectjweaver.jar

                      v.             cglib-nodep-2.1_3.jar

                    vi.             commons-pool.jar

                  vii.             commons-dbcp.jar

2,spring在配置文件中不给提示配置如下(spring xml文件配置):

a)        window – preferences –myeclipse – xml – xml catalog

b)       User Specified Entries – add

                        i.             Location:    D:\share\0900_Spring\soft\spring-framework-2.5.6\dist\resources\spring-beans-2.5.xsd

                       ii.             URI:                 file:///D:/share/0900_Spring/soft/spring-framework-2.5.6/dist/resources/spring-beans-2.5.xsd

                     iii.             KeyType:   Schema Location

                     iv.             Key:           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

3,注入类型(参考项目Spring_0300_IOC_Injection_Type)

c)        setter(重要)

d)       构造方法(可以忘记)

e)        接口注入(可以忘记)

7.xml文件中定义的bean可以是id 或者是 name

区别:name可以用特殊字符

4,简单类属性的注入

f)        Spring_0500_IOC_SimpleProperty

g)       <property name=… value=….>

5,<bean 中的scope属性

h)       Spring_0600_IOC_Bean_Scope

i)         singleton 单例

j)        proptotype每次创建新的对象

6,自动装配,通过在beans.xml文件中配置autowire这个属性来自动装配,如下beans.xml文件所示

k)       Spring_0800_IOC_AutoWire

l)         byName

m)     byType

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <beanname="userDAO"class="com.bjsxt.dao.impl.UserDAOImpl">

     <propertyname="daoId"value="1"></property>

 </bean>

 <beanname="userDAO2"class="com.bjsxt.dao.impl.UserDAOImpl">

     <propertyname="daoId"value="2"></property>

 </bean>

 <beanid="userService"class="com.bjsxt.service.UserService"scope="prototype"autowire="byName">

 </bean>

</beans>

7,生命周期

n)       Spring_0900_IOC_Life_Cycle

o)       lazy-init (不重要)----用到的时候在初始化这个bean

p)       init-method destroy-methd 不要和prototype一起用(了解)

一,springIOC  Annotation(注解)配置

1.不足:如果没有源码,就无法运用annotation,只能使用xml

第一步:

修改xml文件,在beans.xml文件中写上<context:annotation-config/>初始化相应的标签,将相关的属性注入到spring容器中,参考spingAPI

2.        @Autowired(一般不使用这个注解)

默认按类型by type,一般设置在属性的set方法中,自动初始化一个类的对象并将其装配到sping容器中如下:@Autowired

  publicvoid setUserDAO(@Qualifier("userDao") UserDAO userDAO) {

              this.userDAO =userDAO;

        }

a)        如果想用byName,需要使用@Qulifier

b)       写在private field将注写在属性上(第三种注入形式)(不建议,破坏封装)

c)        如果写在set上,@qualifier需要写在参数上

3.        @Resource(用的比较多重要)

a)        加入jar包:j2ee/common-annotations.jar

b)       主要用于获取spring容器中的对象

c)        默认按名称注入到容器中,如果没有定义名称再按类型

一般会指定特定名称如:

@Resource(name="userDao")

       publicvoid setUserDAO( UserDAO userDAO) {

              this.userDAO =userDAO;

   }

d)       初始化对象的名字默认为类名首字母小写

4.        @Component @Service @Controller@Repository

在beans.xml文件中加入这句<context:component-scanbase-package="com.bjsxt"/>,意思是扫描com.bjsxt这个包,包含下面的子包,扫描到哪个类含有@Component,则将这个类初始化一个对象并注入到sping容器中如将userDao注入到spring容器中:

package com.bjsxt.dao.impl;

import org.springframework.stereotype.Component;

import com.bjsxt.dao.UserDAO;

import com.bjsxt.model.User;

 

@Component("userDao")

public class UserDAOImpl implementsUserDAO {

       publicvoid save(User user) {

              System.out.println("user saved!");

       }

}

a)        一般情况下自己定义bean的名字如:@Component(“userDao”),在set方法上使用@Resource获取注入到spring容器的这个对象如:@Resource(name="userDao")

5.        @Scope

6.        @PostConstruct = init-method;@PreDestroy = destroy-method;

四、什么是AOP

面向切面编程Aspect-Oriented-Programming

a)        是对面向对象的思维方式的有力补充

Spring_1400_AOP_Introduction

好处:可以动态的添加和删除在切面上的逻辑而不影响原来的执行代码

b)       Filter

c)        Struts2的interceptor

概念:

d)       JoinPoint

e)        PointCut

f)        Aspect(切面)

g)       Advice

h)       Target

i)         Weave

Spring AOP配置与应用

两种方式:

a)        使用Annotation 参考项目(Spring_1500_AOP_Annotation)

b)       使用xml 参考项目(Spring_1600_AOP_XML)

Annotation

c)        加上对应的xsd文件spring-aop.xsd

d)       beans.xml 文件加上<aop:aspectj-autoproxy/>

e)        此时就可以解析对应的Annotation了

f)        建立我们的拦截类

g)       用@Aspect注解这个类

h)       建立处理方法

i)         用@Before来注解方法

j)         写明白切入点(execution …….)

k)       让spring对我们的拦截器类进行管理@Component

常见的Annotation:

l)         @Pointcut

m)     @Before

n)       @AfterReturning

o)       @AfterThrowing

p)       @After

q)       @Around

xml配置AOP

r)        把interceptor对象初始化

s)        <aop:config

                       i.             <aop:aspect …..

1.        <aop:pointcut

2.        <aop:before

五、Spring整合Hibernate

Spring 指定datasource 连接数据库

百度spring dbcp连接池的配置在bean.xml文件中的配置如下(项目参考:《Spring_1700_Spring_DataSource》):

<bean

       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

              <propertyname="locations">

                     <value>classpath:jdbc.properties</value>

              </property>

</bean>

       <beanid="dataSource"destroy-method="close"

              class="org.apache.commons.dbcp.BasicDataSource">

              <propertyname="driverClassName"

                     value="${jdbc.driverClassName}"/>

              <propertyname="url"value="${jdbc.url}"/>

              <propertyname="username"value="${jdbc.username}"/>

              <propertyname="password"value="${jdbc.password}"/>

</bean>

a)        在DAO或者Service中注入dataSource

b)       在Spring中可以使用PropertyPlaceHolderConfigure来读取Properties文件的内容

Spring整合Hibernate bean.xml文件中的配置如下(项目参考:《Spring_1700_Spring_DataSource》):

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

          http://www.springframework.org/schema/context

          http://www.springframework.org/schema/context/spring-context-2.5.xsd

          http://www.springframework.org/schema/aop

           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

       <context:annotation-config/>

       <context:component-scanbase-package="com.bjsxt"/>

 

       <bean

              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

              <propertyname="locations">

                     <value>classpath:jdbc.properties</value>

              </property>

       </bean>

 

       <beanid="dataSource"destroy-method="close"

              class="org.apache.commons.dbcp.BasicDataSource">

              <propertyname="driverClassName"

                     value="${jdbc.driverClassName}"/>

              <propertyname="url"value="${jdbc.url}"/>

              <propertyname="username"value="${jdbc.username}"/>

              <propertyname="password"value="${jdbc.password}"/>

       </bean>

      

       <beanid="sessionFactory"

              class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

              <propertyname="dataSource"ref="dataSource"/>

              <propertyname="annotatedClasses">

                     <list>

                            <value>com.bjsxt.model.User</value>

                     </list>

              </property>

              <propertyname="hibernateProperties">

                     <props>

                            <propkey="hibernate.dialect">

                                   org.hibernate.dialect.MySQLDialect

                            </prop>

                            <propkey="hibernate.show_sql">true</prop>

                     </props>

              </property>

       </bean>

</beans>

c)        引入hibernate 系列jar包

d)       User上加Annotation 如:

package com.bjsxt.model;

 

import javax.persistence.Entity;

importjavax.persistence.GeneratedValue;

import javax.persistence.Id;

 

@Entity

public class User {

       privateint id;

       privateString name;

      

       @Id

       @GeneratedValue

       publicint getId() {

              returnid;

       }

       publicvoid setId(int id) {

              this.id = id;

       }

       publicString getName() {

              returnname;

       }

       publicvoid setName(String name) {

              this.name =name;

       }

      

}

e)        UserDAO中注入SessionFactory对数据库进行操作

f)        jar包问题一个一个解决

声明式的事务管理(参考项目Spring_1800_Spring_Hibernate_Transaction_Annotation)

g)       bean.xml文件的配置

                       i.             加入annotation.xsd

                     ii.             加入txManager bean

                   iii.             申明<tx:annotation-driven

                    iv.             在需要事务的方法上加:@Transactional

如userService里的add方法:

@Transactional(readOnly=true)

       publicvoid add(User user) {

             

                     userDAO.save(user);

                     Loglog = new Log();

                     log.setMsg("a user saved!");

                     logDAO.save(log);

             

       }

                      v.             需要注意,使用SessionFactory.getCurrentSession 不要使用OpenSession

Bean.xml文件如下所示:

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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-2.5.xsd

          http://www.springframework.org/schema/context

          http://www.springframework.org/schema/context/spring-context-2.5.xsd

          http://www.springframework.org/schema/aop

          http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

          http://www.springframework.org/schema/tx

           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

       <context:annotation-config/>

       <context:component-scanbase-package="com.bjsxt"/>

       <tx:annotation-driventransaction-manager="txManager"/>

 

<!--数据源的连接 -->

       <bean

       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

              <propertyname="locations">

                     <value>classpath:jdbc.properties</value>

              </property>

       </bean>

 

       <beanid="dataSource"destroy-method="close"

              class="org.apache.commons.dbcp.BasicDataSource">

              <propertyname="driverClassName"

                     value="${jdbc.driverClassName}"/>

              <propertyname="url"value="${jdbc.url}"/>

              <propertyname="username"value="${jdbc.username}"/>

              <propertyname="password"value="${jdbc.password}"/>

       </bean>

 

       <beanid="sessionFactory"

              class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

              <propertyname="dataSource"ref="dataSource"/>

              <propertyname="annotatedClasses">

                     <list>

                            <value>com.bjsxt.model.User</value>

                            <value>com.bjsxt.model.Log</value>

                     </list>

              </property>

              <propertyname="hibernateProperties">

                     <props>

                            <propkey="hibernate.dialect">

                                   org.hibernate.dialect.MySQLDialect

                            </prop>

                            <propkey="hibernate.show_sql">true</prop>

                     </props>

              </property>

       </bean>

    <!-- hibernate的声明式的是事务管理:

          事务的边界一般在service层,假如需要在操作数据库的过程中,其中一个对数据库进行了增删改查的事务操作,

但其中一个却报异常,此时需要回滚数据库,只能回滚其中的一个DAO的数据。这里因为和数据库有连接,所以这里将sessionFactory注入进来

      -->

       <beanid="txManager"

              class="org.springframework.orm.hibernate3.HibernateTransactionManager">

              <propertyname="sessionFactory"ref="sessionFactory"/>

       </bean>

</beans>

h)       @Transactional详解(Annotation 配置)

                       i.             什么时候rollback

1.        运行期异常,非运行期异常不会触发rollback

2.        必须uncheck (没有catch)

3.        不管什么异常,只要你catch了,spring就会放弃管理

4.        事务传播特性:propagation_required假如方法A调用了方法B,A中已经有了事务,则B不需要重新创建一个事务,沿用方法A的事务

5.        readOnly=true  设置为只读相当于只能查询数据库五发对数据库进行增,删,改操作。@Transactional(readOnly=true)

i)         xml(推荐,可以同时配置好多方法)bean.xml文件的配置如下:

(xml配置不需要加这句话:<tx:annotation-driventransaction-manager="txManager"/>)

j)         spring整合hibernate的时候使用packagesToScan属性,可以让spring自动扫描对应包下面的实体类如下bean.xml文件配置

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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-2.5.xsd

           http://www.springframework.org/schema/context

          http://www.springframework.org/schema/context/spring-context-2.5.xsd

          http://www.springframework.org/schema/aop

          http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

           http://www.springframework.org/schema/tx

          http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

       <context:annotation-config/>

       <context:component-scanbase-package="com.bjsxt"/>

 

       <bean

              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

              <propertyname="locations">

                     <value>classpath:jdbc.properties</value>

              </property>

       </bean>

 

       <beanid="dataSource"destroy-method="close"

              class="org.apache.commons.dbcp.BasicDataSource">

              <propertyname="driverClassName"

                     value="${jdbc.driverClassName}"/>

              <propertyname="url"value="${jdbc.url}"/>

              <propertyname="username"value="${jdbc.username}"/>

              <propertyname="password"value="${jdbc.password}"/>

       </bean>

 

       <beanid="sessionFactory"

              class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

              <propertyname="dataSource"ref="dataSource"/>

              <!--

      <propertyname="annotatedClasses">

         <list>

            <value>com.bjsxt.model.User</value>

            <value>com.bjsxt.model.Log</value>

         </list>

      </property>

       -->

//以下是直接扫描这个包下所有类,不需要一个个配置

               <propertyname="packagesToScan">

                     <list>

                            <value>com.bjsxt.model</value>

                           

                     </list>

              </property>

              <propertyname="hibernateProperties">

                     <props>

                            <propkey="hibernate.dialect">

                                   org.hibernate.dialect.MySQLDialect

                            </prop>

                            <propkey="hibernate.show_sql">true</prop>

                     </props>

              </property>

       </bean>

 

       <beanid="txManager"

              class="org.springframework.orm.hibernate3.HibernateTransactionManager">

              <propertyname="sessionFactory"ref="sessionFactory"/>

       </bean>

 

       <aop:config>

              <aop:pointcutid="bussinessService"

                     expression="execution(public *com.bjsxt.service..*.*(..))"/>

              <aop:advisorpointcut-ref="bussinessService"

                     advice-ref="txAdvice"/>

       </aop:config>

 

       <tx:adviceid="txAdvice"transaction-manager="txManager">

              <tx:attributes>

                     <tx:methodname="getUser"read-only="true"/>

                     <tx:methodname="add*"propagation="REQUIRED"/>

              </tx:attributes>

       </tx:advice>

</beans>

k)       hibernate对于声明式事务管理有HibernateTemplate、HibernateCallback、HibernateDaoSupport(不重要)这几个简便的方式参考项目(Spring_2000_Spring_Hibernate_HibernateTemplate)

HibernateTemplate是一种设计模式叫做:模板方法

                       i.             Callback:回调/钩子函数

                     ii.             第一种:(常用)

1.        在spring中初始化HibernateTemplate,注入sessionFactory

bean.xml文件配置如下:

<beanid="hibernateTemplate"class="org.springframework.orm.hibernate3.HibernateTemplate">

              <propertyname="sessionFactory"ref="sessionFactory"></property>

       </bean>

2.        DAO里注入HibernateTemplate

3.        DAO层里面save方法可以直接写成:getHibernateTemplate.save();

六,项目分层架构以及Struts2.1.6+ Spring2.5.6 + Hibernate3.3.2的整合

1、单独使用Hibernate访问数据库参考项目《Spring_2300_Registration_4》

单独Hibernate需要的jar包:

antlr-2.7.6.jar,commons-collections-3.1.jar,dom4j-1.6.1.jar,ejb3-persistence.jar,hibernate-annotations.jar,hibernate-common-annotations.jar, hibernate3.jar,javassist-3.9.0.GA.jar, jta-1.1.jar, mysql-connector-java-3.1.13-bin.jar, slf4j-api-1.5.8.jar,slf4j-log4j12-1.5.8.jar,log4j-1.2.15.jar

2、使用Hibernate和Struts2访问数据库参考项目《Spring_2300_Registration_5》

单独Struts2需要的jar包:commons-fileupload-1.2.1.jar,commons-io-1.3.2.jar,commons-logging-1.1.1.jar,freemarker-2.3.13.jar, ognl-2.6.11.jar,struts2-core-2.1.6.jar, xwork-2.1.2.jar

3、写好implement层使用eclipse可以快捷生成interface层的代码,右键—>refactoràextract interface

4Struts2.1.6+ Spring2.5.6 + Hibernate3.3.2参项目《Spring_2300_Registration_7

需要的jar包列表

jar包名称

所在位置

说明

antlr-2.7.6.jar

hibernate/lib/required

解析HQL

aspectjrt

spring/lib/aspectj

AOP

aspectjweaver

..

AOP

cglib-nodep-2.1_3.jar

spring/lib/cglib

代理,二进制增强

common-annotations.jar

spring/lib/j2ee

@Resource

commons-collections-3.1.jar

hibernate/lib/required

集合框架

commons-fileupload-1.2.1.jar

struts/lib

struts

commons-io-1.3.2

struts/lib

struts

commons-logging-1.1.1

单独下载,删除1.0.4(struts/lib)

struts

spring

dom4j-1.6.1.jar

hibernate/required

解析xml

ejb3-persistence.jar

hibernate-annotation/lib

@Entity

freemarker-2.3.13

struts/lib

struts

hibernate3.jar

hibernate

 

hibernate-annotations

hibernate-annotation/

 

hibernate-common-annotations

hibernate-annotation/lib

 

javassist-3.9.0.GA.jar

hiberante/lib/required

hibernate

jta-1.1.jar

..

hibernate transaction

junit4.5

 

 

mysql-

 

 

ognl-2.6.11.jar

struts/lib

 

slf4j-api-1.5.8.jar

hibernate/lib/required

hibernate-log

slf4j-nop-1.5.8.jar

hibernate/lib/required

 

spring.jar

spring/dist

 

struts2-core-2.1.6.jar

struts/lib

 

xwork-2.1.2.jar

struts/lib

struts2

commons-dbcp

spring/lib/jarkata-commons

 

commons-pool.jar

..

 

struts2-spring-plugin-2.1.6.jar

struts/lib

 

步骤

a)        加入jar包

b)       首先整合Spring + Hibernate

                       i.             建立对应的package

1.        dao / dao.impl / model /service / service.impl/ test

                     ii.             建立spring的配置文件(建议自己保留一份经常使用的配置文件,以后用到的时候直接copy改)

                   iii.             建立数据库

                    iv.             加入Hibernate注解

1.        在实体类上加相应注解@Entity @Id等

2.        在beans配置文件配置对应的实体类,使之受管

                      v.             写dao service的实现

                    vi.             加入Spring注解

1.        在对应Service及DAO实现中加入@Component,让spring对其初始化

2.        在Service上加入@Transactional或者使用xml方式(此处建议后者,因为更简单)

3.        在DAO中注入sessionFactory

4.        在Service中注入DAO

5.        写DAO与Service的实现

                  vii.             写测试

c)        整合Struts2

                       i.             结合点:Struts2的Action由Struts2-Spring-plugin插件产生

                     ii.             步骤:

1.        修改web.xml加入 struts的filter

2.        再加入spring的listener,这样的话,webapp一旦启动,spring容器就初始化了

3.        web.xml配置文件如下:

<?xmlversion="1.0"encoding="UTF-8"?>

<web-appversion="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">

       <welcome-file-list>

              <welcome-file>index.jsp</welcome-file>

       </welcome-file-list>

       <!-- web容器启动后就启动了spring容器 -->

   <listener>

              <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

              <!-- default:/WEB-INF/applicationContext.xml -->

       </listener>

       <!-- 加载并初始化spring容器的配置文件beans.xml -->

       <context-param>

              <param-name>contextConfigLocation</param-name>

              <!--<param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>  -->

              <param-value>classpath:beans.xml</param-value>

       </context-param>

      

       <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>

 

</web-app>

                   iii.             struts的读常量:

1.        struts-default.xml

2.        struts-plugin.xml

3.        struts.xml

4.        struts.properties

5.        web.xml

                    iv.             中文问题:

1.        Struts2.1.8已经修正,只需要改i18n.encoding = gbk

2.        使用spring的characterencoding

3.        需要严格注意filter的顺序

4.        需要加到Struts2的filter前面

                      v.             LazyInitializationException

1.        在Struts2的配置文件的filter前加OpenSessionInViewFilter这个filter,扩大sessionFactory的范围,到jsp加载完数据再关闭session

注意:在我们没有手动配置Transaction的时候此时默认的Transaction在Dao层,OpenSessionInViewFilter默认的Transaction为read-only(只读)也就是我们只能查询数据库,不能进行增删改操作

各种Filter的配置参考项目《Spring_3200_Registration_10》web.xml文件如下:

<?xmlversion="1.0"encoding="UTF-8"?>

<web-appversion="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">

       <welcome-file-list>

              <welcome-file>index.jsp</welcome-file>

       </welcome-file-list>

 

       <listener>

              <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

              <!-- default:/WEB-INF/applicationContext.xml -->

       </listener>

 

       <context-param>

              <param-name>contextConfigLocation</param-name>

              <!--<param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>  -->

              <param-value>classpath:beans.xml</param-value>

       </context-param>

      

      

       <filter>

              <filter-name>encodingFilter</filter-name>

              <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

              <init-param>

                     <param-name>encoding</param-name>

                     <param-value>GBK</param-value>

              </init-param>

       </filter>

      

       <filter-mapping>

              <filter-name>encodingFilter</filter-name>

              <url-pattern>/*</url-pattern>

       </filter-mapping>

      

       <filter>

              <filter-name>openSessionInView</filter-name>

              <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>

              <init-param>

                     <param-name>sessionFactoryBeanName</param-name>

                     <param-value>sf</param-value>

              </init-param>

       </filter>

      

       <filter-mapping>

              <filter-name>openSessionInView</filter-name>

              <url-pattern>/*</url-pattern>

       </filter-mapping>

      

       <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>

</web-app>

Bean.xml文件如下:

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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-2.5.xsd

          http://www.springframework.org/schema/context

           http://www.springframework.org/schema/context/spring-context-2.5.xsd

          http://www.springframework.org/schema/aop

          http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

          http://www.springframework.org/schema/tx

           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

       <context:annotation-config/>

       <context:component-scanbase-package="com.bjsxt"/>

 

       <!--

      <bean id="dataSource"

      class="org.apache.commons.dbcp.BasicDataSource"

      destroy-method="close">

     

     

      <propertyname="driverClassName" value="com.mysql.jdbc.Driver" />

      <property name="url"value="jdbc:mysql://localhost:3306/spring" />

      <property name="username"value="root" />

      <property name="password"value="bjsxt" />

      </bean>

   -->

 

       <bean

              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

              <propertyname="locations">

                     <value>classpath:jdbc.properties</value>

              </property>

       </bean>

 

       <beanid="dataSource"destroy-method="close"

              class="org.apache.commons.dbcp.BasicDataSource">

              <propertyname="driverClassName"

                     value="${jdbc.driverClassName}"/>

              <propertyname="url"value="${jdbc.url}"/>

              <propertyname="username"value="${jdbc.username}"/>

              <propertyname="password"value="${jdbc.password}"/>

       </bean>

      

      

 

       <beanid="sf"

              class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

              <propertyname="dataSource"ref="dataSource"/>

              <!--

      <propertyname="annotatedClasses">

         <list>

            <value>com.bjsxt.model.User</value>

            <value>com.bjsxt.model.Log</value>

         </list>

      </property>

       -->

               <propertyname="packagesToScan">

                     <list>

                            <value>com.bjsxt.registration.model</value>

                           

                     </list>

              </property>

              <propertyname="hibernateProperties">

                     <props>

                            <propkey="hibernate.dialect">

                                   org.hibernate.dialect.MySQLDialect

                            </prop>

                            <propkey="hibernate.show_sql">true</prop>

                     </props>

              </property>

       </bean>

      

       <beanid="hibernateTemplate"class="org.springframework.orm.hibernate3.HibernateTemplate">

              <propertyname="sessionFactory"ref="sf"></property>

       </bean>

 

       <beanid="txManager"

              class="org.springframework.orm.hibernate3.HibernateTransactionManager">

              <propertyname="sessionFactory"ref="sf"/>

       </bean>

 

       <aop:config>

              <aop:pointcutid="bussinessService"

                     expression="execution(public *com.bjsxt.registration.service.*.*(..))"/>

              <aop:advisorpointcut-ref="bussinessService"

                     advice-ref="txAdvice"/>

       </aop:config>

 

       <tx:adviceid="txAdvice"transaction-manager="txManager">

              <tx:attributes>

                     <tx:methodname="exists"read-only="true"/>

                     <tx:methodname="add*"propagation="REQUIRED"/>

              </tx:attributes>

       </tx:advice>

 

</beans>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

愚人节第二天

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

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

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

打赏作者

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

抵扣说明:

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

余额充值