SSH(三)

在Spring中引用属性文件:
    优点:
        1.防止随意更改jdbc的连接
        2.给不懂代码的人使用
    步骤:
        1.数据库连接信息写在属性文件中
        范例:#jdbc.properties

1  jdbc.driver = com.mysql.jdbc.Driver
2  jdbc.url = jdbc:mysql://localhost/db
3  jdbc.username = root
4  jdbc.password = root

2.采用PropertyPlaceholderConfigurer可以引入属性文件,在Spring配置文件中采用诸如${jdbc.url}的方式引用属性值

3.PropertyPlaceholderConfigurer的配置用到了List类型属性
        
Spring自动装配:
    1.定义:Spring可以根据属性类型、名称等自动进行注入
    2.使用方法:设置<bean>元素的autowire属性
        a.autowire属性取值:
            取值                            说明
             no                默认值。Spring 默认不进行自动装配,必须显式指定依赖对象
             byName            根据属性名自动装配。Spring 自动查找与属性名相同的id,如果找到,则自动注入,否则什么都不做
             byType            根据属性的类型自动装配。Spring 自动查找与属性类型相同的Bean,如果刚好找到★唯一★的那个,则自动注入;如果找到多个与属性类型相同的Bean,则抛出异常;如果没找              到,就什么也不做
             constructor    和byType 类似,不过它针对构造方法。如果 Spring 找到一个Bean和构造方法的参数类型相匹配,则通过构造注入该依赖对象;如果找不到,将抛出异常
        b.可以为<beans>元素设置default-autowire属性,影响全局
        c.<bean>节点上autowire的设置可以覆盖全局设置
    3.一般情况下,使用byName的方式更合适。Spring3推荐使用带参构造或者使用在setXxx方法上使用@Required注解

4.注意:自动装配使得配置文件可以非常简洁,但同时也造成组件之间的依赖关系不明确,容易引发一些潜在的错误,在实际项目中要谨慎使用

拆分配置文件 -- 拆分策略
    1.公用配置+每个系统模块一个单独配置文件(包含dao、service、action)
    2.公用配置+DAO Bean配置+业务逻辑Bean配置+Action Bean配置
    3.两种策略各有特色,适用于不同场合

方法:
        a.配制Spring集成时:
            1)配制ContextLoadListener的contextConfigLocation属性
            2)配置多个配置文件用逗号隔开
            3)使用通配符
        b.使用<import  resource="xxx.xml"/>方式

使用注解实现IoC:
    1.注解方式将Bean的定义信息和Bean实现类结合在一起
    2.Spring提供的注解:
        @Component
        @Repository    :用于标注DAO类
        @Service    :用于标注业务类
        @Controller    :用于标注控制器类
    范例:

1 @Repository("userDao")
2 public class UserDaoImpl implements UserDao {
3         …
4 }

等效:与在XML配置文件中编写

1 <bean id="userDao" class="com.xuetang9.dao.impl.UserDaoImpl" /> 

3.使用@Autowired注解实现Bean的自动装配
        a.默认按类型匹配
        b.可以使用@Qualifier指定Bean的名称
    范例:
    a.可以对类的成员变量进行标注

1 @Service("userService")
2 public class UserServiceImpl implements UserService {
3         @Autowired
4         @Qualifier("userDao")
5         private UserDao userDao;
6         ……
7 }

b.也可以对方法的入参进行标注

1  @Service("userService")
2   public class UserServiceImpl implements UserService {
3         private UserDao userDao;
4         @Autowired
5         public void setUserDao(UserDao userDao) {
6            this.userDao = userDao;
7         }
8    }

4.使用@Scope注解指定Bean的作用域
    范例:

1  @Scope("prototype")
2  @Service("userService")
3   public class UserService implements UserService {
4         ……
5   }

5.使用注解信息启动Spring容器
    范例:

1  <beans xmlns="http://www.springframework.org/schema/beans"
2         xmlns:context="http://www.springframework.org/schema/context"
3         xsi:schemaLocation="……
4         http://www.springframework.org/schema/context
5         http://www.springframework.org/schema/context/spring-context-3.2.xsd">
6         <!-- 扫描包中注解标注的类 -->
7         <!-- 指定需要扫描的基类包,多个包可用逗号隔开 -->
8         <context:component-scan base-package="com.xuetang9.demo.service, com.xuetang9.demo.dao" />
9  </beans>

