1、三大框架整合原理
2、整合详解
2.1 导包
2.2 单独配置Spring容器(配置过程中切记配一步测一步即服务器重启测试是否报错)
applicationContext.xml(src目录下)
web.xml(WEB-INF目录下)
2.3单独配置Struts2
struts.xml(src目录下)
2.4 Spring和Struts2整合
Struts.xml(src目录下)
2.6 Spring整合c3p0连接池取代hibernate中的连接
cn.ctgu.dao
UserDao.java
package cn.ctgu.dao;
import cn.ctgu.domain.User;
public interface UserDao {
//根据登陆名称查询user对象
User getByUserCode(String usercode);
//保存用户
void save(User u);
}
cn.ctgu.dao.impl
UserDaoImpl.java
package cn.ctgu.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import cn.ctgu.dao.UserDao;
import cn.ctgu.domain.User;
//需要为HibernateDaoSupport注入sessionFactory
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
@Override
public User getByUserCode(final String usercode) {
//HQL方式
/*return getHibernateTemplate().execute(new HibernateCallback() {
@Override
public User doInHibernate(Session session) throws HibernateException {
String hql="from User where user_code=?";
Query query = session.createQuery(hql);
query.setParameter(0, usercode);
User user=(User) query.uniqueResult();
return user;
}
});*/
//Criteria方式
DetachedCriteria dc=DetachedCriteria.forClass(User.class);
dc.add(Restrictions.eq("user_code", usercode));
List list=(List) getHibernateTemplate().findByCriteria(dc);
if(list!=null && list.size()>0) {
return list.get(0);
}else {
return null;
}
}
@Override
public void save(User u) {
getHibernateTemplate().save(u);
}
}
cn.ctgu.domain
Customer.java
package cn.ctgu.domain;
/*CREATE TABLE customer(
id BIGINT(32) NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT'客户编号(主键)',
NAME VARCHAR(32) NOT NULL COMMENT '客户名称(公司名称)',
source VARCHAR(32) DEFAULT NULL COMMENT '客户信息来源',
industry VARCHAR(32)DEFAULT NULL COMMENT '客户所属行业',
LEVEL VARCHAR(32) DEFAULT NULL COMMENT '客户级别',
phone VARCHAR(64) DEFAULT NULL COMMENT '固定电话',
mobile VARCHAR(16) DEFAULT NULL COMMENT '移动电话'
);*/
public class Customer {
private Long id;
private String name;
private String source;
private String industry;
private String level;
private String phone;
private String mobile;
private String linkman;
public String getLinkman() {
return linkman;
}
public void setLinkman(String linkman) {
this.linkman = linkman;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getIndustry() {
return industry;
}
public void setIndustry(String industry) {
this.industry = industry;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + "]";
}
}
LinkMan.java
package cn.ctgu.domain;
//联系人实体
public class LinkMan {
private Long lkm_id;
private Character lkm_gender;
private String lkm_name;
private String lkm_phone;
private String lkm_email;
private String lkm_qq;
private String lkm_mobile;
private String lkm_memo;
private String lkm_position;
//不与数据库中的列对应,只为了接收表单参数
private Long cust_id;
//表达多对一的关系
private Customer customer;
public Long getCust_id() {
return cust_id;
}
public void setCust_id(Long cust_id) {
this.cust_id = cust_id;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Long getLkm_id() {
return lkm_id;
}
public void setLkm_id(Long lkm_id) {
this.lkm_id = lkm_id;
}
public Character getLkm_gender() {
return lkm_gender;
}
public void setLkm_gender(Character lkm_gender) {
this.lkm_gender = lkm_gender;
}
public String getLkm_name() {
return lkm_name;
}
public void setLkm_name(String lkm_name) {
this.lkm_name = lkm_name;
}
public String getLkm_phone() {
return lkm_phone;
}
public void setLkm_phone(String lkm_phone) {
this.lkm_phone = lkm_phone;
}
public String getLkm_email() {
return lkm_email;
}
public void setLkm_email(String lkm_email) {
this.lkm_email = lkm_email;
}
public String getLkm_qq() {
return lkm_qq;
}
public void setLkm_qq(String lkm_qq) {
this.lkm_qq = lkm_qq;
}
public String getLkm_mobile() {
return lkm_mobile;
}
public void setLkm_mobile(String lkm_mobile) {
this.lkm_mobile = lkm_mobile;
}
public String getLkm_memo() {
return lkm_memo;
}
public void setLkm_memo(String lkm_memo) {
this.lkm_memo = lkm_memo;
}
public String getLkm_position() {
return lkm_position;
}
public void setLkm_position(String lkm_position) {
this.lkm_position = lkm_position;
}
}
User.java
package cn.ctgu.domain;
import java.util.HashSet;
import java.util.Set;
public class User {
private Long user_id;
private String user_code;
private String user_name;
private String user_password;
private Character user_state;
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
public String getUser_code() {
return user_code;
}
public void setUser_code(String user_code) {
this.user_code = user_code;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
public Character getUser_state() {
return user_state;
}
public void setUser_state(Character user_state) {
this.user_state = user_state;
}
@Override
public String toString() {
return "User [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password="
+ user_password + "]";
}
}
Customer.hbm.xml
<hibernate-mapping package="cn.ctgu.domain">
<class name="Customer" table="customer">
<id name="id" column="id">
<generator class="native">generator>
id>
<property name="name" column="NAME" >property>
<property name="source" column="source">property>
<property name="industry" column="industry">property>
<property name="level" column="LEVEL">property>
<property name="phone" column="phone">property>
<property name="mobile" column="mobile">property>
<property name="linkman" column="linkman">property>
class>
hibernate-mapping>
LinkMan.hbm.xml
<hibernate-mapping package="cn.ctgu.domain">
<class name="LinkMan" table="link_man">
<id name="lkm_id" >
<generator class="native">generator>
id>
<property name="lkm_name" >property>
<property name="lkm_phone" >property>
<property name="lkm_email" >property>
<property name="lkm_qq" >property>
<property name="lkm_mobile" >property>
<property name="lkm_memo" >property>
<property name="lkm_position" >property>
<property name="lkm_gender" >property>
<many-to-one name="customer" column="lkm_cust_id" class="Customer">many-to-one>
class>
hibernate-mapping>
User.hbm.xml
<hibernate-mapping package="cn.ctgu.domain">
<class name="User" table="user">
<id name="user_id" column="id">
<generator class="native">generator>
id>
<property name="user_name">property>
<property name="user_code" >property>
<property name="user_password">property>
<property name="user_state" >property>
class>
hibernate-mapping>
cn.ctgu.service
UserService.java
package cn.ctgu.service;
import cn.ctgu.domain.User;
public interface UserService {
//登陆方法
User getUserByCodePassword(User u);
//注册用户
void saveUser(User u);
}
cn.ctgu.service.impl
UserServiceImpl.java
package cn.ctgu.service.impl;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.ctgu.dao.UserDao;
import cn.ctgu.domain.User;
import cn.ctgu.service.UserService;
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
public class UserServiceImpl implements UserService{
private UserDao ud;
@Override
public User getUserByCodePassword(User u) {
//1、根据登陆名称查询登陆用户
User existU=ud.getByUserCode(u.getUser_code());
//2、判断用户是否存在,不存在=》抛出异常,提示用户名不存在
if(existU==null) {
throw new RuntimeException("用户名不存在!");
}
//3、判断用户密码是否正确=》不正确=》抛出异常,提示密码错误
if(!existU.getUser_password().equals(u.getUser_password())) {
throw new RuntimeException("密码错误!");
}
//4、返回查询到的用户对象
return existU;
}
@Override
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public void saveUser(User u) {
// TODO Auto-generated method stub
ud.save(u);
}
public void setUd(UserDao ud) {
this.ud = ud;
}
}
cn.ctgu.web.action
UserAction.java
package cn.ctgu.web.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import cn.ctgu.domain.User;
import cn.ctgu.service.UserService;
public class UserAction extends ActionSupport implements ModelDriven<User>{
private User user=new User();
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public String login() throws Exception {
//1、调用Service执行登陆逻辑
User u=userService.getUserByCodePassword(user);
//2、将返回的User对象放入session域
ActionContext.getContext().getSession().put("user", u);
//3、重定向到项目首页
return "toHome";
}
@Override
public User getModel() {
return user;
}
}
配置文件
applicationContext.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<context:property-placeholder location="classpath:db.properties"/>
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}">property>
<property name="driverClass" value="${jdbc.driverClass}">property>
<property name="user" value="${jdbc.user}">property>
<property name="password" value="${jdbc.password}">property>
bean>
<bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory">property>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
<property name="dataSource" ref="dataSource">property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
<prop key="hibernate.show_sql">trueprop>
<prop key="hibernate.format_sql">trueprop>
<prop key="hibernate.hbm2ddl.auto">updateprop>
props>
property>
<property name="mappingDirectoryLocations" value="classpath:cn/ctgu/domain">property>
bean>
<bean name="userAction" class="cn.ctgu.web.action.UserAction" scope="prototype">
<property name="userService" ref="userService">property>
bean>
<bean name="userService" class="cn.ctgu.service.impl.UserServiceImpl">
<property name="ud" ref="userDao">property>
bean>
<bean name="userDao" class="cn.ctgu.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory">property>
bean>
beans>
hibernate.cfg.cml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driverproperty>
<property name="hibernate.connection.url">jdbc:mysql:///hibernateproperty>
<property name="hibernate.connection.username">rootproperty>
<property name="hibernate.connection.password">123456property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialectproperty>
<property name="hibernate.show_sql">trueproperty>
<property name="hibernate.format_sql">trueproperty>
<property name="hibernate.hbm2ddl.auto">updateproperty>
<mapping resource="cn/ctgu/domain/Customer.hbm.xml"/>
<mapping resource="cn/ctgu/domain/LinkMan.hbm.xml"/>
<mapping resource="cn/ctgu/domain/User.hbm.xml"/>
session-factory>
hibernate-configuration>
struts.xml
<struts>
<constant name="struts.objectFactory" value="spring">constant>
<package name="crm" namespace="/" extends="struts-default">
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.RuntimeException">exception-mapping>
global-exception-mappings>
<action name="UserAction_*" class="userAction" method="{1}">
<result name="toHome" type="redirect">/index.htmresult>
<result name="error">/login.jspresult>
action>
package>
struts>
db.properties
jdbc.jdbcUrl=jdbc:mysql:///hibernate
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
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">
<display-name>Spring4display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<filter>
<filter-name>openSessionInViewfilter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilterfilter-class>
filter>
<filter-mapping>
<filter-name>openSessionInViewfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<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>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.htmwelcome-file>
<welcome-file>index.jspwelcome-file>
<welcome-file>default.htmlwelcome-file>
<welcome-file>default.htmwelcome-file>
<welcome-file>default.jspwelcome-file>
welcome-file-list>
web-app>