最新eclipse整合Struts2.3.29+Hibernate5.2.1+Spring4.3.1(三)Struts+Hibernate+spring篇
繼續,我又新建一個專案sshTest,把shDemo的程式碼都移進去(shDemo拿去幹別的事了)
1.引入spring所需jar包
這裡不僅需要spring的jar包
還需要hibernate中兩個資料來源包
另外還有一個aspectjweaver.jar包,這個包在AOP配置的時候需要,現在spring的包裡面不提供了,要自己到網上下載。
2.修改web.xml檔案
在web.xml檔案中新增spring的監聽器和配置檔案位置以及hibernate的session過濾器
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>sshTest</display-name> <!-- spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- struts2 --> <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> <!-- hibernate --> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>*.do,*.action</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file> </welcome-file-list> </web-app>
3.在WEB-INF目錄下建立spring的配置檔案applicationContext.xml
applicationContext.xml
要重點注意以下幾點:<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 定義資料來源的資訊 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>com.mysql.jdbc.Driver</value> </property> <property name="jdbcUrl"> <value>jdbc:mysql://localhost:3306/tzy?useUnicode=true&characterEncoding=utf8&useSSL=true</value> </property> <property name="user"> <value>tzy</value> </property> <property name="password"> <value>11111111</value> </property> <property name="maxPoolSize"> <value>80</value> </property> <property name="minPoolSize"> <value>1</value> </property> <property name="initialPoolSize"> <value>1</value> </property> <property name="maxIdleTime"> <value>20</value> </property> </bean> <!--定義Hibernate的SessionFactory --> <!-- SessionFactory使用的資料來源為上面的資料來源 --> <!-- 指定了Hibernate的對映檔案和配置資訊 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource" /> </property> <property name="mappingResources"> <list> <value>com/tzy/bean/User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="show_sql">true</prop> <prop key="hibernate.jdbc.batch_size">20</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" propagation="REQUIRED" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- aop代理設定,預設是注入介面要加上proxy-target-class="true" 通過AOP配置提供事務增強,讓dao包下所有Bean的所有方法擁有事務--> <aop:config proxy-target-class="true"> <aop:pointcut id="daoPointcut" expression="execution(* com.tzy.dao.*.*(..))"/> <aop:advisor advice-ref="transactionAdvice" pointcut-ref="daoPointcut" /> </aop:config> <bean id="user" class="com.tzy.bean.User"></bean> <!--使用者註冊資料訪問類 --> <bean id="loginDao" class="com.tzy.daoImpl.LoginDaoImpl"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> <property name="user"> <ref bean="user" /> </property> </bean> <!--使用者註冊業務邏輯類 --> <bean id="loginService" class="com.tzy.serviceImpl.LoginServiceImpl"> <property name="loginDao"> <ref bean="loginDao" /> </property> </bean> <!-- 使用者註冊的Action --> <bean id="loginAction" class="com.tzy.action.LoginAction"> <property name="loginService"> <ref bean="loginService" /> </property> </bean> <!-- more bean definitions go here --> </beans>
1.約束引入
2.依賴注入
3.面向切面配置
3.刪除Hibernate的配置檔案
它的工作已經交給spring去做了,所以Hibernate.cfg.xml已經不需要了,卸磨殺驢。
4.修改相應的類
由於applicationContext.xml註冊的物件必須要依賴注入(DI),以後物件的生成都由spring接管,所以以後在程式碼中就不應該出現new物件的情況,以下物件都要作出修改,要給依賴的物件無參的新增setter方法,有參的修改建構函式:
com.tzy.daoImpl.LoginDaoImpl.java
注:package com.tzy.daoImpl; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import com.tzy.bean.User; import com.tzy.dao.LoginDao; public class LoginDaoImpl extends HibernateDaoSupport implements LoginDao { private User user; public void setUser(User user) { this.user = user; } @SuppressWarnings("unchecked") @Override public User getUser(String username) { @SuppressWarnings("resource") ApplicationContext context = new FileSystemXmlApplicationContext("E:/Data/workspace/sshTest/WebContent/WEB-INF/applicationContext.xml"); user=(User) context.getBean("user"); String hql = "from User"; List<User> list= (List<User>) this.getHibernateTemplate().find(hql); for(User user2 : list){ if(username.equals(user2.getUsername())){ user.setId(user2.getId()); user.setUsername(user2.getUsername()); user.setPassword(user2.getPassword()); } } return user; } }
1.ApplicationContext的生成有三種方法:FileSystemXmlApplicationContext、ClasspathXmlApplicationContext、WebXmlApplicationContext,都行,建議使用ClasspathXmlApplicationContext,我是為了省事;
2.getHibernateTemplate()這裡還是用的笨方法,不知道怎麼回事,這次用條件查詢還是會報錯,增刪改的方法都能操作成功,有空應該好好研究一下新版本API的改動了。
com.tzy.serviceImpl.LoginServiceImpl.java
package com.tzy.serviceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.tzy.bean.User;
import com.tzy.daoImpl.LoginDaoImpl;
import com.tzy.service.LoginService;
public class LoginServiceImpl implements LoginService {
LoginDaoImpl loginDao;
User user;
public void setLoginDao(LoginDaoImpl loginDao) {
this.loginDao = loginDao;
}
@Override
public String checkUser(String username, String password) {
@SuppressWarnings("resource")
ApplicationContext context = new FileSystemXmlApplicationContext("E:/Data/workspace/sshTest/WebContent/WEB-INF/applicationContext.xml");
loginDao = (LoginDaoImpl) context.getBean("loginDao");
user = loginDao.getUser(username);
if(user.getUsername()!=null){
if(password.equals(user.getPassword())){
return "success";
}else{
return "error";
}
}else{
return "register";
}
}
}
com.tzy.action.LoginAction.java
package com.tzy.action;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tzy.serviceImpl.LoginServiceImpl;
public class LoginAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
LoginServiceImpl loginService;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setLoginService(LoginServiceImpl loginService) {
this.loginService = loginService;
}
@Override
public String execute() throws Exception {
@SuppressWarnings("resource")
ApplicationContext context = new FileSystemXmlApplicationContext("E:/Data/workspace/sshTest/WebContent/WEB-INF/applicationContext.xml");
loginService = (LoginServiceImpl) context.getBean("loginService");
return loginService.checkUser(username, password);
}
}
最終的檔案結構:
執行專案,操作資料庫均能成功。
最後,總結一句,如果遇到框架使用方面的問題,最好的解決辦法是去讀官方文件,官方給的東西肯定不會錯的,尤其是在使用老方法報錯的時候,先排除其他因素,然後按照官方給的例子先做出來,整個都調通了之後,回頭再優化並研究新改動的API,這一步我先偷懶了,回頭要是會用到再補上。