SSH框架整合——基于注解
@(Spring)[Spring, hibernate, struts2, 框架整合]
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
<?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: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"/>
<!-- 配置c3p0数据源-->
<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
<?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_2_5.xsd"
id="WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- 配置Struts2核心过滤器 -->
<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>
<!-- 配置Spring核心监听器 -->
<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>
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" %>
<!DOCTYPE HTML>
<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
中添加
<!-- 配置Hibernate的SessionFactory,无hibernate配置文件 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置hibernate属性-->
<property name="hibernateProperties">
<props>
<!-- 数据库的方言 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 是否显示SQL语句 -->
<prop key="hibernate.show_sql">true</prop>
<!-- 是否格式化显示SQL语句 -->
<!-- <prop key="hibernate.format_sql">true</prop> -->
<!-- 采用何种策略来创建表结构: -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 配置实体注解扫描 -->
<property name="packagesToScan">
<list>
<value>com.pc.crm.domain</value>
</list>
</property>
</bean>
第十步配置Hibernate模板
- 在
applicationContext.xml
中添加
<!-- 配置hibernate模板 -->
<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
核心过滤器上面
<!-- 配置OpenSessionInview过滤器 -->
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
配置全站编码过滤器
- 在
web.xml
中添加,注意要放在Struts2
核心过滤器上面
<!-- 配置Spring的字符编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>