使用注解实现事务处理:
    1.在Spring配置文件中配置事务管理类,并添加对注解配置的事务的支持
    范例:

1 <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
2         <property name="sessionFactory" ref="sessionFactory" />
3 </bean>
4 <tx:annotation-driven transaction-manager="txManager" />

2.使用@Transactional为方法添加事务支持
    范例:

1  public class UserServiceImpl implements UserService {
2         @Transactional(readOnly=true)
3         public User login(User user){
4             ......
5         }
6   }

[email protected]属性
    属性                        类型                                                                说明
    propagation                枚举型:Propagation                                        可选的传播性设置。使用举例:@Transactional(propagation=Propagation.REQUIRES_NEW)
    isolation                枚举型:Isolation                                        可选的隔离性级别。使用举例:@Transactional(isolation=Isolation.READ_COMMITTED)
    readOnly                布尔型                                                    是否为只读型事务。使用举例:@Transactional(readOnly=true)
    timeout                    sint型(以秒为单位)                                    事务超时。使用举例:Transactional(timeout=10)
    rollbackFor                一组 Class 类的实例,必须是Throwable的子类            一组异常类,遇到时 必须回滚。使用举例:@Transactional(rollbackFor={SQLException.class}),多个异常用逗号隔开
    rollbackForClassName    一组 Class 类的名字,必须是Throwable的子类            一组异常类名,遇到时 必须回滚。使用举例:@Transactional(rollbackForClassName={"SQLException"}),多个异常用逗号隔开
    noRollbackFor            一组 Class 类的实例,必须是Throwable的子类            一组异常类,遇到时 必须不回滚
    noRollbackForClassName    一组 Class 类的名字,必须是Throwable的子类            一组异常类名,遇到时 必须不回滚
    
范例:
1.hibernate的配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 8         <property name="hibernate.connection.password">root</property>
 9         <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatedb</property>
10         <property name="hibernate.connection.username">root</property>
11         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
12     </session-factory>
13 </hibernate-configuration>

2.Struts的配置文件

3.Spring的配置文件
a1.spring与hibernate的配置文件分离 -- applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
10         http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
12
13     <!-- 配置SessionFactory -->
14     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
15         <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
16     </bean>
17     <!-- 配置事务 -->
18     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
19         <property name="sessionFactory" ref="sessionFactory"></property>
20     </bean>
21     <tx:advice id="tx" transaction-manager="transactionManager">
22         <tx:attributes>
23             <tx:method name="search*" propagation="REQUIRED" read-only="true" timeout="5"/>
24             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
25         </tx:attributes>
26     </tx:advice>
27     <aop:config>
28         <aop:pointcut id="txpointcut" expression="execution(* com.Elastic.SpringDemo4.ivy.service..*.*(..))" />
29         <aop:advisor advice-ref="tx" pointcut-ref="txpointcut"/>
30     </aop:config>
31 </beans>

