采用目前最新的struts-2.3.1.2、hibernate3.6.10.Final、spring-framework-3.1.1.RELEASE开发包,以及eclipse-jee-indigo-SR2-win32、apache-tomcat-7.0.27服务器、JDK6和mysql5做开发环境,参考了前辈的一篇,改正了其中的错误和疏漏,克服了公司分配的“新”机器每小时自动重启三次的困难,终于把环境给搭好了。整个过程中遵循的一个原则是,避免引入用不到的jar包,以求搭建一个最小的SSH运行环境。
首先创建一个Dynamic web project 输入任意名字如SSHBase。
第一步:加载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已经把包按功能分开,不像以前一个包,这样更灵活,只要运行我们需要的功能,而没用到的就不用在硬性的添加进来。
包加好了之后我们开始创建spring应用,创建一个XML文件ApplicationContext.xml(放在src根目录),下面是基本结构
- <?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
- <a href="http://www.springframework.org/schema/beans/spring-beans-3.0.xsd'%3E">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <span style="color:#000000;"></span>
- </a><!--在这里面添加beans-->
- </beans>
写一个用例来测试一下spring搭建好了没有,创建一个Person类:
- public class Person {
- private String name;
- private int age;
- /* 也可以写get方法这边就不写了,不写也行spring没有要求一定要有 */
- public void setName(String name) {
- this.name = name;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String toString() {
- return "name : " + name + " age : " + age; // 重写toString方法以便输出信息
- }
- }
然后在配置文件,也就是AppliccationContext.xml里面添加bean相关配置,要注意类的包路径(这是值注入,还有接口和构造注入):
- <bean id="nike" class="Person" scope="prototype" >
- <property name="name" value="XXX"></property>
- <property name="age" value="18"></property>
- </bean>
再写一个测试类,来进行测试:
- import org.springframework.beans.factory.xml.XmlBeanFactory;
- import org.springframework.core.io.FileSystemResource;
- public class testSpring {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- XmlBeanFactory beansfactory = new XmlBeanFactory(new FileSystemResource("src/ApplicationContext.xml"));
- System.out.println(beansfactory);
- Person nike = (Person)beansfactory.getBean("nike");
- System.out.println(nike);
- }
- }
运行效果应该看到: name : XXX age : 18
这就证明搭建好了,beans已经自己创建。
第二步:整合hibernate
需要的包如下:
antlr-2.7.6.jar commons-collections-3.1.jar commons-logging-1.1.1.jar dom4j-1.6.1.jar
hibernate3.jar slf4j-api-1.6.1.jar hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.12.0.GA.jar jta-1.1.jar ejb3-persistence.jar
加好之后在spring里面配置hibernate(假定在数据库已经创建了一个叫做myTest的数据库)
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- 定义数据源 -->
- <property name="driverClassName" value="com.mysql.jdbc.Driver"/><!-- 定义数据库驱动-->
- <property name="url" value="jdbc:mysql://localhost:3306/mytest?characterEncoding=UTF-8"/><!-- 连接字符串-->
- <property name="username" value="root" /><!-- 账号-->
- <property name="password" value="root"/><!-- 密码-->
- </bean>
- <!-- 配置sessionFactory 配置 -->
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
- <property name="annotatedClasses" >
- <list>
- <value>com.neareast.test.Person</value><!-- 定义元素关联,xml文件也可以配置我这边直接用annoration配置 -->
- </list>
- </property>
- <property name="hibernateProperties"><!--hibernate参数-->
- <props>
- <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
- <prop key="hibernate.show_sql">true</prop>
- <prop key="hiberante.format_sql">true</prop>
- <prop key="hibernate.hbm2ddl.auto">update</prop>
- </props>
- </property>
- </bean>
- <!--定义DAO-->
- <bean id="personDao" class="com.neareast.test.PersonDao">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
然后修改一下刚才的Person类,并加上注解,就可以用了:
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.Id;
- import javax.persistence.Table;
- @Entity
- @Table(name="person")
- public class Person {
- @Id
- @Column(unique=true,name="id",nullable=false)
- private int id ;
- @Column(name="name",length=20)
- private String name;
- @Column(name="age")
- private int age;
- /*也可以写get方法这边就不写了,不写也行spring没有要求一定要有*/
- public void setName(String name){
- this.name=name;
- }
- public void setId(int id ){
- this.id = id;
- }
- public void setAge(int age){
- this.age=age;
- }
- public String toString() {
- return "name : " + name + " age : " + age;//重写toString方法以便输出信息
- }
- }
DAO接口中定义了四个简单的方法:
- public interface IPersonDao {
- public void createPerson(Person person);
- public List<Serializable> getAll();
- public int count();
- public void drop(Person person);
- }
其实现如下:
- import org.hibernate.Query;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- public class PersonDao implements IPersonDao {
- private SessionFactory sessionFactory;
- @Override
- public void createPerson(Person person) {
- Session session = sessionFactory.openSession();
- session.beginTransaction();
- session.save(person);
- session.beginTransaction().commit();
- }
- @Override
- public List<Serializable> getAll() {
- Session session = sessionFactory.openSession();
- String sql = "from Person";
- session.beginTransaction();
- Query query = session.createQuery(sql);
- return query.list();
- }
- @Override
- public int count() {
- Session session = sessionFactory.openSession();
- String sql = "from Person";
- session.beginTransaction();
- Query query = session.createQuery(sql);
- return query.list().size();
- }
- @Override
- public void drop(Person person) {
- Session session = sessionFactory.openSession();
- session.beginTransaction();
- session.delete(person);
- session.beginTransaction().commit();
- }
- public void setSessionFactory(SessionFactory sessionFactory) {
- this.sessionFactory = sessionFactory;
- }
- }
然后再写一个简单的用例来测试:
- import org.springframework.beans.factory.xml.XmlBeanFactory;
- import org.springframework.core.io.FileSystemResource;
- public class TestHibernate {
- public static void main(String[] args) {
- XmlBeanFactory beansfactory = new XmlBeanFactory(
- new FileSystemResource("src/ApplicationContext.xml"));
- PersonDao persondao = (PersonDao) beansfactory.getBean("personDao");
- Person person = new Person();
- person.setAge(123);
- person.setName("哈哈哈");
- persondao.createPerson(person);
- System.out.println(persondao.getAll().size());
- }
- }
由于数据表设置成自动更新,在没有表的情况下,hibernate会帮我们自动创建表和他们之间的关系。打开mysql客户端 输入:
use mytest;
select * from person;
如果看到我们的数据就证明OK了!
在这我们就已经将hibernate 基本整合好了!
第三步:整合Struts2
引入下列jar包:
struts2-core-2.3.1.2.jar struts2-spring-plugin-2.3.1.2.jar xwork-core-2.3.1.2.jar commons-io-2.0.1.jar commons-lang-2.5.jar
ognl-3.0.4.jar freemarker-2.3.18.jar commons-logging-api-1.1.jar commons-fileupload-1.2.2.jar
在WEB-INF目录下,创建并编辑web.xml文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
- id="WebApp_ID" version="3.0">
- <display-name>SSHBase1.0</display-name>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/classes/ApplicationContext.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <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>
在src下创建配置文件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>
- <constant name="struts.devMode" value="true" />
- <!--很重要注明工厂 -->
- <constant name="struts.objectFactory" value="spring"></constant>
- <package name="myPackage" extends="struts-default">
- <action name="index">
- <result>/index.jsp</result>
- </action>
- <!-- 第一个测试的 -->
- <action name="helloAction" class="hello" method="getPerson">
- <result name="SUCCESS">/hello.jsp</result>
- </action>
- </package>
- </struts>
接下来,创建相应的Action,(注意此处可能需要手动引入服务器的Server Runtime库),例如:
- import javax.servlet.http.HttpServletRequest;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- public class HelloAction extends ActionSupport {
- private static final long serialVersionUID = 1L;
- private IPersonDao dao;
- /*
- * 测试方法 spring 值注入顺序是按照配置文件值的顺序注入
- */
- public String getPerson() {
- System.out.println(dao);
- HttpServletRequest request = ServletActionContext.getRequest();
- request.getSession().setAttribute("personlist", dao.getAll());
- return "SUCCESS";
- }
- public IPersonDao getDao() {
- return dao;
- }
- public void setDao(IPersonDao dao) {
- this.dao = dao;
- }
- }
然后在spring的配置文件里,配置相应的class bean:
- <bean id="hello" class="com.neareast.test.HelloAction">
- <property name="dao" ref="personDao"></property>
- </bean>
接下来创建个页面来进行测试,可在WebContent下面创建一个hello.jsp页面:
- <%@ page language="java" contentType="text/html; charset=utf-8"
- pageEncoding="utf-8"%>
- <!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>test OK</title>
- </head>
- <body>
- 测试OK
- <br>
- <a> 姓 :</a>
- <label>${personlist}</label>
- <br />
- </body>
- </html>
最后,启动服务器,在浏览器中输入: ,就可以看到我们数据库里的数据了。
至此,最基本的SSH已经整合完毕!
整个项目的代码我已经打包上传,欢迎下载,链接如下: