Spring2.5+Hibernate3.3+Struts2整合开发

接下来我来学习一下SSH的整合开发,我们学完前面的基本原理之后,这里主要讲的就是相关文件的配置了。首先我们把相关的jar包拷贝到WEB-INF文件夹下面的lib文件夹。

ssh-lib

首先还是配置数据源::

jdbc属性文件

1
2
3
4
5
6
7
8
driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=test
initialSize=3
maxActive=500
maxIdle=2
minIdle=1

beans.xml部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<context:annotation-config/>
     <!-- 配置数据源 -->
     <context:property-placeholder location="classpath:jdbc.properties"/>
     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
         <!-- 连接池启动时的初始值 -->
         <property name="initialSize" value="${initialSize}"/>
         <!-- 连接池的最大值 -->
         <property name="maxActive" value="${maxActive}"/>
         <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
         <property name="maxIdle" value="${maxIdle}"/>
         <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
         <property name="minIdle" value="${maxIdle}"/>
      </bean>
    <!-- 配置sessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
         <property name="dataSource" ref="dataSource"/>
         <property name="mappingResources">
            <list>
              <value>cn/lpq/bean/Person.hbm.xml</value>
            </list>
         </property>
         <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
                hibernate.hbm2ddl.auto=update
                hibernate.show_sql=false
                hibernate.format_sql=false
                hibernate.cache.use_second_level_cache=true
                hibernate.cache.use_query_cache=false
                hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
              </value>
         </property>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!-- 采用@Transactional注解方式使用事务 -->
    <tx:annotation-driven transaction-manager="txManager"/>

bean类:

Person.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package cn.lpq.bean;

public class Person {
    private Integer id;
    private String name;
   
    public Person(){}
   
    public Person(String name) {
        this.name = name;
    }
   
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Person.hbm.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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="cn.lpq.bean">
    <class name="Person" table="person">
        <cache usage="read-write" region="cn.lpq.bean.Person"/>
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name" length="10" not-null="true"/>
    </class>
</hibernate-mapping>

PersonSevice.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package cn.lpq.service;

import java.util.List;

import cn.lpq.bean.Person;

public interface PersonService {

    public void save(Person person);

    public void update(Person person);

    public Person getPerson(Integer personid);

    public void delete(Integer personid);

    public List<Person> getPersons();

}

PersonServiceBean.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package cn.lpq.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.lpq.bean.Person;
import cn.lpq.service.PersonService;

@Transactional
public class PersonServiceBean implements PersonService {
    @Resource private SessionFactory sessionFactory;

    public void save(Person person){
        sessionFactory.getCurrentSession().persist(person);
    }
   
    public void update(Person person){
        sessionFactory.getCurrentSession().merge(person);
    }
    @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
    public Person getPerson(Integer personid){
        return (Person)sessionFactory.getCurrentSession().get(Person.class, personid);
    }

    public void delete(Integer personid){
        sessionFactory.getCurrentSession().delete(
                sessionFactory.getCurrentSession().load(Person.class, personid));
    }
    @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
    @SuppressWarnings("unchecked")
    public List<Person> getPersons(){      
        return sessionFactory.getCurrentSession().createQuery("from Person").list();
    }
   
}

控制器:

PersonAction.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package cn.lpq.web.action;

import java.util.List;

import javax.annotation.Resource;

import org.apache.struts.action.Action;

import cn.lpq.bean.Person;
import cn.lpq.service.PersonService;

public class PersonAction extends Action {
    @Resource PersonService personService;
    private String messgae;
    private List<Person> persons;
    private Person person;
   
   
    /**
     * 人员列表显示
     * @return
     */

    public String list(){
        this.persons = personService.getPersons();
        return "list";
    }
   
    /**
     * 人员添加界面
     * @return
     */

    public String addUI(){
        return "add";
    }
   
    /**
     * 人员添加
     * @return
     */

