本博文主要是讲解如何 搭建一个比较规范的SSH开发环境,以及对它测试【在前面的搭建中,只是整合了SSH框架,能够使用SSH实现功能】,而这次是相对规范的。
<!-- 禁用动态方法访问 --> <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的目录下:
<?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文件中注册监听器:
<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>
我们会一般会新建一个test包来测试,与src是平级的。
预期: 如果可以在action中能够正确调用service里面的方法执行并返回到一个页面中;那么我们认定struts和spring的整合是成功的。
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目录,创建TestAction
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包】
<?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配置文件引入
在WEB-INF下创建专门管理JSP的目录,其中创建用于测试的test.jsp
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接口
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(); } }