SSH框架整合——基于注解

SSH框架整合——基于注解

@(Spring)[Spring, hibernate, struts2, 框架整合]

  • SSH框架整合基于注解
    • SSH框架整合
      • 第一步导入Jar包
      • 第二步导入配置文件
      • 第三步创建相关的包和类
      • 第四步创建界面
      • 第五步配置组件注解扫描
      • 第六步配置Action注解
      • 第七步配置业务层接口和实现类
      • 第八步配置实体类和映射注解
      • 第九步配置会话工厂
      • 第十步配置Hibernate模板
      • 第十一步配置事务管理器和事务注解扫描
      • 第十二步配置持久层接口和实现类
    • 配置OpenSessionInView过滤器
    • 配置全站编码过滤器

SSH框架整合

第一步导入Jar包

导入的jar包在《SSH框架整合——基于XML配置文件》博文中都有所介绍,这里不再赘述。唯一不同的是,基于注解的SSH整合还需要导入Struts2注解整合包struts2-convention-plugin-x.x.x.jar

第二步导入配置文件

  • db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.user=root
jdbc.password=123456
  • applicationContext.xml

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

    
    <context:property-placeholder location="classpath:db.properties"/>

    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>
beans>
  • web.xml

<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_2_5.xsd"
         id="WebApp_ID" version="2.5">
    <welcome-file-list>
        <welcome-file>index.jspwelcome-file>
        <welcome-file>index.htmlwelcome-file>
    welcome-file-list>

    
    <filter>
        <filter-name>struts2filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>struts2filter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
web-app>
  • log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout

第三步创建相关的包和类

package com.pc.crm.domain;
import java.io.Serializable;

/**
 * 客户实体类
 * Created by Switch on 2016/12/3.
 */
public class Customer implements Serializable {

}
package com.pc.crm.dao;

/**
 * 客户持久层接口
 * Created by Switch on 2016/12/3.
 */
public interface CustomerDao {

}
package com.pc.crm.dao.impl;

import com.pc.crm.dao.CustomerDao;

/**
 * 客户持久层接口实现类
 * Created by Switch on 2016/12/3.
 */
public class CustomerDaoImpl implements CustomerDao {

}
package com.pc.crm.service;

/**
 * 客户服务接口
 * Created by Switch on 2016/12/3.
 */
public interface CustomerService {

}
package com.pc.crm.service.impl;

import com.pc.crm.service.CustomerService;

/**
 * 客户服务接口实现类
 * Created by Switch on 2016/12/3.
 */
public class CustomerServiceImpl implements CustomerService {

}
package com.pc.crm.web.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.pc.crm.domain.Customer;

/**
 * 客户Action
 * Created by Switch on 2016/12/3.
 */
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {

    // 模型驱动对象
    private Customer customer = new Customer();

    @Override
    public Customer getModel() {
        return this.customer;
    }
}

第四步创建界面

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
    <head>
        <title>首页title>
        <meta charset="utf-8">
    head>
    <body>
        <s:form action="customer_save" namespace="/customer" method="post">
            <s:textfield name="custName" maxLength="50" cssStyle="WIDTH: 180px" label="客户名称"/>
            <s:textfield name="custPhone" maxLength="50" cssStyle="WIDTH: 180px" label="固定电话"/>
            <s:textfield name="custMobile" maxLength="50" cssStyle="WIDTH: 180px" label="移动电话"/>
            <s:submit value="保存"/>
        s:form>
    body>
html>

第五步配置组件注解扫描

  • applicationContext.xml中添加

<context:component-scan base-package="com.pc.crm.web.action"/>
<context:component-scan base-package="com.pc.crm.*.impl"/>

第六步配置Action注解

package com.pc.crm.web.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.pc.crm.domain.Customer;
import com.pc.crm.service.CustomerService;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

/**
 * 客户Action
 * Created by Switch on 2016/12/3.
 */
// 控制器组件注解,用于Web层
@Controller("customerAction")
// Action是多例的,所以需要配置为Prototype范围
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
// Struts2的注解
// 等价于Struts2配置文件中的package元素的extends属性
@ParentPackage("struts-default")
// 等价于Struts2配置文件中的package元素的namespace属性
@Namespace("/customer")
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {
    @Resource(name = "customerService")
    // 注入客户服务对象
    private CustomerService customerService;

    // 模型驱动对象
    private Customer customer = new Customer();

    @Override
    public Customer getModel() {
        return this.customer;
    }

    // 等价于Struts2配置文件中的action元素的name属性和method属性的复合
    @Action("customer_save")
    public String save() {
        System.out.println("Action的Save方法执行了");
        customerService.save(customer);

        return NONE;
    }
}

第七步配置业务层接口和实现类

package com.pc.crm.service;

import com.pc.crm.domain.Customer;

/**
 * 客户服务接口
 * Created by Switch on 2016/12/3.
 */
public interface CustomerService {
    /**
     * 保存客户
     *
     * @param customer
     */
    void save(Customer customer);
}
package com.pc.crm.service.impl;

import com.pc.crm.dao.CustomerDao;
import com.pc.crm.domain.Customer;
import com.pc.crm.service.CustomerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 客户服务接口实现类
 * Created by Switch on 2016/12/3.
 */
// 服务层组件注解,用于服务层
@Service("customerService")
// 配置事务,使用默认配置
@Transactional
public class CustomerServiceImpl implements CustomerService {

    @Resource(name = "customerDao")
    // 注入客户持久层对象
    private CustomerDao customerDao;

    @Override
    public void save(Customer customer) {
        System.out.println("Service中的save方法执行了");
        customerDao.save(customer);
    }
}

第八步配置实体类和映射注解

package com.pc.crm.domain;

import javax.persistence.*;
import java.io.Serializable;

/**
 * 客户实体类
 * Created by Switch on 2016/12/3.
 */
// 配置为实体类
@Entity
// 配置对应的表名
@Table(name = "cst_customer")
public class Customer implements Serializable {
    // 配置ID,主键
    @Id
    // 配置主键生成策略为由底层数据库生成
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    // 配置数据库中字段的名字等属性
    @Column(name = "cust_id")
    private Long custId; // 客户编号(主键)
    @Column(name = "cust_name")
    private String custName; // 客户名称(公司名称)
    @Column(name = "cust_phone")
    private String custPhone; // 固定电话
    @Column(name = "cust_mobile")
    private String custMobile; // 移动电话

    public Long getCustId() {
        return custId;
    }

    public void setCustId(Long custId) {
        this.custId = custId;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

    public String getCustMobile() {
        return custMobile;
    }

    public void setCustMobile(String custMobile) {
        this.custMobile = custMobile;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custPhone='" + custPhone + '\'' +
                ", custMobile='" + custMobile + '\'' +
                '}';
    }
}

第九步配置会话工厂

  • applicationContext.xml中添加

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    
    <property name="dataSource" ref="dataSource"/>

    
    <property name="hibernateProperties">
        <props>
            
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
            
            <prop key="hibernate.show_sql">trueprop>
            
            
            
            <prop key="hibernate.hbm2ddl.auto">updateprop>
        props>
    property>

    
    <property name="packagesToScan">
        <list>
            <value>com.pc.crm.domainvalue>
        list>
    property>
bean>

第十步配置Hibernate模板

  • applicationContext.xml中添加

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <property name="sessionFactory" ref="sessionFactory"/>
bean>

第十一步配置事务管理器和事务注解扫描

  • applicationContext.xml中添加

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
bean>


<tx:annotation-driven transaction-manager="transactionManager"/>

第十二步配置持久层接口和实现类

package com.pc.crm.dao;

import com.pc.crm.domain.Customer;

/**
 * 客户持久层接口
 * Created by Switch on 2016/12/3.
 */
public interface CustomerDao {

    /**
     * 保存客户
     *
     * @param customer
     */
    void save(Customer customer);
}
package com.pc.crm.dao.impl;

import com.pc.crm.dao.CustomerDao;
import com.pc.crm.domain.Customer;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * 客户持久层接口实现类
 * Created by Switch on 2016/12/3.
 */
// 持久层组件注解,用于持久层
@Repository("customerDao")
public class CustomerDaoImpl implements CustomerDao {

    @Resource(name = "hibernateTemplate")
    // 注入Hibernate模板
    private HibernateTemplate hibernateTemplate;

    @Override
    public void save(Customer customer) {
        System.out.println("Dao中的save方法执行了");
        this.hibernateTemplate.save(customer);
    }
}

配置OpenSessionInView过滤器

  • web.xml中添加,注意要放在Struts2核心过滤器上面

<filter>
    <filter-name>OpenSessionInViewFilterfilter-name>
    <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilterfilter-class>
filter>
<filter-mapping>
    <filter-name>OpenSessionInViewFilterfilter-name>
    <url-pattern>*.actionurl-pattern>
filter-mapping>

配置全站编码过滤器

  • web.xml中添加,注意要放在Struts2核心过滤器上面

<filter>
    <filter-name>CharacterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
        <param-name>encodingparam-name>
        <param-value>UTF-8param-value>
    init-param>
    <init-param>
        <param-name>forceEncodingparam-name>
        <param-value>trueparam-value>
    init-param>
filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

你可能感兴趣的:(Spring,Struts2,Hibernate)