1.工程介绍
工程是结合了Spring+struts2+hibernate,实现了一个简单的form表单提交的功能,可能需要对spring,struts2,hibernate有一个基础的了解才好理解。
2.工程结构图
首先来看一下整个工程的结构
3.java文件
User.java - 用于往数据库中存入数据
package com.ssh.bean; public class User { private int userId; private String username; private String password; private int gender; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } 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 int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } }
UserForm.java - 用于接收页面传来的表单数据
package com.ssh.forms; public class UserForm { private String username; private String password; private int gender; 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 int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } }
UserDao.java - 用于实现数据接口层
package com.ssh.dao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class UserDao{ @Autowired private SessionFactory sessionFactory; private Session getCurrentSession() { return sessionFactory.openSession(); } public void saveObject(Object obj) throws HibernateException { this.getCurrentSession().save(obj); } }
UserService.java - 用于实现业务层逻辑
package com.ssh.service; import org.hibernate.HibernateException; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ssh.bean.User; import com.ssh.dao.UserDao; import com.ssh.forms.UserForm; @Service public class UserService { @Autowired private UserDao dao; public void regUser(UserForm userForm) throws HibernateException { User user = new User(); BeanUtils.copyProperties(userForm, user); dao.saveObject(user); } }
RegisterAction.java - struts2的Action
package com.ssh.action; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; import com.ssh.forms.UserForm; import com.ssh.service.UserService; public class RegisterAction extends ActionSupport { private static final long serialVersionUID = 1L; private UserForm user; @Autowired private UserService userService; public UserForm getUser() { return user; } public void setUser(UserForm user) { this.user = user; } public String execute() { try { userService.regUser(user); return SUCCESS; } catch (Exception e) { e.printStackTrace(); return ERROR; } } }
4.配置信息
如第一张工程结构图可知,为了结构清晰,ssh的所有配置信息都放在resource路径下面。
struts.xml - struts2配置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="default" extends="struts-default"> <action name="register" class="com.ssh.action.RegisterAction"> <result name="input">/Register.jsp</result> <result name="success">/success.jsp</result> <result name="error">/fail.jsp</result> </action> </package> </struts>
hibernate.cfg.xml - hibernate的一些配置信息
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 配置 hibernate 的基本属性 --> <!-- 1. 数据源需配置到 IOC 容器中, 所以在此处不再需要配置数据源 --> <!-- 2. 关联的 .hbm.xml 也在 IOC 容器配置 SessionFactory 实例时再进行配置 --> <!-- 3. 配置 hibernate 的基本属性: 方言, SQL 显示及格式化, 生成数据表的策略以及二级缓存等. --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">create</property> <!-- 配置 hibernate 二级缓存相关的属性. --> </session-factory> </hibernate-configuration>
在本工程中将原来在hibernate中的数据源信息和关联的*.hbm.xml文件配置到了spring配置文件中由spring容器管理。
为了让工程结构调理清晰保留了hibernate.cfg.xml文件,并且把hibernate的基本属性配置写在了里面,也方便以后添加其他的配置信息。(hibernate的基本属性也可以配置到spring的配置文件当中,然后删除掉hibernate.cfg.xml文件,后面会具体讲述如何配置)
db.properties - 抽取了数据源的基本信息,方便以后修改
jdbc.user=root jdbc.password=123456 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql:///ssh1 jdbc.initPoolSize=5 jdbc.maxPoolSize=10
applicationContext.xml - spring配置文件
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置自动扫描的包 --> <context:component-scan base-package="com.ssh"></context:component-scan> <!-- 配置数据源 --> <!-- 导入资源文件 --> <context:property-placeholder location="classpath:db.properties" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- 配置 Hibernate 的 SessionFactory 实例: 通过 Spring 提供的 LocalSessionFactoryBean 进行配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 配置数据源属性 --> <property name="dataSource" ref="dataSource"></property> <!-- 配置 hibernate 配置文件的位置及名称 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 配置 hibernate 映射文件的位置及名称, 可以使用通配符 --> <property name="mappingLocations" value="classpath:com/ssh/bean/*.hbm.xml"></property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
上面提到可以删除hibernate.cfg.xml文件,可以将spring配置文件中的 id=sessionFactory 的bean 替换如下即可:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 配置数据源属性 --> <property name="dataSource" ref="dataSource"></property> <!-- 使用 hibernateProperties 属相来配置 Hibernate 原生的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- 配置 hibernate 映射文件的位置及名称, 可以使用通配符 --> <property name="mappingLocations" value="classpath:com/ssh/bean/*.hbm.xml"></property> </bean>
web.xml - 额外指定了 spring 和 struts2配置文件的路径
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!-- struts.xml路径配置,若不配置需放到类路径下 --> <init-param> <param-name>config</param-name> <param-value>../../resources/struts.xml</param-value> </init-param> <!-- spring配置文件路径,如不配置需放到web-inf下 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <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> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>Register.jsp</welcome-file> </welcome-file-list> </web-app>
pom.xml - 配置了一些ssh框架所必需的jar包,有maven自动下载到本地仓库
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com</groupId> <artifactId>ssh1</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssh1 Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <!-- 添加SSH依赖 --> <!-- Struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.24</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.24.1</version> </dependency> <!-- 添加Hibernate依赖 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.2.Final</version> </dependency> <!-- spring框架依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- 包含了大量注解@Autowired等。 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- 包含SessionFactory org.springframework.orm.hibernate4.LocalSessionFactoryBean --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- 包含ContextLoaderListener 监听器 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- ApplicationContextInitializer --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency> <!-- c3p0数据源 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- 添加Log4J依赖 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.6.4</version> </dependency> <!-- 添加javassist --> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.11.0.GA</version> </dependency> </dependencies> <build> <finalName>ssh1</finalName> </build> </project>
5.页面文件
Register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>User Register Page</title> </head> <body> <s:form action="register"> <s:textfield name="user.username" label="用户名"></s:textfield> <s:password name="user.password" label="密码"></s:password> <s:select list="#{'1':'男','0':'女'}" listKey="key" listValue="value" name="user.gender" label="性别" value="1"></s:select> <s:submit value="注册"></s:submit> </s:form> </body> </html>
success.js
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>User Register Page</title> </head> <body> <h1>SUCCESS</h1> </body> </html>
6.配置中遇到的一些问题和解决方法
1.hibernate配置了自动建表,但是程序运行之后不仅没有自动建表而且还总是提示无法找到表。
解决方法:hbm2ddl.auto 改成hibernate.hbm2ddl.auto 当然值也要改成create才可以自动建表。
.......
源代码在此:点击此处下载