继续,我又新建一个项目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,这一步我先偷懒了,回头要是会用到再补上。