SSH笔记---基础框架搭建

一、加入 Spring:使用 Spring 整合 Hibernate 和 Struts2

1.1. 加入 jar 包

spring_jar

1.2. 配置 web.xml 文件

1.2.1 原来的配置:
spring_web1
1.2.2 添加配置:

<?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"
    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">

    <!-- 配置启动 Ioc 容器的 Listener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 配置文件的位置 -->
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>  

1.3. 加入 Spring 的配置文件

1.3.1 新建 conf 源码包
spring_conf
1.3.2 编辑 Spring 的配置文件 applicationContext.xml

conf/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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

</beans>

二、加入 Hibernate

2.1. 加入 jar 包

hibernate_jar

2.2. 在类路径下加入 hibernate.cfg.xml 文件,在其中配置 Hibernate 的基本属性

conf/hibernate.cfg.xml:

<?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>
        <!-- 配置 hibernate 的基本属性 -->
        <!-- 方言 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <!-- 是否显示及格式化 SQL -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <!-- 生成数据表的策略 -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- 二级缓存相关 -->

    </session-factory>

</hibernate-configuration>

2.3. 建立持久化类和其对应的 .hbm.xml 文件

2.3.1 创建实体类 Department

public class Department {

    private Integer id;
    private String departmentName;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getDepartmentName() {
        return departmentName;
    }
    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    public Department() {}

    public Department(Integer id, String departmentName) {
        this.id = id;
        this.departmentName = departmentName;
    }

}

2.3.2 创建实体类 Employee

public class Employee {

    private Integer id;
    private String lastName;        // 一被创建,则不能修改
    private String email;
    private Date birth;             // 从前端传入的是 String 类型,所以需要转换
    private Date createTime;        // 一被创建,则不能修改
    private Department department;  // 单向多对一的关联关系

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Department getDepartment() {
        return department;
    }
    public void setDepartment(Department department) {
        this.department = department;
    }

    public Employee() {}

    public Employee(Integer id, String lastName, String email, Date birth,
            Date createTime, Department department) {
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.birth = birth;
        this.createTime = createTime;
        this.department = department;
    }

}

2.3.3 创建映射文件 Department.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2014-7-22 11:21:48 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.johnnie.ssh.entities.Department" table="SSH_DEPARTMENT">

        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>

        <property name="departmentName" type="java.lang.String">
            <column name="DEPARTMENT_NAME" />
        </property>

    </class>
</hibernate-mapping>

2.3.4 创建映射文件 Employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2014-7-22 11:21:48 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.johnnie.ssh.entities.Employee" table="SSH_EMPLOYEE">

        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>

        <property name="lastName" type="java.lang.String">
            <column name="LAST_NAME" />
        </property>

        <property name="email" type="java.lang.String">
            <column name="EMAIL" />
        </property>

        <property name="birth" type="java.util.Date">
            <column name="BIRTH" />
        </property>

        <property name="createTime" type="java.util.Date">
            <column name="CREATE_TIME" />
        </property>

        <!-- 映射单向 n-1 的关联关系 -->
        <many-to-one name="department" class="com.johnnie.ssh.entities.Department">
            <column name="DEPARTMENT_ID" />
        </many-to-one>

    </class>
</hibernate-mapping>

结构图:
ssh_project

2.4. Spring 整合 Hibernate

2.4.1 加入 c3p0 和 MYSQL 的驱动
spring_hibernate

2.4.2 新建数据库 ssh
ssh_db

2.4.3 加入数据库配置文件 db.properties

[conf/db.properties]

# MySQL 的基本配置
jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///ssh

# 配置 c3p0
jdbc.initPoolSize=5
jdbc.maxPoolSize=10
# ...

注:user 和 password 的值请改为自己 Mysql 配置时的值

2.4.2 修改 Spring 的配置文件 applicationContext.xml:数据源、SessionFactory、声明式事务

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 配置 C3P0 数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>

        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>

    <!-- 配置 SessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <property name="mappingLocations" value="classpath:com/johnnie/ssh/entities/*.hbm.xml"></property>
    </bean>

    <!-- 配置 Spring 的声明式事务 -->
    <!-- 1. 配置 hibernate 的事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 2. 配置事务属性 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="lastNameIsValid" read-only="true" />
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

    <!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.johnnie.ssh.service.*.*(..))"
            id="txPointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
    </aop:config>

</beans>

2.4.3 新建 com.johnnie.ssh.service 包,存放所有的服务
ssh_service

2.5. 启动项目

运行项目,这时会看到原本是空的 ssh 数据库下生成了对应的数据表,如下:
ssh_table

三、加入 Struts2

3.1 加入 jar:若有重复的 jar,则删除较低版本的 jar

struts_jar

3.2 在 web.xml 文件中配置 Struts2 的 Filter

