https://wenku.baidu.com/view/d0dcfc017f1922791788e8a5.html
一, 通过IDE创建项目, 并创建相应的包结构
image.png image.png image.png image.png查看web.xml中的StrutsPrepareAndExecuteFilter包名是否正确.不正确的话去掉.ng包.
打开Project Structure and Fix the Problems
image.png image.png
二 整合Hibernate到Spring中
image.png image.png右键数据库, 创建表
image.png image.png image.png image.png
如果遇到如下问题:
image.png
解决方法:
image.png image.png
手动创建一个sessionFactory
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
</bean>
</beans>
此时选项中便有了可选项
image.png
自动生成如下内容
image.png
导入需要的jdbc驱动包后修改配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>com.minicuper.ssh.entity.UserEntity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/ssh</prop>
<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
<prop key="connection.username">root</prop>
<prop key="connection.password">1234</prop>
<prop key="current_session_context_class">thread</prop>
<prop key="format_sql">true</prop>
<prop key="show_sql">true</prop>
<prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
</beans>
生成的实体类中有一些错误
image.png
解决方法:为sessionFactory指定对应的DataSources即可
image.png image.png
三 整合Struts到Spring中.
配置ContextLoaderListener, 使WebApp启动时便初始化Spring配置文件
ContextLoaderListener类在spring-web.jar包中.需要手动引入jar包.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Spring整合-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
</web-app>
创建的类,及修改的类 :
image.png
UserAction.java
package com.minicuper.ssh2.action;
import com.minicuper.ssh2.entity.User;
import com.minicuper.ssh2.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class UserAction extends ActionSupport implements ModelDriven<User> {
public String result = "";
private User user = new User();
@Override
public User getModel() {
return user;
}
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public String regist(){
System.out.println("UserAction regist()");
if(userService.regist(user)){
result = "注册成功";
return SUCCESS;
}else {
result = "注册失败";
return ERROR;
}
}
}
User.java
package com.minicuper.ssh2.entity;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Objects;
@Entity
public class User {
private int uid;
private String name;
private String pwd;
@Id
@Column(name = "uid")
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "pwd")
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return uid == user.uid &&
Objects.equals(name, user.name) &&
Objects.equals(pwd, user.pwd);
}
@Override
public int hashCode() {
return Objects.hash(uid, name, pwd);
}
}
UserService.java
package com.minicuper.ssh2.service;
import com.minicuper.ssh2.dao.UserDao;
import com.minicuper.ssh2.entity.User;
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public boolean regist(User user){
System.out.println("UserService regist()");
return userDao.regist(user);
}
}
UserDao.java
package com.minicuper.ssh2.dao;
import com.minicuper.ssh2.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.transaction.annotation.Transactional;
public class UserDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public boolean regist(User user){
System.out.println("UserDao regist()");
Session currentSession = sessionFactory.openSession();
Transaction transaction = currentSession.beginTransaction();
try {
currentSession.save(user);
transaction.commit();
return true;
}catch (Exception e){
e.printStackTrace();
transaction.rollback();
}finally {
currentSession.close();
sessionFactory.close();
}
return false;
}
}
spring-config.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"
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">
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>com.minicuper.ssh2.entity.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/ssh?serverTimezone=UTC</prop>
<prop key="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</prop>
<prop key="hibernate.connection.password">1234</prop>
<prop key="hibernate.connection.username">root</prop>
<prop key="hbm2ddl.auto">create</prop>
<prop key="show_sql">true</prop>
<prop key="format_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<!--<prop key="current_session_context_class">thread</prop>-->
</props>
</property>
</bean>
<bean class="com.minicuper.ssh2.action.UserAction" id="userAction" scope="prototype">
<property name="userService" ref="userService"/>
</bean>
<bean class="com.minicuper.ssh2.service.UserService" id="userService">
<property name="userDao" ref="userDao"></property>
</bean>
<bean class="com.minicuper.ssh2.dao.UserDao" id="userDao">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="*_*" class="{1}Action" method="{2}">
<result name="success">result.jsp</result>
<result name="error">result.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
</web-app>
index.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<s:form namespace="/" theme="simple" method="POST" action="user_regist">
姓名:<input name="name" type="text"><br>
密码:<input name="pwd" type="text"><br>
<input type="submit" value="提交 ">
</s:form>
</body>
</html>
result.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
Result:<s:property value="result"/>
</body>
</html>
部署到Tomcat服务器:
image.png image.png image.png image.png image.png
常见问题:
- sessionFactory.getCurrentSession()
异常: org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
配置不起作用:<prop key="current_session_context_class">thread</prop>
解决方法: 配置HibernateTransactionManager
在Spring配置文件中添加:
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven/>
后在Service类上添加注解:@Transactional
- 配置事务时
出现异常:org.hibernate.service.UnknownUnwrapTypeException: Cannot unwrap to requested type [javax.sql.DataSource]
解决方法:
1.导入c3p0相关的包.
2.修改spring.config.xml
3.Dao类中原来的事务操作删掉即可
添加
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="user" value="root"/>
<property name="password" value="1234"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh?serverTimezone=UTC"/>
</bean>
修改
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.minicuper.practice.entity.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="show_sql">true</prop>
<prop key="format_sql">true</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
添加
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
添加
<tx:annotation-driven/>
- 配置c3p0时: 出现 ClassNotFoundException: com.mchange.v2.ser.Indirector
解决方法:添加 mchange-commons-java.jar包
网友评论