a2.spring与hibernate集成 -- applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
10         http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
12
13     <!-- 配置DataSource,c3p0的方式配置数据源 -->
14     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
15         <property name="user" value="root"></property>
16         <property name="password" value="root"></property>
17         <property name="jdbcUrl" value="jdbc:mysql://localhost/hibernatedb"></property>
18         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
19         <property name="initialPoolSize" value="10"></property>
20         <property name="minPoolSize" value="5"></property>
21         <property name="maxPoolSize" value="100"></property>
22         <property name="acquireIncrement" value="3"></property>
23         <property name="acquireRetryAttempts" value="3"></property>
24         <property name="acquireRetryDelay" value="5"></property>
25         <property name="idleConnectionTestPeriod" value="60"></property>
26     </bean>
27
28     <!-- 配置SessionFactory -->
29     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
30         <property name="dataSource" ref="dataSource"></property>
31         <property name="hibernateProperties">
32             <props>
33                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
34                 <prop key="show_sql">true</prop>
35                 <prop key="format_sql">true</prop>
36             </props>
37         </property>
38         <property name="mappingLocations">
39             <list>
40                 <value>classpath:com/Elastic/SpringDemo4/ivy/entity/*.hbm.xml</value>
41             </list>
42         </property>
43         <!-- 加载持久化类也可以使用<property name="packagesToScan" value="com.Elastic.SpringDemo4.ivy.entity" /> -->
44         <!-- <property name="annotatedClasses">
45             <list>
46                 <value>com.Elastic.SpringDemo4.ivy.entity.User</value>
47             </list>
48         </property> -->
49     </bean>
50     <!-- 配置事务 -->
51     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
52         <property name="sessionFactory" ref="sessionFactory"></property>
53     </bean>
54     <tx:advice id="tx" transaction-manager="transactionManager">
55         <tx:attributes>
56             <tx:method name="search*" propagation="REQUIRED" read-only="true" timeout="5"/>
57             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
58         </tx:attributes>
59     </tx:advice>
60     <aop:config>
61         <aop:pointcut id="txpointcut" expression="execution(* com.Elastic.SpringDemo4.ivy.service..*.*(..))" />
62         <aop:advisor advice-ref="tx" pointcut-ref="txpointcut"/>
63     </aop:config>
64 </beans>

a3.在Spring中引用属性文件 -- applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
10         http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
12     <!-- 配置属性文件的读取 -->
13     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
14         <property name="location" value="classpath:jdbc.properties"></property>
15     </bean>
16
17     <!-- 配置DataSource -->
18     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
19         <property name="user" value="${jdbc.username}"></property>
20         <property name="password" value="${jdbc.password}"></property>
21         <property name="jdbcUrl" value="${jdbc.url}"></property>
22         <property name="driverClass" value="${jdbc.driver}"></property>
23         <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
24         <property name="minPoolSize" value="${jdbc.minPoolSize}"></property>
25         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
26         <property name="acquireIncrement" value="${jdbc.acquireIncrement}"></property>
27         <property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"></property>
28         <property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}"></property>
29         <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"></property>
30     </bean>
31
32     <!-- 配置SessionFactory -->
33     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
34         <property name="dataSource" ref="dataSource"></property>
35         <property name="hibernateProperties">
36             <props>
37                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
38                 <prop key="show_sql">true</prop>
39                 <prop key="format_sql">true</prop>
40             </props>
41         </property>
42         <property name="mappingLocations">
43             <list>
44                 <value>classpath:com/Elastic/SpringDemo4/ivy/entity/*.hbm.xml</value>
45             </list>
46         </property>
47     </bean>
48     <!-- 配置事务 -->
49     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
50         <property name="sessionFactory" ref="sessionFactory"></property>
51     </bean>
52     <tx:advice id="tx" transaction-manager="transactionManager">
53         <tx:attributes>
54             <tx:method name="search*" propagation="REQUIRED" read-only="true" timeout="5"/>
55             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
56         </tx:attributes>
57     </tx:advice>
58     <aop:config>
59         <aop:pointcut id="txpointcut" expression="execution(* com.Elastic.SpringDemo4.ivy.service..*.*(..))" />
60         <aop:advisor advice-ref="tx" pointcut-ref="txpointcut"/>
61     </aop:config>
62 </beans>

a4.当有多个Spring的配置文件时 -- applicationContext.xml
方法二:applicationContext配置中用,<import resource="">

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
10         http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
12     <!-- 配置属性文件的读取 -->
13     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
14         <property name="location" value="classpath:jdbc.properties"></property>
15     </bean>
16
17     <!-- 配置DataSource -->
18     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
19         <property name="user" value="${jdbc.username}"></property>
20         <property name="password" value="${jdbc.password}"></property>
21         <property name="jdbcUrl" value="${jdbc.url}"></property>
22         <property name="driverClass" value="${jdbc.driver}"></property>
23         <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
24         <property name="minPoolSize" value="${jdbc.minPoolSize}"></property>
25         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
26         <property name="acquireIncrement" value="${jdbc.acquireIncrement}"></property>
27         <property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"></property>
28         <property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}"></property>
29         <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"></property>
30     </bean>
31
32     <!-- 配置SessionFactory -->
33     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
34         <!-- <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> -->
35         <property name="dataSource" ref="dataSource"></property>
36         <property name="hibernateProperties">
37             <props>
38                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
39                 <prop key="show_sql">true</prop>
40                 <prop key="format_sql">true</prop>
41             </props>
42         </property>
43         <property name="mappingLocations">
44             <list>
45                 <value>classpath:com/Elastic/SpringDemo4/ivy/entity/*.hbm.xml</value>
46             </list>
47         </property>
48     </bean>
49     <!-- 配置事务 -->
50     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
51         <property name="sessionFactory" ref="sessionFactory"></property>
52     </bean>
53     <tx:advice id="tx" transaction-manager="transactionManager">
54         <tx:attributes>
55             <tx:method name="search*" propagation="REQUIRED" read-only="true" timeout="5"/>
56             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
57         </tx:attributes>
58     </tx:advice>
59     <aop:config>
60         <aop:pointcut id="txpointcut" expression="execution(* com.Elastic.SpringDemo4.ivy.service..*.*(..))" />
61         <aop:advisor advice-ref="tx" pointcut-ref="txpointcut"/>
62     </aop:config>
63
64     <!-- DAO -->
65     <import resource="Spring-DAO.xml"/>
66
67     <!-- Service -->
68     <import resource="Spring-Service.xml"/>
69 </beans>

a5.使用注解 -- applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans
 8         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 9         http://www.springframework.org/schema/aop
10         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
11         http://www.springframework.org/schema/tx
12         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
13         http://www.springframework.org/schema/context
14         http://www.springframework.org/schema/context/spring-context-3.2.xsd">
15     <!-- 配置属性文件的读取 -->
16     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
17         <property name="location" value="classpath:jdbc.properties"></property>
18     </bean>
19
20     <!-- 配置DataSource -->
21     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
22         <property name="user" value="${jdbc.username}"></property>
23         <property name="password" value="${jdbc.password}"></property>
24         <property name="jdbcUrl" value="${jdbc.url}"></property>
25         <property name="driverClass" value="${jdbc.driver}"></property>
26         <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
27         <property name="minPoolSize" value="${jdbc.minPoolSize}"></property>
28         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
29         <property name="acquireIncrement" value="${jdbc.acquireIncrement}"></property>
30         <property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"></property>
31         <property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}"></property>
32         <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"></property>
33     </bean>
34
35     <!-- 配置SessionFactory -->
36     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
37         <property name="dataSource" ref="dataSource"></property>
38         <property name="hibernateProperties">
39             <props>
40                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
41                 <prop key="show_sql">true</prop>
42                 <prop key="format_sql">true</prop>
43             </props>
44         </property>
45         <property name="mappingLocations">
46             <list>
47                 <value>classpath:com/Elastic/SpringDemo4/ivy/entity/*.hbm.xml</value>
48             </list>
49         </property>
50     </bean>
51
52     <!-- 配置事务 -->
53     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
54         <property name="sessionFactory" ref="sessionFactory"></property>
55     </bean>
56     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
57
58     <!-- 使用注解配置DAO\Service -->
59     <context:component-scan base-package="com.Elastic.SpringDemo4.ivy"></context:component-scan>
60 </beans>

b.Spring-DAO.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 7
 8     <bean id="userDao" class="com.Elastic.SpringDemo4.ivy.dao.impl.UserDaoImpl">
 9         <property name="sessionFactory" ref="sessionFactory"></property>
10     </bean>
11
12 </beans>

b2.Spring自动配置 -- Spring-DAO.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 7
 8     <bean id="userDao" class="com.Elastic.SpringDemo4.ivy.dao.impl.UserDaoImpl" autowire="byName">
 9     </bean>
10 </beans>

c.Spring-Service.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 7
 8     <bean id="userService" class="com.Elastic.SpringDemo4.ivy.service.impl.UserServiceImpl">
 9         <property name="userDao" ref="userDao"></property>
10     </bean>
11 </beans>

c2.Spring自动配置 -- Spring-Service.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 7
 8     <bean id="userService" class="com.Elastic.SpringDemo4.ivy.service.impl.UserServiceImpl" autowire="byName">
 9     </bean>
10 </beans>

4.动态Java项目的配置
a.web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 3     <display-name>SpringDemo4_ivy</display-name>
 4     <welcome-file-list>
 5         <welcome-file>index.html</welcome-file>
 6         <welcome-file>index.htm</welcome-file>
 7         <welcome-file>index.jsp</welcome-file>
 8         <welcome-file>default.html</welcome-file>
 9         <welcome-file>default.htm</welcome-file>
10         <welcome-file>default.jsp</welcome-file>
11     </welcome-file-list>
12
13     <!-- 配置Spring文件的位置 -->
14     <context-param>
15         <param-name>contextConfigLocation</param-name>
16         <param-value>classpath:applicationContext.xml</param-value>
17     </context-param>
18
19     <!-- 配置Spring监听器 -->
20     <listener>
21         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
22     </listener>
23
24     <!-- OpenSessionInView -->
25     <filter>
26         <filter-name>OpenSessionInView</filter-name>
27         <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
28     </filter>
29     <filter-mapping>
30         <filter-name>OpenSessionInView</filter-name>
31         <url-pattern>/*</url-pattern>
32     </filter-mapping>
33
34     <!-- 配置Struts2核心过滤器 -->
35     <filter>
36         <filter-name>Struts2</filter-name>
37         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
38     </filter>
39     <filter-mapping>
40         <filter-name>Struts2</filter-name>
41         <url-pattern>/*</url-pattern>
42     </filter-mapping>
43
44     <!-- 设置session过期时间(单位:分钟) -->
45     <session-config>
46         <session-timeout>20</session-timeout>
47     </session-config>
48
49 </web-app>

b.当有多个Spring的配置文件时
方法一:context-param配置中用逗号隔开

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 3     <display-name>SpringDemo4_ivy</display-name>
 4     <welcome-file-list>
 5         <welcome-file>index.html</welcome-file>
 6         <welcome-file>index.htm</welcome-file>
 7         <welcome-file>index.jsp</welcome-file>
 8         <welcome-file>default.html</welcome-file>
 9         <welcome-file>default.htm</welcome-file>
10         <welcome-file>default.jsp</welcome-file>
11     </welcome-file-list>
12
13     <!-- 配置Spring文件的位置 -->
14     <context-param>
15         <param-name>contextConfigLocation</param-name>
16         <param-value>classpath:applicationContext.xml,classpath:Spring-*.xml</param-value>
17     </context-param>
18
19     <!-- 配置Spring监听器 -->
20     <listener>
21         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
22     </listener>
23
24     <!-- OpenSessionInView -->
25     <filter>
26         <filter-name>OpenSessionInView</filter-name>
27         <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
28     </filter>
29     <filter-mapping>
30         <filter-name>OpenSessionInView</filter-name>
31         <url-pattern>/*</url-pattern>
32     </filter-mapping>
33
34     <!-- 配置Struts2核心过滤器 -->
35     <filter>
36         <filter-name>Struts2</filter-name>
37         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
38     </filter>
39     <filter-mapping>
40         <filter-name>Struts2</filter-name>
41         <url-pattern>/*</url-pattern>
42     </filter-mapping>
43
44     <!-- 设置session过期时间(单位:分钟) -->
45     <session-config>
46         <session-timeout>20</session-timeout>
47     </session-config>
48
49 </web-app>

5.属性文件
a.jdbc.properties

 1 jdbc.username=root
 2 jdbc.password=root
 3 jdbc.url=jdbc:mysql://localhost/hibernatedb
 4 jdbc.driver=com.mysql.jdbc.Driver
 5
 6 # c3p0
 7 jdbc.initialPoolSize=10
 8 jdbc.minPoolSize=5
 9 jdbc.maxPoolSize=100
10 jdbc.acquireIncrement=3
11 jdbc.acquireRetryAttempts=3
12 jdbc.acquireRetryDelay=5
13 jdbc.idleConnectionTestPeriod=60

6.实体类及其配置文件
a.User类

 1 package com.Elastic.SpringDemo4.ivy.entity;
 2
 3 import java.io.Serializable;
 4
 5 public class User implements Serializable{
 6     private String loginName;
 7     private String loginPass;
 8
 9     public String getLoginName() {
10         return loginName;
11     }
12     public void setLoginName(String loginName) {
13         this.loginName = loginName;
14     }
15     public String getLoginPass() {
16         return loginPass;
17     }
18     public void setLoginPass(String loginPass) {
19         this.loginPass = loginPass;
20     }
21
22 }

b.User.hbm.xml

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4 <!-- Generated 2016-7-8 16:52:24 by Hibernate Tools 3.4.0.CR1 -->
 5 <hibernate-mapping>
 6     <class name="com.Elastic.SpringDemo4.ivy.entity.User" table="user">
 7         <id name="loginName" type="java.lang.String">
 8             <column name="userName" />
 9             <generator class="assigned" />
10         </id>
11         <property name="loginPass" type="java.lang.String">
12             <column name="passWord" />
13         </property>
14     </class>
15 </hibernate-mapping>

7.dao包
a.UserDao接口

1 package com.Elastic.SpringDemo4.ivy.dao;
2
3 import java.io.Serializable;
4
5 import com.Elastic.SpringDemo4.ivy.entity.User;
6
7 public interface UserDao {
8     User findById(Serializable id);
9 }

8.dao.impl包
a1.UserDaoImpl

 1 package com.Elastic.SpringDemo4.ivy.dao.impl;
 2
 3 import java.io.Serializable;
 4
 5 import org.hibernate.SessionFactory;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 8 import org.springframework.stereotype.Repository;
 9
10 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
11 import com.Elastic.SpringDemo4.ivy.entity.User;
12
13 public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
14
15     @Override
16     public User findById(Serializable id) {
17         return this.getHibernateTemplate().get(User.class, id);
18     }
19 }

a2.使用注解 -- UserDaoImpl

 1 package com.Elastic.SpringDemo4.ivy.dao.impl;
 2
 3 import java.io.Serializable;
 4
 5 import org.hibernate.SessionFactory;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 8 import org.springframework.stereotype.Repository;
 9
10 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
11 import com.Elastic.SpringDemo4.ivy.entity.User;
12
13 @Repository
14 public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
15
16     @Autowired
17     public UserDaoImpl(SessionFactory sessionFactory) {
18         super.setSessionFactory(sessionFactory);
19     }
20
21     @Override
22     public User findById(Serializable id) {
23         return this.getHibernateTemplate().get(User.class, id);
24     }
25 }

b.使用注解 -- TestUserDaoImpl

 1 package com.Elastic.SpringDemo4.ivy.dao.impl;
 2
 3 import java.io.Serializable;
 4
 5 import org.hibernate.SessionFactory;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 8 import org.springframework.stereotype.Repository;
 9
10 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
11 import com.Elastic.SpringDemo4.ivy.entity.User;
12
13 @Repository
14 public class TestUserDaoImpl extends HibernateDaoSupport implements UserDao {
15
16     @Autowired
17     public TestUserDaoImpl(SessionFactory sessionFactory) {
18         super.setSessionFactory(sessionFactory);
19     }
20
21     @Override
22     public User findById(Serializable id) {
23         return null;
24     }
25 }

9.service包
a.UserService接口

1 package com.Elastic.SpringDemo4.ivy.service;
2
3 import com.Elastic.SpringDemo4.ivy.entity.User;
4
5 public interface UserService {
6     public User search(String name, String pass);
7 }

10.service.impl包
a.UserServiceImpl

 1 package com.Elastic.SpringDemo4.ivy.service.impl;
 2
 3 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
 4 import com.Elastic.SpringDemo4.ivy.entity.User;
 5 import com.Elastic.SpringDemo4.ivy.service.UserService;
 6
 7 public class UserServiceImpl implements UserService {
 8     private UserDao userDao;
 9
10     public UserDao getUserDao() {
11         return userDao;
12     }
13
14     public void setUserDao(UserDao userDao) {
15         this.userDao = userDao;
16     }
17
18     @Override
19     public User search(String name, String pass) {
20         User user = userDao.findById(name);
21         if (null != user && user.getLoginPass().equals(pass)) {
22             return user;
23         }
24         return null;
25     }
26 }

a2.使用注解 -- UserServiceImpl

 1 package com.Elastic.SpringDemo4.ivy.service.impl;
 2
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Qualifier;
 5 import org.springframework.stereotype.Service;
 6 import org.springframework.transaction.annotation.Propagation;
 7 import org.springframework.transaction.annotation.Transactional;
 8
 9 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
10 import com.Elastic.SpringDemo4.ivy.entity.User;
11 import com.Elastic.SpringDemo4.ivy.service.UserService;
12
13 @Service("userService")
14 @Transactional(propagation=Propagation.REQUIRED,rollbackFor={Exception.class,RuntimeException.class})
15 public class UserServiceImpl implements UserService {
16     //方法一
17     @Autowired
18     @Qualifier("userDaoImpl")
19     private UserDao userDao;
20
21     //方法二
22     /*public UserDao getUserDao() {
23         return userDao;
24     }
25
26     @Autowired
27     @Qualifier("testUserDaoImpl")
28     public void setUserDao(UserDao userDao) {
29         this.userDao = userDao;
30     }*/
31
32 //    @Transactional(propagation=Propagation.REQUIRED,readOnly=true,timeout=3,rollbackFor={Exception.class,RuntimeException.class})
33     @Transactional(timeout=3)
34     @Override
35     public User search(String name, String pass) {
36         try {
37             Thread.sleep(4000);
38         } catch (InterruptedException e) {
39             e.printStackTrace();
40         }
41
42         User user = userDao.findById(name);
43         if (null != user && user.getLoginPass().equals(pass)) {
44             return user;
45         }
46         return null;
47     }
48
49     @Transactional
50     public void test() {
51         userDao.findById("");
52     }
53 }

