首先下载相应的文件和包:mysql tomcat spring3 struts2 hibernate3
1.先搭建一个struts2的web项目
打开Eclipse,File>>New>>Dynamic Web Project。在WebContent/WEB-INF文件夹下新建一个web.xml文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 配置struts2为项目的controller -->
<filter>
<filter-name>SSH</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SSH</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
这个web.xml中的<filter>元素定义了一个名为SSH的拦截器以及拦截器的实现类。<filter-mapping>定义了拦截器要拦截的用户请求,这里的话所有的请求都会被拦截下来,然后交给我们写的action来处理,这样的话,通过在web.xml中定义一个filter,完成了struts2的引入。
当然除此之外,我们还要导入struts2的jar包,下载解压后,将要用到的包复制到WebContent/WEB-INF/lib文件夹下。必须的jar包名字大致如下:
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
freemarker-2.3.18.jar
ognl-3.0.4.jar
struts2-core-2.3.1.2.jar
xwork-core-2.3.1.2.jar
javassist-3.11.0.GA.jar
struts.xml:
<?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>
<include file="struts-default.xml" />
<package name="register" extends="struts-default">
<action name="register" class="com.edu.nju.firstSSH.Action.RegisterAction">
<result name="input">/WEB-INF/view/register.jsp</result>
<result name="success">/WEB-INF/view/success.jsp</result>
<result name="error">/WEB-INF/view/fail.jsp</result>
</action>
</package>
</struts>
下面建立Action类,代码如下:
package com.edu.nju.firstSSH.Action;
import com.edu.nju.firstSSH.FormBean.UserForm;
import com.edu.nju.firstSSH.Service.UserService;
import com.edu.nju.firstSSH.Service.UserServiceImp;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private UserForm userform;
private UserService userService;
public String execute(){
userService = new UserServiceImp();
userService.register(userform);
return "success";
}
public UserForm getUserform() {
return userform;
}
public void setUserform(UserForm userform) {
this.userform = userform;
}
}
最后建立Userform类,封装表达数据:
package com.edu.nju.firstSSH.FormBean;
public class UserForm {
private String username;
private String password;
private int gender;
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;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
注册表单页面:
<%@ 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" method="post">
<s:textfield name="userform.username" label="用户名"></s:textfield>
<s:password name="userform.password" label="密码"></s:password>
<s:select list="#{'1':'男','0':'女'}" listKey="key" listValue="value"
name="userform.gender" label="性别" value="1"></s:select>
<s:submit value="注册"></s:submit>
</s:form>
</body>
</html>
启动项目(run on server),浏览器访问如下:
说明struts2配置完成。
项目目录如下:
2.加入Hibernate
首先把要用到的hibernate包导入到lib下。
编写PO,首先写数据库实体类,User类,代码如下:
package com.edu.nju.firstSSH.Bean;
public class User {
private String name;
private String password;
private int gender;
private int userid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
}
User类与数据库中的表结构一一对应。
然后写PO的hibernate配置文件,每一个数据库表都要有一个配置文件和对应的类。配置文件命名为:User.hbm.xml,代码为:
<?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 package="com.edu.nju.firstSSH.Bean">
<class name="User" table="test">
<id name="userid" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name" type="java.lang.String"
not-null="true" length="16"></property>
<property name="password" column="password" type="java.lang.String"
not-null="true" length="16" />
<property name="gender" column="gender" type="java.lang.Integer" length="1" />
</class>
</hibernate-mapping>
最后配置hibernate,在src中新建hibernate.cfg.xml,代码为:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property> -->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<!-- <property name="current_session_context_class">thread</property> -->
<!-- Disable the second-level cache -->
<!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> -->
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">update</property> -->
<mapping resource="com/edu/nju/firstSSH/Bean/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
这里还要引入数据库的驱动程序,放在lib下即可。这个配置文件指定了数据源的信息和POJO配置文件列表。
下面建立UserDao借口以及实现程序:
UserDao:
package com.edu.nju.firstSSH.UserDao;
import org.hibernate.Session;
public interface UserDao {
public void save(Object o);
public void setSession(Session session);
}
UserDaoImp:
package com.edu.nju.firstSSH.UserDao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
public class UserDaoImp implements UserDao {
private Session session;
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
@Override
public void save(Object obj) throws HibernateException {
session.save(obj);
}
}
这里的session方法是为了使用sessionFactory的。
最后是service层:
UserService:
package com.edu.nju.firstSSH.Service;
import com.edu.nju.firstSSH.FormBean.UserForm;
public interface UserService {
public void register(UserForm userForm);
}
UserServiceImp:
package com.edu.nju.firstSSH.Service;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.edu.nju.firstSSH.Bean.User;
import com.edu.nju.firstSSH.FormBean.UserForm;
import com.edu.nju.firstSSH.UserDao.UserDao;
import com.edu.nju.firstSSH.UserDao.UserDaoImp;
public class UserServiceImp implements UserService{
private Session session;
private UserDao userDao;
public UserServiceImp(){
userDao = new UserDaoImp();
}
@Override
public void register(UserForm userForm) {
session = HibernateSessionFactory.currentSession();
userDao.setSession(session);
// 获取事务
Transaction ts = session.beginTransaction();
// 构造User对象
User user = new User();
System.out.println("userForm: "+userForm);
user.setName(userForm.getUsername());
user.setPassword(userForm.getPassword());
user.setGender(userForm.getGender());
// 保存User对象
userDao.save(user);
// 提交事务
ts.commit();
// 关闭Session
HibernateSessionFactory.closeSession();
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
}
HibernateSessionFactory类:
package com.edu.nju.firstSSH.Service;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static final Configuration cfg = new Configuration() .configure();
private static SessionFactory sessionFactory;
public static Session currentSession() throws HibernateException {
Session session = threadLocal.get();
if (session == null || session.isOpen() == false) {
if (sessionFactory == null) {
try {
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession() throws HibernateException {
Session session = threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
}
这是hibernate3获取hibernateFactory的方法。
项目目录为:
至此,项目中加入了hibernate3。
3.引入spring3
首先写spring的配置文件,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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/test</value>
</property>
<property name="user">
<value>root</value>
</property>
<property name="password">
<value></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.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource" />
</property>
<property name="mappingResources">
<list>
<value>com/edu/nju/firstSSH/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>
<!-- 注册Dao -->
<bean id="userDao" class="com.edu.nju.firstSSH.UserDao.UserDaoImp">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- 注册业务逻辑类 -->
<bean id="userService" class="com.edu.nju.firstSSH.Service.UserServiceImp">
<property name="userDao">
<ref bean="userDao" />
</property>
</bean>
<!-- 注册的Action -->
<bean id="reg" class="com.edu.nju.firstSSH.Action.RegisterAction">
<property name="userService">
<ref bean="userService" />
</property>
</bean>
<!-- more bean definitions go here -->
</beans>
这个文件其实声明了所有要用的对象实例,spring通过这个文件来管理这些实例,每一个实例就是一个<bean>,这样的话java文件中的private属性就不需要初始化了,只需要声明,然后提供getter setter方法就可以,spring会为我们注入这些实例,把他们赋值。
下面修改struts.xml文件为:
<?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>
<include file="struts-default.xml" />
<package name="register" extends="struts-default">
<action name="register" class="reg">
<result name="input">/WEB-INF/view/register.jsp</result>
<result name="success">/WEB-INF/view/success.jsp</result>
<result name="error">/WEB-INF/view/fail.jsp</result>
</action>
</package>
</struts>
这里主要改了<action>标签里面的class,原先直接写class=类名,但是这里的话action实例要被spring创建,也就是说交给spring管理,所以要用到applicationContext.xml里面配置好的action才行。这一点很重要,因为如果不用spring的action实例,那么action就是通过构造方法创建的,这样的话,action里面的属性就是空,因为没写初始化(要用spring啊),所以这里必须改为使用spring创建的action实例,这样action里面的属性才会被赋值,否则报nullpointer,我就是遇到这个问题了,开始还以为spring没有注入,但是我在run on server时,它提示了很多关于注入的错误(比如setter没写),所以我觉得spring是注入了,最后才发现是这里的问题。
但是把这里改了以后,又报了一个新错Action class not found - action - file,大致就是说,reg这个东西并不是类,事实上它也确实不是一个类啊,它是spring管理的一个实例,也就是说struts2不认识spring创建的这个实例,查了半天,才发先是缺少一个包所致,这个包是struts2-spring-plugin-2.0.11.2.jar,它就是负责struts2与spring来整合的,说白了就是让spring来管理struts2的action实例,让struts2识别spring的action实例。到此,spring方面的解决了。
最后还得把spring配置加入到项目中,要修改web.xml为:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 配置struts2为项目的controller -->
<filter>
<filter-name>SSH</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SSH</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
添加一个listerner即可。
当然其他的类也需要修改,大致的内容就是把原来写new实例化的地方去掉,然后为这个private属性添加getter 和setter方法。
删掉之前的HibernateSessionFactory 类,我们用spring来管理sessionFactory,需要调用session的地方就用下面的方式:
Session session = sessionFactory.openSession();
session.save(obj);
这是不使用事务的方式,如果要使用事务的话,要先从session得到事务,再save,再提交事务。
总之hibernate的数据操作流程就是先得到factory,这个又spring提供,然后由factory得到session,session才是操作数据的对象。
还要删掉hibernate.cfg.xml。
下面贴出其他的类的最终实现:
UserDao:
package com.edu.nju.firstSSH.UserDao;
public interface UserDao {
public void save(Object o);
}
UserDaoImp:
package com.edu.nju.firstSSH.UserDao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class UserDaoImp implements UserDao {
private SessionFactory sessionFactory;
@Override
public void save(Object obj) throws HibernateException {
Session session = sessionFactory.openSession();
//开始事务;
Transaction tr = session.beginTransaction();
//存储 ;
session.save(obj);
//提交事务 ;
tr.commit();
session.close();
sessionFactory.close();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
UserService:
package com.edu.nju.firstSSH.Service;
import com.edu.nju.firstSSH.FormBean.UserForm;
public interface UserService {
public void register(UserForm userForm);
}
UserServiceImp:
package com.edu.nju.firstSSH.Service;
import com.edu.nju.firstSSH.Bean.User;
import com.edu.nju.firstSSH.FormBean.UserForm;
import com.edu.nju.firstSSH.UserDao.UserDao;
public class UserServiceImp implements UserService{
private UserDao userDao;
@Override
public void register(UserForm userForm) {
//userDao.setSession(session);
// 构造User对象
User user = new User();
user.setName(userForm.getUsername());
user.setPassword(userForm.getPassword());
user.setGender(userForm.getGender());
// 保存User对象
userDao.save(user);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
UserForm:
package com.edu.nju.firstSSH.FormBean;
public class UserForm {
private String username;
private String password;
private int gender;
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;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
User:
package com.edu.nju.firstSSH.Bean;
public class User {
private String name;
private String password;
private int gender;
private int userid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
}
User.hbm.xml不变
RegisterAction:
package com.edu.nju.firstSSH.Action;
import com.edu.nju.firstSSH.FormBean.UserForm;
import com.edu.nju.firstSSH.Service.UserService;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private UserForm userform;
private UserService userService;
public String execute(){
//userService = new UserServiceImp();
userService.register(userform);
return "success";
}
public UserForm getUserform() {
return userform;
}
public void setUserform(UserForm userform) {
this.userform = userform;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
项目目录结构:
访问:
搭建成功!
最后附上项目源码:
http://pan.baidu.com/s/1pKrBv43