[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"
    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">

    <!-- 配置启动 IOC 容器的 Listener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 配置文件的位置 -->
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置 Struts2 的 Filter -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

3.3 加入 Struts2 的配置文件 strutsx.ml

[conf/struts.xml]

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">


    </package>

</struts>

3.4 Spring 整合 Struts2

3.4.1 加入 Struts2 的 Spring 插件 jar
struts_spring

3.4.2 在 Spring 的配置文件中正常配置 Action:注意 Action 的 scope 为 prototype

在 conf 下新建 applicationContext-beans.xml 文件,代码如下:
[conf/applicationContext-beans.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.xsd">

    <!-- 配置 Action,注意 Action 的 scope 为 prototype -->
    <bean id="employeeAction" class="com.johnnie.ssh.actions.EmployeeAction"
        scope="prototype">
    </bean>

</beans>

3.4.3 在 Struts2 的配置文件中配置 Action 时,class 属性指向该 Action 在 IOC 中的 id

[conf/struts.xml]

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">

        <!-- 配置 action -->
        <!-- class 属性指向该 Action 在 IOC 中的 id,即 applicationContext-beans.xml 中配置的 id -->
        <action name="emp-*" class="employeeAction" method="{1}">

        </action>

    </package>

</struts>

至此,SSH框架是正常搭建完毕了。接下来就是实现一些简单的功能。

四、完成功能:查询所有员工信息

4.1 初始化数据

4.1.1 ssh_department 表加入几条初始数据:
ssh_dep

4.1.2 ssh_employee 表加入数据:
ssh_emp

4.2 index.jsp

[WebContent/index.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>index</title>
    </head>
    <body>
        <!-- 显示所有的 Employee 信息 -->
        <a href="emp-list">List All Employees</a>
    </body>
</html>

4.3 EmployeeDao.java

新建 com.johnnie.ssh.dao 包,并在该包下新建 EmployeeDao 文件:

public class EmployeeDao {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Session getSession () {
        return this.sessionFactory.getCurrentSession();
    }

    public List<Employee> getAll(){
        // 若在 Dao 中只查询 Employee 的信息,而 Employee 和 Department 还是
        // 使用懒加载,页面上还需要显示员工部门信息,那么此时会出现懒加载异常
        // 解决办法:
        // 1.关闭懒加载 在 Employee.hbm.xml 的 many-to-one 中关闭懒加载 lazy = false-->不推荐
        // 2.获取 Employee 时使用迫切左外连接同时初始化其关联的 Department 对象-->推荐
        // 3.使用 OpenSessionInViewFilter
        String hql = "FROM Employee e LEFT OUTER JOIN FETCH e.department";

        return getSession().createQuery(hql).list();
    }

}

4.4 EmployeeService.java

在 com.johnnie.ssh.service 包下新建 EmployeeService 文件:

public class EmployeeService {

    private EmployeeDao employeeDao;

    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

    public List<Employee> getAll(){
        return this.employeeDao.getAll();
    }

}

4.5 EmployeeAction.java

新建 com.johnnie.ssh.actions 包,并在该包下新建 EmployeeAction 文件
[EmployeeAction]

public class EmployeeAction extends ActionSupport implements RequestAware {

    private static final long serialVersionUID = 1L;
    private EmployeeService employeeService;

    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    public String list () {
        request.put("employees", employeeService.getAll());
        return "list";
    }

    private Map<String, Object> request;

    @Override
    public void setRequest(Map<String, Object> request) {
        this.request = request;
    }

}

4.6 配置 applicationContext-beans.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.xsd">

    <bean id="employeeDao" class="com.johnnie.ssh.dao.EmployeeDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <bean id="employeeService" class="com.johnnie.ssh.service.EmployeeService">
        <property name="employeeDao" ref="employeeDao"></property>
    </bean>

    <!-- 配置 Action,注意 Action 的 scope 为 prototype -->
    <bean id="employeeAction" class="com.johnnie.ssh.actions.EmployeeAction"
        scope="prototype">
        <property name="employeeService" ref="employeeService"></property>
    </bean>

</beans>

4.7 配置 struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">

        <!-- 配置 action -->
        <!-- class 属性指向该 Action 在 IOC 中的 id,即 applicationContext-beans.xml 中配置的 id -->
        <action name="emp-*" class="employeeAction" method="{1}">
            <result name="list">/WEB-INF/views/emp-list.jsp</result>
        </action>

    </package>

</struts>

4.8 编辑 emp-list.jsp 文件:

WebContent/views/emp-list.jsp:

<%@ 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>emp-list</title>
    </head>
    <body>

        <h4>Employee List Page</h4>

        <s:if test="#request.employees == null || #request.employees.size() == 0">
            没有任何员工信息
        </s:if>
        <s:else>
            <table border="1" cellpadding="10" cellspacing="0">
                <tr>
                    <td>ID</td>
                    <td>LAST_NAME</td>
                    <td>EMAIL</td>
                    <td>BIRTH</td>
                    <td>CREATE_TIME</td>
                    <td>DEPT</td>
                </tr>

                <s:iterator value="#request.employees">
                    <tr>
                        <td>${id }</td>
                        <td>${lastName }</td>
                        <td>${email }</td>
                        <td>${birth }</td>
                        <td>${createTime }</td>
                        <td>${department.departmentName }</td>
                    </tr>
                </s:iterator>

            </table>            
        </s:else>

    </body>
</html>

4.10 运行项目:

结果如下:
4.10.1 index.jsp:
ssh_index

4.10.2 查看所有员工信息:
ssh_query

4.10.3 控制台 SQL 语句输出:
ssh_console

前往 bascker/javaworld 获取更多 Java 知识

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值