本博文主要是講解如何搭建一個比較規範的SSH開發環境,以及對它測試【在前面的搭建中,只是整合了SSH框架,可以使用SSH實現功能】,而此次是相對規範的。java
<!-- 禁用動態方法訪問 --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <!-- 配置成開發模式 --> <constant name="struts.devMode" value="true" /> <!-- 配置拓展名爲action --> <constant name="struts.action.extention" value="action" /> <!-- 把主題配置成simple --> <constant name="struts.ui.theme" value="simple" />
<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>*.action</url-pattern> </filter-mapping>
把Spring的配置文件添加到src的目錄下:mysql
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> </beans>
在web.xml文件中註冊監聽器:web
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
到目前爲止,咱們已經搭建好SSH框架了,接下來就是要測試SSH是否完美整合了。咱們會通常會新建一個test包來測試,與src是平級的。spring
預期:若是能夠在action中可以正確調用service裏面的方法執行並返回到一個頁面中;那麼咱們認定struts和spring的整合是成功的。sql
private ClassPathXmlApplicationContext context; @Test public void load() { context = new ClassPathXmlApplicationContext("bean.xml"); System.out.println(context); }
package zhongfucheng.test.service; /** * Created by ozc on 2017/5/22. */ public interface TestService { void say(); }
package zhongfucheng.test.service.impl; import org.springframework.stereotype.Service; /** * Created by ozc on 2017/5/22. */ @Service public class TestServiceImpl implements zhongfucheng.test.service.TestService { @Override public void say() { System.out.println("hi "); } }
<context:component-scan base-package="zhongfucheng.test"/>
<import resource="classpath:zhongfucheng/test/config/test-spring.xml"/>
@Test public void testSpring() { TestService testService = (TestService) context.getBean("testServiceImpl"); System.out.println(testService); }
建立action目錄,建立TestActionexpress
package zhongfucheng.test.action; import com.opensymphony.xwork2.ActionSupport; /** * Created by ozc on 2017/5/22. */ public class TestAction extends ActionSupport { public String test2() { return SUCCESS; } }
在config下多添加一個Struts的配置文件,配置對應的信息。在Class中要麼咱們在配置Action的時候把對象交給Spring管理,要麼就直接寫上類的全名交給Struts2管理。這兩種方式都是能夠的!【這裏咱們使用的是把對象交給Struts2管理,Spring是能夠感知的,由於咱們導入了Struts2-Spring.jar包】apache
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="test" namespace="/" extends="struts-default"> <action name="test_*" class="zhongfucheng.test.action.TestAction" method="{1}"> <result name="success">/WEB-INF/jsp/test/test.jsp</result> </action> </package> </struts>
固然了,在Struts2的總配置文件中也要把test中的Struts配置文件引入markdown
在WEB-INF下建立專門管理JSP的目錄,其中建立用於測試的test.jspsession
public class TestAction extends ActionSupport { @Qualifier("testServiceImpl") @Autowired private TestService service; public String test2() { service.say(); return SUCCESS; } }
<!-- 導入外部的properties配置文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置c3p0數據源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="jdbcUrl" value="${jdbcUrl}"></property> <property name="driverClass" value="${driverClass}"></property> <property name="user" value="${user}"></property> <property name="password" value="${password}"></property> <!--初始化時獲取三個鏈接,取值應在minPoolSize與maxPoolSize之間。Default: 3 --> <property name="initialPoolSize" value="${initialPoolSize}"></property> <!--鏈接池中保留的最小鏈接數。Default: 3 --> <property name="minPoolSize" value="3"></property> <!--鏈接池中保留的最大鏈接數。Default: 15 --> <property name="maxPoolSize" value="${maxPoolSize}"></property> <!--當鏈接池中的鏈接耗盡的時候c3p0一次同時獲取的鏈接數。Default: 3 --> <property name="acquireIncrement" value="3"></property> <!--最大空閒時間,1800秒內未使用則鏈接被丟棄,若爲0則永不丟棄。Default: 0 --> <property name="maxIdleTime" value="1800"></property> </bean>
jdbcUrl=jdbc:mysql://localhost:3306/SSH03?useUnicode=true&characterEncoding=utf8 driverClass=com.mysql.jdbc.Driver user=root password=root initialPoolSize=10 maxPoolSize=30
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="javax.persistence.validation.mode">none</prop> </props> </property> <property name="mappingLocations"> <list> <value>classpath:zhongfucheng/test/entity/*.hbm.xml</value> </list> </property> </bean>
package zhongfucheng.test.entity; /** * Created by ozc on 2017/5/22. */ public class Person implements Serializable { private String id; private String username; public Person() { } public Person(String username) { this.username = username; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="zhongfucheng.test.entity.Person" table="person"> <id name="id" type="java.lang.String"> <column name="id" length="32" /> <generator class="uuid.hex" /> </id> <property name="username" type="java.lang.String"> <column name="username" length="20" not-null="true" /> </property> </class> </hibernate-mapping>
@Test public void testHibernate() { SessionFactory factory = (SessionFactory) context.getBean("sessionFactory"); Session session = factory.openSession(); session.beginTransaction(); session.save(new Person("人員1")); session.getTransaction().commit(); session.close(); }
建立TestDao接口,建立TestDaoImpl實例,繼承HibernateDaoSupport這個類【方便開發】,實現TestDao接口app
public class TestDaoImpl extends HibernateDaoSupport implements TestDao { @Override public void save(Person person) { getHibernateTemplate().save(person); } }
值得注意的是:繼承了HibernateDaoSupport這個類,這個類是須要SessionFactory的,經過註解的方式給不了【給屬性的話,屬性只與TestDaoImpl相關,而HibernateDaoSupport的setFactory()被定義了final】,所以只能經過XML的方式來配置【XML配置TestDaoImpl,TestDaoImpl是擁有setFactory方法的,不能改寫,可是能經過XML注入呀】
<bean id="testDaoImpl" class="zhongfucheng.test.dao.impl.TestDaoImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean>
@Service public class TestServiceImpl implements zhongfucheng.test.service.TestService { @Autowired private TestDao testDaoImpl; @Override public void save(Person person) { testDaoImpl.save(person); } }
@Test public void testMVC() { TestService service = (TestService) context.getBean("testServiceImpl"); service.save(new Person("人員2")); }
在Spring的總配置文件下添加如下配置:
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="find*" read-only="true" /> <tx:method name="get*" read-only="true" /> <tx:method name="load*" read-only="true" /> <tx:method name="list*" read-only="true" /> <tx:method name="search*" read-only="true" /> <tx:method name="*" rollback-for="Throwable" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="serviceOperation" expression="bean(*Service*)" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" /> </aop:config> <!-- 全部業務配置文件都要用到sessionFactory,那麼這個就是專門來建立sessionFactory的,其餘的業務配置文件指定parent就有了該屬性 --> <!-- 全部業務dao的parent --> <bean id="baseDao" abstract="true"> <property name="sessionFactory" ref="sessionFactory"></property> </bean>
@Service public class TestServiceImpl implements zhongfucheng.test.service.TestService { @Autowired private TestDao testDaoImpl; @Override public void save(Person person) { testDaoImpl.save(person); int i = 1 / 0; } }
@Test public void testTx() { TestService service = (TestService) context.getBean("testServiceImpl"); service.save(new Person("人員3")); }
咱們發現,每當使用Junit測試的時候都出現瞭如下的紅色信息,雖然對咱們的功能沒有任何影響:
它出現的緣由是沒有配置log4j,其實log4j對咱們頗有用。能夠根據日誌文件來找到對應的錯誤,咱們在開發中也應該使用它。
要配置log4j,要導入jar包:com.springsource.org.apache.log4j-1.2.15.jar【在導入SSH的jar包中已經存在了】
log4j.properties
log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p [%t] %c{1}:%L - %m%n #默認從warn開始 log4j.rootLogger=warn, stdout, R log4j.logger.zhongfucheng=debug log4j.appender.R=org.apache.log4j.DailyRollingFileAppender #R.File是把日誌信息輸出到哪裏 log4j.appender.R.File=D:/itcast/itcast.log log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d [%t] %5p %c - %m%n
輸出到硬盤的日誌文件:
package zhongfucheng.core.dao; import java.io.Serializable; import java.util.List; public interface BaseDao<T> { //新增 public void save(T entity); //更新 public void update(T entity); //根據id刪除 public void delete(Serializable id); //根據id查找 public T findObjectById(Serializable id); //查找列表 public List<T> findObjects(); }
package zhongfucheng.core.dao.impl; import org.hibernate.Query; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import zhongfucheng.core.dao.BaseDao; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.List; public abstract class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> { Class<T> clazz; public BaseDaoImpl(){ ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();//BaseDaoImpl<User> clazz = (Class<T>)pt.getActualTypeArguments()[0]; } @Override public void save(T entity) { getHibernateTemplate().save(entity); } @Override public void update(T entity) { getHibernateTemplate().update(entity); } @Override public void delete(Serializable id) { getHibernateTemplate().delete(findObjectById(id)); } @Override public T findObjectById(Serializable id) { return getHibernateTemplate().get(clazz, id); } @Override public List<T> findObjects() { Query query = getSession().createQuery("FROM " + clazz.getSimpleName()); return query.list(); } }