一、Struts2+Spring2.5+Hibernate3搭建过程:
1. Eclipse->New->Danamic Web Project
2. 加入核心jar包:
Struts2核心包:
struts2-core-2.0.11.2.jar
commons-logging-1.0.4.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
xwork-2.0.5.jar
struts2-spring-plugin-2.0.11.2.jar
Spring核心包:
spring.jar
Hibernate核心包:
hibernate3.jar
antlr-2.7.6.jar
asm.jar
asm-attrs.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.6.1.jar
ehcache-1.2.jar
jta.jar
log4j-1.2.11.jar
其他包:ojdbc14.jar、dwr.jar等
3. 提供相关配置文件,修改web.xml
Web.xml配置:
<!-- struts2 config -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 加载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>
<!-- spring 提供的字符串过滤器 -->
<filter>
<filter-name>Spring character encoding filter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Spring character encoding filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/tld/c.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/fmt</taglib-uri>
<taglib-location>/WEB-INF/tld/fmt.tld</taglib-location>
</taglib>
</jsp-config>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
在src/java下添加struts.xml配置文件:
Struts配置文件:
<?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"/>
<!-- 配置编码格式支持 默认为utf8 -->
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="project-default" extends="struts-default" abstract="true">
<interceptors>
</interceptors>
<!-- 定义默认的拦截器栈 -->
<!-- 全局结果定义 -->
<global-results>
<result name=""></result>
</global-results>
<!-- 全局异常映射定义 -->
<global-exception-mappings>
</global-exception-mappings>
</package>
<!-- 添加包含子文件 -->
<include file="struts_demo.xml"/>
</struts>
在src下添加hibernate配置文件及其log4j.properties.(日志记录配置文件,在hibernate包中可以找到)
Hibernate配置文件:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.username">demo</property>
<property name="hibernate.connection.password">demo</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="com/isoftstone/ssh/demo/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
在webroot/WEB-INF下添加spring核心配置文件,提供对hibernate的支持,配置数据源及SessionFactory:
applicationContext-core.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-2.5.xsd">
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@localhost:1521:orcl</value>
</property>
<property name="username">
<value>demo</value>
</property>
<property name="password">
<value>demo</value>
</property>
</bean>
<!-- 配置hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource" />
</property>
<!-- 配置hibernate属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop> </props>
</property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
</beans>
文件目录结构:
图一、src目录结构
图二、webroot目录结构
测试:配置相关的数据库连接,部署启动项目,看能否正常启动。
二、demo示例程序开发过程:
1. 创建实体类及其hibernate映射文件,创建数据库表。
在com.isoftstone.ssh.demo.entity下创建实体类:User
public class User extends BaseEntity {
private long userId;
private String username;
private String password;
//getters和setters方法省略
}
//BaseEntity为实现Serializable接口的实体类
在entity包下,提供hibernate实体类映射文件如下:
User.hbm.xml
<hibernate-mapping>
<class table="t_user" name="com.isoftstone.ssh.demo.entity.User">
<id name="userId">
<generator class="native"/>
</id>
<property name="username" unique="true" not-null="true"/>
<property name="password" not-null="true"/>
</class>
</hibernate-mapping>
在hibernate.cfg.xml中添加资源配置:
<mapping resource=” com/isoftstone/ssh/demo/entity/User.hbm.xml” />
使用hibernate提供的类实现数据库表的创建:
在com.isoftstone.ssh.common.util中,执行ExportDB的main()方法,生成实体类对应的数据库表(注:在hibernate.cfg.xml中需要暂时提供数据库连接等属性,后期可以采用Ant和xDoclet的方式,自动生成实体类的配置文件及创建数据库表)
2.编写DAO层及其实现类:
编写UserDAO接口,
package com.isoftstone.ssh.demo.integration.dao;
import java.util.List;
import com.isoftstone.ssh.common.core.BaseDAO;
import com.isoftstone.ssh.demo.entity.User;
public interface UserDAO extends BaseDAO {
public void createUser(User user);
public void deleteUser(long userId);
public List<User> searchAllUser();
public User loginUser(String username, String password);
}
编写UserDAO类的实现类UserHiberanteDAO,继承HibernateDaoSupport实现UserDAO
package com.isoftstone.ssh.demo.integration.dao.impl;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.isoftstone.ssh.common.core.ProjectException;
import com.isoftstone.ssh.demo.entity.User;
import com.isoftstone.ssh.demo.integration.dao.UserDAO;
public class UserHibernateDAO extends HibernateDaoSupport implements UserDAO {
@Override
public void createUser(User user) {}
@Override
public void deleteUser(long userId) {}
@Override
public List<User> searchAllUser() {
return getSession().createQuery("from User").list();
}
@Override
public User loginUser(String username, String password) {
User user = findUserByUsername(username);
if(user == null)
throw new ProjectException("用户名不存在:" + username);
if(!user.getPassword().equals(password))
throw new ProjectException("密码不正确!");
return user;
}
private User findUserByUsername(String username){
return (User)
this.getSession().createQuery("select u from
com.isoftstone.ssh.demo.entity.User u where u.username=?")
.setParameter(0, username)
.uniqueResult();
}
}
在applicationContext-demo.xml中配置DAO,纳入spring的IOC容器管理,
<!-- config dao -->
<bean id="userDAO" class="com.isoftstone.ssh.demo.integration.dao.impl.UserHibernateDAO" scope="prototype">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
(注意:HibernateDaoSupport由Spring框架提供,对hibernate提供了支持,其使用和hibernate的session基本一致;配置DAO类时,注意设置scope属性为“prototype”类型)
3.编写Service层及其实现类
编写UserService接口:
package com.isoftstone.ssh.demo.biz.service;
import java.util.List;
import com.isoftstone.ssh.demo.entity.User;
public interface UserService {
public void createUser(User user);
public void deleteUser(long userId);
public List<User> searchAllUser();
public User loginUser(String username, String password);
}
编写service实现类:UserPojoService
package com.isoftstone.ssh.demo.biz.service.impl;
import java.util.List;
import com.isoftstone.ssh.common.core.BaseService;
import com.isoftstone.ssh.demo.biz.service.UserService;
import com.isoftstone.ssh.demo.entity.User;
import com.isoftstone.ssh.demo.integration.dao.UserDAO;
public class UserPojoService extends BaseService implements UserService {
@Override
public void createUser(User user) {}
@Override
public void deleteUser(long userId) {}
@Override
public List<User> searchAllUser() {
UserDAO userDAO = (UserDAO) context.getBean("userDAO");
return userDAO.searchAllUser();
}
@Override
public User loginUser(String username, String password) {
UserDAO userDAO = (UserDAO) context.getBean("userDAO");
return userDAO.loginUser(username, password);
}
}
在applicationContext-demo.xml中配置Service,纳入spring的IOC容器管理,
<!-- config service -->
<bean id="userService" class="com.isoftstone.ssh.demo.biz.service.impl.UserPojoService">
</bean>
(注意:UserPojoService实现类继承了BaseService类,BaseService实现类Service接口及其 BeanNameAware, DisposableBean,InitializingBean, BeanFactoryAware等spring提供的工具类,在spring启动的时候会自动注入相关的属性,这样在其实现类中可是直接通过配置的beanName使用spring容器中的相关bean等,如context.getBean(“beanName”);)
4. 编写Struts2的Action控制器
在com.isoftstone.ssh.demo.web.action包中创建LoginAction
package com.isoftstone.ssh.demo.web.action;
import com.isoftstone.ssh.common.core.AbstractAction;
import com.isoftstone.ssh.demo.biz.service.UserService;
import com.isoftstone.ssh.demo.entity.User;
public class LoginAction extends AbstractAction {
private UserService userService;
private User user = new User();
@Override
public String execute() throws Exception {
user = userService.loginUser(user.getUsername(), user.getPassword());
getSession().put("user", user);
logger.debug("logger信息 : " + user.getUsername() + " : " + user.getPassword() + ": " + user.getUserId());
return SUCCESS;
}
@Override
public User getViewModel() {
return user;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
在spring配置文件中添加action类的配置:
<bean id="LoginAction"
class="com.isoftstone.ssh.demo.web.action.LoginAction"
scope="prototype">
<property name="userService" ref="userService"/>
</bean>
配置Struts配置文件,在struts-demo.xml添加配置文件:
<struts>
<package name="user" extends="project-default">
<action name="login" class="LoginAction">
<result>/welcome.jsp</result>
<result name="input">/login.jsp</result>
</action>
<!-- Add actions here -->
</package>
</struts>
在struts.xml中添加子文件:
<include file="struts_demo.xml"/>
注意:(1. LoginAction 继承于抽象类AbstractAction,AbstractAction继承了Struts2的ActionSupport类,及其实现了ModelDriven, SessionAware, ParameterAware等接口,提供getRequest(),getSession()以及日志记录logger等,在common/util包中可以查看其代码;2. struts2对spring提供了支持,通过struts2-spring-plugin-2.0.11.2.jar包,Action类是交给spring的ioc容器管理,且scope属性为prototype,spring默认为singleton,Struts2不同于Struts1的单实例,不需要考虑线程安全问题;3. Struts配置文件中,action的class属性为spring配置的Action Bean的名字)
5. 页面显示,配置Struts2的验证器
在login.jsp中使用sturts的标签做显示,如:
//struts2标签
<s:form method="post" action="login.action">
<s:textfield name="username" key="username" label="用户名"/>
<s:textfield name="password" key="password" label="密码"/>
<s:submit value="登录系统"/>
</s:form>
实现struts2的验证器,在LoginAction的包下添加配置文件(可从struts2的jar包中找到资源文件)
package.properties:(用于定义国际化消息文本)
HelloWorld.message= Struts is up and running ...
requiredstring = ${getText(fieldName)} is required.
password = Password
username = Username
LoginAction-validation.xml:
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<message key="requiredstring"/>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message key="requiredstring"/>
</field-validator>
</field>
</validators>
注意:(sturts2的验证功能是通过interception拦截器实现的,在struts-default.xml文件中,默认是开启验证功能)
6. 其他:在common/core包中提供了自定义异常等类,在sturts.xml中配置了全局异常处理等
<!-- 全局结果定义 -->
<global-results>
<result name="exception">
/common/error.jsp
</result>
<result name="login">/login.jsp</result>
</global-results>
<!-- 全局异常映射定义 -->
<global-exception-mappings>
<exception-mapping exception="com.isoftstone.ssh.common.core.ProjectException" result="exception" />
</global-exception-mappings>
关键字: dwr2+struts2+spring2.5+hibernate3、注册登录
用户注册和登录是每个系统的必须存在的一部分,基于Dwr+Struts2+Spring+Hibernate写了一个用户登录注册系统。
其中用Dwr去进行用户注册的用户是否存在的验证。
全部业务控制交由Spring去进行处理。事务处理也交由Spring去管理。
压缩文件中不包含Jar文件(由于全部的Jar将近12M,不能全部上传),所用到的Jar目录为,工程中再也不会出现由于MyEclipse自动整合而出现的大量Jar文件 :
Java代码
//如果不用,启动时不会出错,但使用Dwr时,会抛出异常:java.lang.NoClassDefFoundError: antlr/ANTLRException
antlr-2.7.2.jar
//如果不用此包,在启动时会抛出: nested exception is java.lang.NoClassDefFoundError: org/objectweb/asm/Type
asm.jar
//如果不用此包,在启动时抛出:nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
aspectjweaver.jar
//如果不用此包,在启动时抛出:nested exception is java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter
cglib-2.1.3.jar
//如果不用此包,在启动时抛出:nested exception is java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap
commons-collections-3.1.jar
//这个似乎可以不用的
commons-fileupload-1.2.1.jar
//这个就不用说啦,几乎所有框架都要使用的
commons-logging-1.0.4.jar
//如果不用此包会抛出:java.lang.NoClassDefFoundError: org/dom4j/DocumentException
dom4j-1.6.1.jar
//dwr必须
dwr.jar
//不用此包,在启动时招聘:java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
jta.jar
//Mysql JDBC驱动
mysql-connector.jar
//Hibernate必须使用,注意此包是包含全部的。
hibernate3.jar
//Spring整体包
spring.jar
//struts2必须
freemarker-2.3.8.jar
//struts2必须
ognl-2.6.11.jar
//struts2核心包
struts2-core-2.0.11.2.jar
//struts2整合Spring插件
struts2-spring-plugin-2.0.11.2.jar
//struts2必须
xwork-2.0.5.jar
//如果不用,启动时不会出错,但使用Dwr时,会抛出异常:java.lang.NoClassDefFoundError: antlr/ANTLRException antlr-2.7.2.jar //如果不用此包,在启动时会抛出: nested exception is java.lang.NoClassDefFoundError: org/objectweb/asm/Type asm.jar //如果不用此包,在启动时抛出:nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException aspectjweaver.jar //如果不用此包,在启动时抛出:nested exception is java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter cglib-2.1.3.jar //如果不用此包,在启动时抛出:nested exception is java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap commons-collections-3.1.jar //这个似乎可以不用的 commons-fileupload-1.2.1.jar //这个就不用说啦,几乎所有框架都要使用的 commons-logging-1.0.4.jar //如果不用此包会抛出:java.lang.NoClassDefFoundError: org/dom4j/DocumentException dom4j-1.6.1.jar //dwr必须 dwr.jar //不用此包,在启动时招聘:java.lang.NoClassDefFoundError: javax/transaction/TransactionManager jta.jar //Mysql JDBC驱动 mysql-connector.jar //Hibernate必须使用,注意此包是包含全部的。 hibernate3.jar //Spring整体包 spring.jar //struts2必须 freemarker-2.3.8.jar //struts2必须 ognl-2.6.11.jar //struts2核心包 struts2-core-2.0.11.2.jar //struts2整合Spring插件 struts2-spring-plugin-2.0.11.2.jar //struts2必须 xwork-2.0.5.jar
数据库设计(使用MySql数据库):
Java代码 create table user
(
id varchar(32) not null,
userName varchar(20),
password varchar(20),
primary key(id)
);
create table user_infor
(
id varchar(32) not null,
user_id varchar(32),
name varchar(20),
email varchar(30),
sex char,
age int,
address varchar(300),
primary key(id)
);
ALTER TABLE user_infor
ADD FOREIGN KEY(user_id)
REFERENCES user(id)
ON DELETE CASCADE;