SSH整合小例子

2016-07-05  本文已影响0人  Slience无言

此例子来自于《轻量级JavaEE企业应用开发》(李刚著)

本例子实现了Spring来整合Struts和Hibernate,这是一个添加书本功能的小示例
首先实体类Book

package com.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="my_books")
public class Book {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private Integer id;
    @Column(name="title")
    private String title;
    @Column(name="author")
    private String author;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}

基本DAO接口,如果还有其他的DAO可以实现这个接口

package com.dao;

import java.io.Serializable;
import java.util.List;

public interface BaseDao<T> {
    //根据ID加载实体
    T get(Class<T> entityClazz, Serializable id);
    //保存实体
    Serializable save(T entity);
    //更新实体
    void update(T entity);
    //删除
    void delete(T entity);
    //根据ID删除实体
    void delete(Class<T> entityClazz, Serializable id);
    //获取所有实体 
    List<T> findAll(Class<T> entityClass);
    //获取实体总数
    long findCount(Class<T> entityClazz);
}

BookDao接口

package com.dao;

import com.domain.Book;

public interface BookDao extends BaseDao<Book> {
    //这里没有内容是因为不需要增加什么方法了
}

Hbiernate4的基本Dao的实现类

package com.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.dao.BaseDao;

public class BaseDaoHibernate4<T> implements BaseDao<T> {
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

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

    @SuppressWarnings("unchecked")
    @Override
    public T get(Class<T> entityClazz, Serializable id) {
        // TODO Auto-generated method stub
        return (T)getSessionFactory().getCurrentSession().get(entityClazz, id);
    }

    @Override
    public Serializable save(T entity) {
        // TODO Auto-generated method stub
        return getSessionFactory().getCurrentSession().save(entity);
    }

    @Override
    public void update(T entity) {
        // TODO Auto-generated method stub
        getSessionFactory().getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(T entity) {
        // TODO Auto-generated method stub
        getSessionFactory().getCurrentSession().delete(entity);
        
    }

    @Override
    public void delete(Class<T> entityClazz, Serializable id) {
        // TODO Auto-generated method stub
        getSessionFactory().getCurrentSession().
            createQuery("delete " + entityClazz.getSimpleName() + 
            "en where en.id = ?0").setParameter("0", id).executeUpdate();
        
    }

    @Override
    public List<T> findAll(Class<T> entityClass) {
        // TODO Auto-generated method stub
        String sql = "select en from " + entityClass.getSimpleName() + " en";
        return find(sql);
    }

    @Override
    public long findCount(Class<T> entityClazz) {
        // TODO Auto-generated method stub
        List<?> list = find("select count(*) from " + entityClazz.getSimpleName());
        if(list != null && list.size() == 1) {
            return (long) list.get(0);
        }
        return 0;
    }
    @SuppressWarnings("unchecked")
    protected List<T> find(String hql) {
        return getSessionFactory().
                getCurrentSession().createQuery(hql).list();
    }
    /**
     * 根据带占位符参数的HQL语句查询实体
     * @param hql
     * @param params
     * @return
     */
    @SuppressWarnings("unchecked")
    protected List<T> find(String hql, Object... params) {
        Query query = getSessionFactory().
                getCurrentSession().createQuery(hql);
        for(int i = 0; i < params.length; i++) {
            query.setParameter(i + "", params[i]);
        }
        return query.list();
    }
    /**
     * 分页查询
     * @param hql
     * @param pageNo查询第几页的记录
     * @param pageSize一页多少行
     * @return
     */
    @SuppressWarnings("unchecked")
    protected List<T> findByPage(String hql, int pageNo, int pageSize) {
        return getSessionFactory().getCurrentSession()
                .createQuery(hql).setFirstResult((pageNo-1)*pageSize)
                .setMaxResults(pageSize).list();
    }
    
    protected List<T> findByPage(String hql, int pageNo, int pageSize, Object... params) {
        Query query = getSessionFactory().getCurrentSession()
                .createQuery(hql).setFirstResult((pageNo-1)*pageSize)
                .setMaxResults(pageSize);
        for(int i = 0; i < params.length; i++) {
            query.setParameter(i+"", params[i]);
        }
        return query.list();
    }
}

BookDao实现类

package com.dao.impl;

import com.dao.BookDao;
import com.domain.Book;

public class BookDaoHibernate4 extends BaseDaoHibernate4<Book> implements BookDao {
    //这里也没有内容是因为不需要添加什么方法
}

BookService接口

package com.service;

import com.domain.Book;

public interface BookService {
    //添加图书
    int addBook(Book book);
}

BookService实现类

package com.service.impl;

import com.dao.BookDao;
import com.domain.Book;
import com.service.BookService;

public class BookServiceImpl implements BookService {
    