11.action包
a.UserAction

 1 package com.Elastic.SpringDemo4.ivy.action;
 2
 3 import com.Elastic.SpringDemo4.ivy.entity.User;
 4 import com.Elastic.SpringDemo4.ivy.service.UserService;
 5 import com.opensymphony.xwork2.ActionSupport;
 6
 7 public class UserAction extends ActionSupport {
 8     private UserService userService;
 9     private User user;
10
11     public UserService getUserService() {
12         return userService;
13     }
14
15     public void setUserService(UserService userService) {
16         this.userService = userService;
17     }
18
19     public User getUser() {
20         return user;
21     }
22
23     public void setUser(User user) {
24         this.user = user;
25     }
26
27     public String login() {
28         User loginUser =  userService.search(user.getLoginName(), user.getLoginPass());
29         if (null == loginUser) {
30             return ERROR;
31         }
32         return SUCCESS;
33     }
34 }
时间: 2024-10-22 16:12:37

SSH(三)的相关文章

加密,gpg加密,ssh三种转发,openssl,pam 题目

加密,gpg加密,ssh三种转发,openssl,pam 一.仅开放本机两个IP地址中的一个地址172.16.0.X上绑定的sshd和vsftpd服务给172.16.0.0/16网络中除了 172.16.0.0/24网络中的主机之外的所有主机,但允许172.16.0.200访问,每次的用户访问都要记录于日志文件 中,注:其中X为学号 /etc/hosts.allow: sshd,vsftpd: 172.16.0.0/16 EXCEPT 172.16.0.0/24 EXCEPT 172.16.0.

