ssh;struts+spring+hibernate
通过一个项目来实现ssh整合:
1.导包:spring基本包,springsource下的包 struts2基本包,struts2与spring插件包 hibernate基本的包:
2.书写配置文件:
web.xml文件
数据库连接配置文件:db.properties
struts.xml:用于配置action
applicationContex.xml:用于配置所有的
web,xml文件:配置spring监听器,读取,spring的配置文件 扩大session的作用域,配置struts2拦截器
<!-- 让Spring随web容器启动而创建监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置session的作用域
注意 openSessionInView一定要在struts中的filter的之前
-->
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>
org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置struts拦截器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
struts.xml:用于配置action的操作配置拦截器,注意:
<!-- 配置常量意思是否把action对象交给Spring容器来管理和创建 -->
<constant name="struts.objectFactory" value="spring"></constant>
<!-- 用来配置Action的的依赖注入属性 -->
<constant name="struts.objectFactory.spring.autoWire" value="name"></constant>
这里的action所对应的class为appliationcontext.xml实例action时对应的id属性.在struts2高版本中需要用<allowed-method>标签来制定允许的action中的响应的方法
<struts>
<!-- developerment Mode:开发模式以后修改下面配置,不需要重新启动Tmocat服务器 -->
<constant name="struts.devMode" value="true" />
<!-- 配置常量意思是否把action对象交给Spring容器来管理和创建 -->
<constant name="struts.objectFactory" value="spring"></constant>
<!-- 用来配置Action的的依赖注入属性 -->
<constant name="struts.objectFactory.spring.autoWire" value="name"></constant>
<!-- 允许动作名称有斜杠 -->
<constant name="struts.enable.SlashesInActionNames " value="true"></constant>
<!-- user -->
<package name="user" namespace="/" extends="struts-default">
<interceptors>
<!-- 注册拦截器 -->
<interceptor name="privilegeInterceptor" class="com.leo.crm.interceptor.PrivilegeInterceptor"></interceptor>
<!-- 配置拦截器栈 -->
<interceptor-stack name="myStack">
<interceptor-ref name="privilegeInterceptor">
<param name="excludeMethods">login,regist</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 指定默认拦截器栈 -->
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<!-- 全局结果集配置 -->
<global-results>
<result name="toLogin" type="redirect" >/login.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
</global-exception-mappings>
<!--方案二: class属性填写Spring中action对象的beanName,就是spring管理的xml中配置的bean的名字。完全有Spring来创建管理action的周期
注意;Spring不能自动组装,只能手动注入依赖属性 -->
<!-- 关键地方 struts2.5 为了提升安全性,添加了 allomethod 这个属性
<global-allowed-methods>regex:.*</global-allowed-methods>-->
<action name="userAction_*" class="userAction" method="{ 1 }">
<result name="toHome" type="redirect">/index.htm</result>
<result name="error">/login.jsp</result>
<allowed-methods>login</allowed-methods>
</action>
<action name="userAction_login" class="userAction" method="login">
<result name="toHome" type="redirect">index.htm</result>
<result name="error">/login.jsp</result>
</action>
</package>
在applicationConte.xml需要做以下配置:
1.引入数据源配置文件,2.引入hibernate的映射文件3.注入sesssionfactory,4.实例化其他的各个层
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 1.将连接池交给Spring管理 -->
<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>
<!-- 2。核心事务管理让spring来管理事务
<bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>-->
<!-- 3。加载配置hibernate信息 -->
<bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 将连接池注入到sessionFactory中,使其获得连接 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置hibernate信息 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto" >update</prop>
<prop key="hibernate.dialect" >org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql" >true</prop>
<prop key="hibernate.format_sql" >true</prop>
</props>
</property>
<!-- 引入orm元数据,读取hibernate映射配置文件 -->
<property name="mappingDirectoryLocations" value="classpath:com/leo/crm/domain"></property>
</bean>
<!--4.配置Action -->
<bean name="userAction" class="com.leo.crm.web.action.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean>
<!-- 创建对象UserService -->
<bean name="userService" class="com.leo.crm.service.impl.UserServiceImpl">
<!-- 引用数据层注入数据层 -->
<property name="userDao" ref="userDao"></property>
</bean>
<!--创建操作数据层dao -->
<bean name="userDao" class="com.leo.crm.dao.impl.UserDaoImpl">
<!-- 注入sessionFactory -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- customer -->
<bean name="customerAction" class="com.leo.crm.web.action.CustomerAction" scope="prototype">
<property name="customerService" ref="customerService"></property>
</bean>
<!-- 创建对象CustomerService -->
<bean name="customerService" class="com.leo.crm.service.impl.CustomerServiceImpl">
<!-- 引用数据层注入数据层 -->
<property name="customerDao" ref="customerDao"></property>
</bean>
<!--创建操作数据层dao -->
<bean name="customerDao" class="com.leo.crm.dao.impl.CustomerDaoImpl">
<!-- 注入sessionFactory -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- baseDict -->
<bean name="baseDictAction" class="com.leo.crm.web.action.BaseDictAction" scope="prototype">
<property name="baseDictService" ref="baseDictService"></property>
</bean>
<!-- 创建对象C-->
<bean name="baseDictService" class="com.leo.crm.service.impl.BaseDictServiceImpl">
<!-- 引用数据层注入数据层 -->
<property name="baseDictDao" ref="baseDictDao"></property>
</bean>
<!--创建操作数据层dao -->
<bean name="baseDictDao" class="com.leo.crm.dao.impl.BaseDictDaoImpl">
<!-- 注入sessionFactory -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- linkman -->
<bean name="linkManAction" class="com.leo.crm.web.action.LinkManAction" scope="prototype">
<property name="linkManService" ref="linkManService"></property>
</bean>
<!-- 创建对象C-->
<bean name="linkManService" class="com.leo.crm.service.impl.LinkManServiceImpl">
<!-- 引用数据层注入数据层 -->
<property name="linkManDao" ref="linkManDao"></property>
</bean>
<!--创建操作数据层dao -->
<bean name="linkManDao" class="com.leo.crm.dao.impl.LinkManDaoImpl">
<!-- 注入sessionFactory -->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
hibernate映射文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.leo.crm.domain">
<class name="User" table="crm_user">
<id name="user_id" column="user_id">
<generator class="native"></generator>
</id>
<property name="user_code" column="user_code"></property>
<property name="user_name" column="user_name"></property>
<property name="user_password" column="user_password"></property>
<property name="user_state" column="user_state"></property>
</class>
</hibernate-mapping>
这时只需要在dao层进行继承HibernateDaoSupport就可以了,其他层不变:
比如一个抽取出来的操作数据的类:
/**
* 实现BaseDao接口
* @author leoi555
*
*/
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>{
private Class clazz;//接收运行期的泛型类型
public BaseDaoImpl() {
// TODO Auto-generated constructor stub
//获得当前类型的父类(父类中含有泛型)
ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
//获得运行期的泛型类型
//返回值为数组类型的,最后再取出
clazz = (Class) genericSuperclass.getActualTypeArguments()[0];
}
@Override
public void save(T t) {
// TODO Auto-generated method stub
getHibernateTemplate().save(t);
}
@Override
public void delete(T t) {
// TODO Auto-generated method stub
getHibernateTemplate().delete(t);
}
@Override
public void delete(Serializable id) {
// TODO Auto-generated method stub
//先取出这个
T byId = this.getById(id);
getHibernateTemplate().delete(byId);
}
@Override
public void update(T t) {
// TODO Auto-generated method stub
getHibernateTemplate().update(t);
}
@Override
public T getById(Serializable id) {
// TODO Auto-generated method stub
return (T) getHibernateTemplate().get(clazz, id);
}
@Override
public Integer getTotalCount(DetachedCriteria dc) {
// TODO Auto-generated method stub
//需要用聚合函数
dc.setProjection(Projections.rowCount());
List list = getHibernateTemplate().findByCriteria(dc);
//清空聚合函数
dc.setProjection(null);
if (list!=null && list.size()>0) {
Long count=(Long) list.get(0);
return count.intValue();//这是返回int性的
}else {
return null;
}
}
@Override
public List<T> getPageList(DetachedCriteria dc, Integer start, Integer pageSize) {
// TODO Auto-generated method stub
List<T> list=(List<T>) this.getHibernateTemplate().findByCriteria(dc, start, pageSize);
return list;
}
@Override
public void saveOrUpdate(T t) {
// TODO Auto-generated method stub
this.getHibernateTemplate().saveOrUpdate(t);
}
}
domain层中书写映射文件,书写pojo同时属性要和数据裤字段一致,web层就是写的action,这里的所有的属性都生成setget方法由spring容器进行管理然后进行实例化
/**
* 操作user的Action
* @author leoi555
*
*/
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
private Customer customer;
private CustomerService customerService;
private Integer currentPage;
private Integer pageSize;
//后台提供name与属性相同的就可以
private File photo;//接收文件
private String photoContentType;//file类型mime类型
private String photoFileName;//file 名称
public String getPhotoContentType() {
return photoContentType;
}
public void setPhotoContentType(String photoContentType) {
this.photoContentType = photoContentType;
}
public String getPhotoFileName() {
return photoFileName;
}
public void setPhotoFileName(String photoFileName) {
this.photoFileName = photoFileName;
}
public File getPhoto() {
return photo;
}
public void setPhoto(File photo) {
this.photo = photo;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public CustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
@Override
public Customer getModel() {
// TODO Auto-generated method stub
return customer;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
/**
* 获得列表
* @return
*/
public String list() {
//封装离线查询对象
DetachedCriteria dCriteria=DetachedCriteria.forClass(Customer.class);
if (org.apache.commons.lang3.StringUtils.isNotBlank(customer.getCust_name())) {
dCriteria.add(Restrictions.like("cust_name", "%"+customer.getCust_name()+"%"));
}
PageBean bean=customerService.getPageBean(dCriteria,currentPage,pageSize);
ActionContext.getContext().put("PageBean", bean);
return "list";
}
/**
* 保存客户
* @param customer
* @return
*/
public String saveCustomer(){
if (photo!=null) {
System.out.println("文件名称:"+photoFileName);
System.out.println("文件类型:"+photoContentType);
//将文件保存到指定的位置
photo.renameTo(new File("/upload/photo.jpg"));
}
customerService.addCustomer(customer);
return "toList";
}
/**
* 获取指定的用户
* @param id
* @return
*/
public String getCutomerById() {
Customer customer =customerService.getCustomerById(this.customer.getCust_id());
System.out.println(customer.getCust_id()+customer.getCust_linkman());
System.out.println(customer);
//将客户放到request域
ActionContext.getContext().put("customer", customer);
return "edit";
}
public String deleteCustomer() {
customerService.deleteCustomer(customer.getCust_id());
return "toList";
}
}
其他各层的逻辑该怎么写还是怎么写,其他各层不变