    public String add(){
        this.personService.save(person);
        this.messgae = "添加成功!";
        return "message";
    }
   
    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
   
    public List<Person> getPersons() {
        return persons;
    }

    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }

    public PersonService getPersonService() {
        return personService;
    }

    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    public String getMessgae() {
        return messgae;
    }

    public void setMessgae(String messgae) {
        this.messgae = messgae;
    }
}

配置bean

1
2
3
<!-- 配置bean -->
    <bean id="personService" class="cn.lpq.service.impl.PersonServiceBean"/>
    <bean id="personList" class="cn.lpq.web.action.PersonAction"/>

配置二级缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<!--
    defaultCache节点为缺省的缓存策略
     maxElementsInMemory 内存中最大允许存在的对象数量
     eternal 设置缓存中的对象是否永远不过期
     overflowToDisk 把溢出的对象存放到硬盘上
     timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉
     timeToLiveSeconds 指定缓存对象总的存活时间
     diskPersistent 当jvm结束是是否持久化对象
     diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间
 -->
<ehcache>
    <diskStore path="D:\cache"/>
    <defaultCache  maxElementsInMemory="1000" eternal="false" overflowToDisk="true"
        timeToIdleSeconds="120"
        timeToLiveSeconds="180"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="60"/>
    <cache name="cn.itcast.bean.Person" maxElementsInMemory="100" eternal="false"
    overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/>
</ehcache>

配置struts.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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>
    <!-- 指定Web应用的默认编码集,相当于调用HttpServletRequest的setCharacterEncoding方法 -->
    <constant name="struts.i18n.encoding" value="UTF-8"/>
    <!-- 该属性指定需要Struts 2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。
    如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
    <constant name="struts.action.extension" value="do"/>
    <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
    <constant name="struts.serve.static.browserCache" value="false"/>
    <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
    <constant name="struts.configuration.xml.reload" value="true"/>
    <!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
    <constant name="struts.devMode" value="true" />
     <!-- 默认的视图主题 -->
    <constant name="struts.ui.theme" value="simple" />
    <constant name="struts.objectFactory" value="spring" />
   
    <package name="person" namespace="/person" extends="struts-default">
        <global-results>
            <result name="message">/WEB-INF/page/message.jsp</result>
        </global-results>
        <action name="action_*" class="personList" method="{1}">
            <result name="list">/WEB-INF/page/personlist.jsp</result>
            <result name="add">/WEB-INF/page/addperson.jsp</result>
            <result name="message">/WEB-INF/page/message.jsp</result>
        </action>
    </package>
</struts>

配置web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
>
   
    <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:beans.xml</param-value>
    </context-param>
    <!-- 对Spring容器进行实例化 -->
    <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
   
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
    <filter>
            <filter-name>OpenSessionInViewFilter</filter-name>
            <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    </filter>
    <filter-mapping>
            <filter-name>OpenSessionInViewFilter</filter-name>
            <url-pattern>/*</url-pattern>
    </filter-mapping>
   
    <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>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

jsp页面:

addperson.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>添加用户</title>
  </head>
 
  <body>
    <s:form action="action_add" namespace="/person">
        姓名:<s:textfield name="person.name"></s:textfield>
        <input type="submit" value="提交"/>
    </s:form>
  </body>
</html>

personList.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    <title>人员列表</title>

  </head>
 
  <body>
   <s:iterator value="persons">
   id=<s:property value="id"/>
   name=<s:property value="name"/>
   </s:iterator>

  </body>
</html>

message.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
        <title>提示信息</title>
  </head>
 
  <body>
    <s:property value="messgae"/>
  </body>
</html>

 

发布、运行服务器:

输入http://localhost:8080/SSH/person/action_add.do  添加用户

http://localhost:8080/SSH/person/action_list.do   显示用户列表

除非注明,Coder文章均为原创,转载请以链接形式标明本文地址

本文地址:http://www.alonemonkey.com/ssh.html

本文链接:http://www.alonemonkey.com/ssh.html