    private BookDao bookDao;
    
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    @Override
    public int addBook(Book book) {
        // TODO Auto-generated method stub
        return (int) bookDao.save(book);
    }

}

Action类

package com.action;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.domain.Book;
import com.opensymphony.xwork2.ActionSupport;
import com.service.BookService;
import com.service.impl.BookServiceImpl;

public class BookAction extends ActionSupport {
    private BookService bookService;
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }
    private Book book;

    public Book getBook() {
        return book;
    }
    public void setBook(Book book) {
        this.book = book;
    }
    public String add() throws Exception {
        int result = bookService.addBook(book);
        if(result > 0) {
            addActionMessage("图书添加成功");
            return SUCCESS;
        }
        addActionMessage("图书添加失败");
        return ERROR;
    }
    @Override
    public String execute() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("默认的BookAction");
        return super.execute();
    }
    
}

struts.xml文件,在src文件夹下

<?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.devMode" value="true"/>
    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>
    <package name="default" namespace="/" extends="struts-default">
        <!-- 此处的class是指applicationContext.xml配置的bean的id -->
        <action name="createBook" class="bookAction" method="add">
            <result name="success">success.jsp</result>
            <result name="error">error.jsp</result>
        </action>
        <action name="*">
            <result>{1}.jsp</result>
        </action>
    </package>
</struts>

web.xml,在WEB-INF文件夹下

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>TestSSH</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 使用ContextLoaderListener让Web容器启动的时候自动装配ApplicationContext的配置信息 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 指定application.xml问文件路径 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <!-- 配置Struts -->
  <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>

applicationContext.xml在WEB-INF文件夹下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    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.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    
    <!-- 数据库相关配置 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close"
        p:driverClass="com.mysql.jdbc.Driver"
        p:user="root"
        p:password="abc123"
        p:jdbcUrl="jdbc:mysql://localhost/spring"
        p:maxPoolSize="40"
        p:minPoolSize="2"
        p:initialPoolSize="2"
        p:maxIdleTime="30"
    />
    
    <!-- 定义Hibernate的SessionFactory,将数据源dataSource注入 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource">
        <!-- 实体类列表 -->
        <property name="annotatedClasses">
            <list>
                <value>com.domain.Book</value>
            </list>
        </property>
        <!-- Hibernate相关参数 -->
        <property name="hibernateProperties">
            <props>
                <!-- 数据库方言 -->
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQL5InnoDBDialect
                </prop>
                <!-- 设置成update会更新原来的数据,还有一种是create,每次创建数据都会删除掉原来的数据 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!-- 显示SQL语句 -->
                <prop key="hibernate.show_sql">true</prop>
                <!-- 格式化SQL语句 -->
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>
    
    <!-- 配置一个bookService的bean,用来写对相关数据逻辑 -->
    <bean id="bookService" class="com.service.impl.BookServiceImpl" p:bookDao-ref="bookDao"/>
    <!-- 基本的数据库处理DAO类,提供CRUD等方法 -->
    <bean id="bookDao" class="com.dao.impl.BookDaoHibernate4" p:sessionFactory-ref="sessionFactory"/>
    <!-- 定义事物管理器,以便支持各种数据访问框架的事物管理,本例子中使用的是Hibernate -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory"/>
    <!-- 配置Action类,在struts.xml中可以使用这个bean的id来跳转到指定的class中 -->
    <!-- 因为Action里包含了请求的状态信息,必须为每一个请求对应Action -->
    <bean id="bookAction" class="com.action.BookAction" p:bookService-ref="bookService" scope="prototype"/>
    
    <!-- 配置事物增强管理器 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 所有以get开头的方设为只读 -->
            <tx:method name="get*" read-only="true"/>
            <!-- 所有方法事物隔离级别为默认,事物的传播行为为REQUIRED,超时时间为5秒 -->
            <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" timeout="5"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <!-- 注解使用bean(bookService)是指专门对bookService这个bean起作用 -->
        <!-- <aop:pointcut expression="bean(bookService)" id="myPointcut"/> -->
        <!-- 对所有类型的返回值,在com.service.impl包下的所有类的所有方法 -->
        <aop:pointcut expression="execution(* com.service.impl.*.*(..))" id="myPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/>
    </aop:config>
</beans>

index.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>添加图书</title>
</head>
<body>
<s:form action="createBook">
    <s:textfield name="book.title" label="书名"/>
    <s:textfield name="book.author" label="作者"/>
    <s:submit value="提交"/>
</s:form>
</body>
</html>

之后还要写success.jsp和error.jsp,用来标明是否插入成功了
做好了之后的项目文件结构是这样的

文件结构

值得注意的是struts.xml的class要用bean的id还有在web.xml中指定applicationContext.xml文件的路径才可以正确将action从struts中转到spring

上一篇下一篇

猜你喜欢

热点阅读