【SSH三个框架】Hibernate第八部分基础:经营-many关系

在Hibernate在-many关系.它通常不使用.由于当数据库查询复杂度太高时. 我们在这里做的是学生和教师,学生可以有多个老师,教师可以有多个学生. watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMDgwMDUzMA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" > 我们首先建立一个学生实体类:Student.java packag

SSH(三)资源分类和日志管理

上篇博文已经分别介绍了如何搭建SSH开发环境以及对SSH三个框架的整合.整合完成之后,我们基本上就可以正常的开始一个基于SSH框架开发的项目了.本篇博文介绍的资源分类和日志管理都是一些锦上添花的配置.利用这些,来清晰我们的思路,便利我们的编程. 先来说说资源分类吧.这里的资源分类是指对项目中代码或者配置文件等的一个分类管理.以下截图中的分类只是参考,主要是对于资源分类管理思想上的重视.我们要知道,一个结构清晰,骨架简洁的项目是极其方便团队开发,同时也可加快新人或者他人对该项目的理解. 再来说说日

SSH架构图及各部分知识点

SSH分别是指:Struts,Spring,Hibernate 下面是SSH三部分简单主要的知识点: Sturts: execute :     execute()方法相当于main()方法,有三种创建模式 : 1 自定义类,类里面不能写main()方法,写个execute方法,返回值为一个字符串,和struts.xml里面的<result name="字符串">对应就行     public String execute() {            return &qu

SSH三大框架的整合

SSH三个框架的知识点 一.Hibernate框架 1. Hibernate的核心配置文件 1.1 数据库信息.连接池配置 1.2 Hibernate信息 1.3 映射配置 1.4 Hibernate核心配置文件 如果单纯使用Hibernate框架,核心配置文件名称hibernate.cfg.xml并且一定要放在src下面,而hibernate和spring整合的时候,hibernate核心配置文件名称和位置没有固定要求的(因为到时候会有一个参数指定其位置). 2. Hibernate映射配置文

ubuntu开启SSH服务,并允许ROOT权限远程登录。

服务器配完ubuntu系统以及LNMP环境以后,想用WINSCP远程登录,就需要开启SSH服务才能支持. SSH服务分为客户端和服务器.顾名思义,我想用WINSCP远程登录Ubuntu服务器,所以需要安装SSH server. OK,下面介绍如何开启SSH服务. 一.检查是否开启SSH服务 因为Ubuntu默认是不安装SSH服务的,所以在安装之前可以查看目前系统是否安装,通过以下命令: ps -e|grep ssh 输出的结果ssh-agent表示ssh-client启动,sshd表示ssh-s

【Struts2+Hibernate3+Spring3】利用SSH整合,完成打印用户表,用户登录、注册、修改密码系统

本文视图尽可能不杂糅其它技术,尽可能少写代码,完成SSH整合.以致于各位在现有网上资料越来越天花龙凤之下,清晰地了解到传说中的三大框架SSH是怎么整合的. 一.SSH的下载 首先SSH的下载就已经是一个难点.SSH三个地方同时推出各自的新技术,已经要求利用Maven完成其版本的同步.毕竟Spring的版本,决定其能整合什么版本的Struts与Hibernate.Spring3.0.5就不能整合Hibernate4.x了.因此本文选取的SSH的版本,分别为struts 2.3.20 GA.Hibe

Cisco设备配置SSH登录

一 试验拓扑 二 Server配置 ①配置hostname和domain name 因为rsa的秘钥是用hostname和domain name产生的 Router(config)#host Server Server(config)#ip domain name test.com ②生成RSA秘钥 当生成rsa秘钥后ssh服务会自动开启,反之会自动关闭 要删除 RSA 密钥对,请使用 crypto key zeroize rsa 全局配置模式命令.删除 RSA 密钥对之后,SSH 服务器将自动

使用eclipse整合ssh项目的例子--lljf(1)

最近向自己单独做一个基于ssh的项目,来预习和巩固自己的Java基础.找了一个实际生活中的定做衣服的例子来做一做,放到博客上给大家一起分享学习,后边会持续更新项目编写时候遇到的困难和使用的技术等. 1.点击新建-->选择Dynamic Web Project -->next-->next..并创建package结果图: 2.创建自己的架包库并导入架包到项目: 平时开发需要使用外部的jar时直接将其拷入WEB-INF/lib下.这个是可以的,但是分类一下会让系统更有条理.eclipse中分

ansible三节点部署k8s

一.部署环境 VMware Workstation 10 centos7 二.主机配置 主机名 ip cpu ram master 192.168.137.10 1 2G node1 192.168.137.11 1 2G node2 192.168.137.12 1 2G 1.每台主机在 /etc/hosts 添加以下内容: 2.对三台主机进行免密设置: 1).CentOS7默认没有启动ssh无密登录,去掉/etc/ssh/sshd_config其中1行的注释,每台服务器都要设置 #Pubke