1 开发环境
MyEclipse 10
JDK 1.6
Java EE 5.0
Tomcat 7.0.25
Struts 2.3.4
Spring 3.1.1
Hibernate 3.6.10
2 为ssh做好准备
2.1下载包
Struts 2.3.4包下载:
http://struts.apache.org/download.cgi#struts234
Hibernate 3.6.10包下载:
http://sourceforge.net/projects/hibernate/files/hibernate3/
Spring下载:
http://www.springsource.org/download/community
2.2搭建开发环境
打开MyEclipse,新建一个web project
注意:J2ee版本设为java ee 5.0
点击Finish完成。
配置tomcat
好了,工程已经建好了,下面就开始配置struts吧。配置之前先把struts的包下载下来哦,下载地址上面已经给出了。
3 配置Struts2.0
3.1 基础配置
1)引入Struts必需的七个jar包。下载struts-2.3.4-all.zip解压后,struts-2.3.4\lib目录下是struts所有的相关jar包。这么多jar包并不是struts必须得,使用struts只需要把下面七个引入即可,以后用到什么jar包,再引入。
commons-logging-1.1.1.jar
commons-fileupload-1.2.2.jar
antlr-2.7.6.jar
freemarker-2.3.19.jar
ognl-3.0.5.jar
struts2-core-2.3.4.jar
xwork-core-2.3.4.jar
2)修改WEB-INF下的web.xml文件,增加struts2的配置。增加代码如下:这些配置代码对于struts2是不变的,直接复制到web.xml即可。
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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> </web-app>
3)添加struts配置文件。 在WEB-INF/classes目录下,新建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> </struts>
好了,struts基本配置完毕,是不是很简单?
现在把工程发布到tomcat上去,启动tomcat,如果启动无异常,则说明配置成功。
注意:可能会出现struts-default.xml相关异常,根据提示引入相关jar包。我测试的时候是缺少commons-io-2.0.1.jar包,于是引入了commons-io-2.0.1.jar。
3.2 配置一个Action
下面开始配置一个Action吧,以用户登录为例:
1)首先新建一个登陆页面login.jsp,代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>登录</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <s:form name="form1" action="testLogin"> <s:textfield id="username" name="username" label="username" ></s:textfield> <s:password id="password" name="password" label="password" ></s:password> <s:submit label="submit"></s:submit> </s:form> <s:actionerror/> </body> </html>
2)在我们已经建好的struts.xml中来配置登录的action。这里定义登录action的名字为testLogin,配置代码如下:
<?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> <package name="struts2" extends="struts-default"> <action name="testLogin" class="test.strutsConfigure.TestLogin"> <result name="success">index.jsp</result> <result name="input">/strutsConfigure/login.jsp</result> <result name="error">/strutsConfigure/login.jsp</result> </action> </package> </struts>
3)下面就来编写具体的action类了。代码如下:
package test.strutsConfigure;
import com.opensymphony.xwork2.ActionSupport;
public class TestLogin extends ActionSupport {
private static final long serialVersionUID = 1689366594548952480L;
private String username;
private String password;
@Override
public String execute() throws Exception {
if(!username.equals("admin")){
super.addFieldError("username", "用户名错误");
return ERROR;
}
if(!password.equals("001")){
super.addFieldError("password", "密码错误");
return ERROR;
}
return SUCCESS;
}
@Override
public void validate() {
if(username == null || username.length() == 0){
super.addActionError("用户名不能为空");
}
if(password == null || password.length() == 0){
super.addActionError("密码不能为空");
}
}
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;
}
}
4)好了,一个Action就创建完成了,重启tomcat测试一下吧。如果第一次使用struts,你可能你明白上面的代码,以后慢慢学习即可,现在先来看一下效果吧。
打开登录页面http://localhost:8080/WeiboPortal/strutsConfigure/login.jsp,输入正确或错误的用户名和密码,看看有什么提示。
4 配置Hibernate
4.1 基础配置
1) 导入最小jar包,即使用Hibernate3所必需的jar包。下载Hibernate 3.6.10解压后,必需jar包都在lib”required目录下。必需jar包如下:
hibernate3.jar—————————–核心类库
antlr-2.7.6.jar—————————–代码扫描器,用来翻译HQL语句
commons-collections-3.1.jar———– Apache Commons包中的一个,包含了一些Apache开发的集合类,功能比java.util.*强大
commons-lang3-3.1.jar———– Apache Commons包中的一个,包含了一些Apache开发的集合类,功能比java.lang.*强大
dom4j-1.6.1.jar—————————-是一个Java的XML API,类似于jdom,用来读写XML文件的
javassist-3.12.0.GA.jar———————– Javassist 字节码解释器
jta-1.1.jar————————————标准的JTA API。
log4j-1.2.14.jar
c3p0-0.9.1.jar
cglib-2.2.jar
mysql-connector-java-5.1.7-bin.jar
slf4j-api-1.6.1.jar
2) 创建Hibernate配置文件。在WEB-INF”calsses目录下(工程的src包下)新建hibernate.cfg.xml。这是hibernate连接数据库的配置文件。这里以连接MySQL为例:
<?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> <property name="connection.useUnicode">true</property> <property name="connection.characterEncoding">UTF8</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="connection.url"> jdbc:mysql://localhost:3306/weibo_portal </property> <property name="connection.username">root</property> <property name="connection.password">system</property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="jdbc.batch_size">25</property> <property name="c3p0.max_size">20</property> <property name="c3p0.min_size">5</property> <property name="c3p0.timeout">300</property> <property name="c3p0.max_statements">50</property> <property name="c3p0.idle_test_period">3000</property> <property name="show_sql">true</property> <mapping resource="com/huawei/pojo/UserInfo.hbm.xml" /><!--UserInfo实体bean类的hbm文件--> </session-factory> </hibernate-configuration>
3) 创建Session工厂类HibernateSessionFactory。
让我们先了解一下Session, Hibernat 对数据库的操作是通过Session来实现的,这里的session不同于页面间传递参数的session,而是类似于JDBC中的 Connection。Session是Hibernate运作的中心,对象的生命周期、事务的管理、数据库的存取都与session息息相关。
而Session是由HibernateSessionFactory创建的,是线程安全的,可以让多个执行线程同时存取HibernateSessionFactory而不会有数据共享的问题,但不能让多个线程共享一个Session。
HibernateSessionFactory可以用myeclispe自动创建
package com.huawei.dao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
同时配置一下日志文件,使用log4j,文件名log4j.properties
log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE}=>%5p %c(1):L - %m%n log4j.rootLogger=INFO, stdout log4j.logger.org.hibernate=INFO log4j.logger.org.hibernate.type=INFO
注意:别忘了把数据库驱动包引入到工程中。对于MySQL是mysql-connector-java-5.1.7-bin.jar。
4.2 示例
这个自己去测试一下吧。
5 配置Spring2.5
5.1 基础配置
1)导入spring包
org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.jdbc-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar
org.springframework.orm-3.1.1.RELEASE.jar
由于spring默认开启了日志,还需要加入commons-logging的jar包,否则会报错。
建议不要一次性加入 应该先加最核心的运行代码看缺少什么加什么,这样就不会加多余的包进来了,spring3已经把包按功能分开,不像以前一个包,这样更灵活,只要运行我们需要的功能,而没用到的就不用在硬性的添加进来。
2) 配置web.xml文件。Jar包引入完成后,就开始配置spring了,首先修改web.xml文件,增加如下代码:
<!-- 配置Spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>application*.xml</param-value> </context-param>
3) 在src下面新建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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> </beans>
5.2 示例
Spring基本配置完毕,让我们建个示例来测试一下吧,首先在test.spring包下创建两个java文件:TUser.java、SpringTest.java。
TUser.java:
package test.springTest;
import java.io.Serializable;
public class TUser implements Serializable{
private static final long serialVersionUID = -7072165319140144554L;
private String username;
private String allname;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAllname() {
return allname;
}
public void setAllname(String allname) {
this.allname = allname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
SpringTest.java:
package test.springTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
public static void main( String[] args ) {
//加载spring配置文件,初始化IoC容器
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//从容器 接管Bean
TUser user = (TUser) ac.getBean("TUser");
//输出欢迎信息
System.out.println( "Hello:" + user.getUsername() + ";u is in " + user.getAddress() + " ; and u is " + user.getAllname() );
}
}
创建完毕后,就剩最后一步了,在applicationContext.xml中配置一个bean,在xml中增加如下代码:
<bean id="TUser" class="test.springTest.TUser"> <property name="username" value="小张"></property> <property name="allname" value="张三"></property> <property name="address" value="青岛市"></property> </bean>
好了,下面运行一下吧,右键单击SpringTest.java选择run as Java Application,运行结果如下:
如果你的运行结果和上面一样,且没有异常,则说明Spring配置成功了
5.3 整合 Struts
Spring与Struts的整合其实就是把Struts的Action类交给Spring来管理,下面开始吧!
1) 导入jar包。在struts-2.3.4-all.zip的lib目录中找到struts2-spring-plugin-2.3.4.jar,引入到工程中。
2) 配置web.xml文件。在web.xml中加入以下代码:
<!-- 配置Spring的监听 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
3) 现在就来看如何把struts的action交给spring。以struts示例中的testLogin.action为例,首先创建一个LoginAction类的Bean。在applicationContext.xml中增加如下代码:
<bean name="loginAction" class="test.strutsConfigure.TestLogin" scope="prototype"> </bean>
这里,我们把这个bean的id设为loginAction。Scope设为prototype,含义是每一次请求创建一个LoginAction类的实例,Scope还有另一个值“singleton”意为“单例模式”。
接下来修改struts.xml文件,把原来login.action的配置做如下修改:
把
<action name="testLogin" class="test.strutsConfigure.TestLogin">
<result name="success">index.jsp</result>
<result name="input">/strutsConfigure/login.jsp</result>
<result name="error">/strutsConfigure/login.jsp</result>
</action>
改为
<action name="testLogin" class="loginAction">
<result name="success">index.jsp</result>
<result name="input">/strutsConfigure/login.jsp</result>
<result name="error">/strutsConfigure/login.jsp</result>
</action>
区别在于class值设为了loginAction,即LoginAction类的bean的ID。这样我们就把LoginAction类交给了spring管理。至于具体是怎么处理的,秘密在struts2-spring-plugin-2.3.4.jar中,有空自己就去研究吧,现在会用就可以了。
5.4 整合 Hibernate
Spring整合Hibernate主要是对hibernate的Session进行管理,包含Session的创建、提交、关闭的整个生命周期。Spring对事务的管理应用了AOP的技术,配置前请先了解一下AOP的知识。
1) 配置sessionFactory,让spring来创建Session。在applicationContext.xml中增加如下代码:
<!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> </bean>
创建jdbc.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/weibo_portal jdbc.username=root jdbc.password=system
配置数据源
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean>
我们原来是用HibernateSessionFactory.java来创建Session的,现在删除即可,交给Spring创建。这里,创建了一个Session工厂类的Bean,其ID为“sessionFactory”。
2) 配置事务管理器。增加如下代码:
<!-- 配置事务管理器transactionManager --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean>
这里创建了一个id为txManager的事务管理器,它匹配一个session工厂,<ref bean=”sessionFactory”/>这个sessionFactory是指session工厂的ID。
3) 对事务管理器进行事务设置。增加如下代码:
<!-- 对事务管理器进行事务设置 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="insert*"/> <tx:method name="update*" /> <tx:method name="delete*" /> <tx:method name="modify*" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice>
这里创建了一个advice(通知),对事务管理器进行事务设置,这里意思是指,对于以save、del、update开头的方法应用事务。
4) 下面就把事务应用到具体的类。看如下代码:
<aop:config id="txMethod"> <aop:advisor pointcut="execution(* test.service.impl.*.*(..))" advice-ref="txAdvice" /> </aop:config>
这里配置的作用是把我们上面创建的advice应用到具体的类中。以上代码的意思指,给test.service.impl下的所有类的所有方法应用smAdvice。