此例子来自于《轻量级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 {
//根据ID加载实体
T get(Class entityClazz, Serializable id);
//保存实体
Serializable save(T entity);
//更新实体
void update(T entity);
//删除
void delete(T entity);
//根据ID删除实体
void delete(Class entityClazz, Serializable id);
//获取所有实体
List findAll(Class entityClass);
//获取实体总数
long findCount(Class entityClazz);
}
BookDao接口
package com.dao;
import com.domain.Book;
public interface BookDao extends BaseDao {
//这里没有内容是因为不需要增加什么方法了
}
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 implements BaseDao {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@SuppressWarnings("unchecked")
@Override
public T get(Class 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 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 findAll(Class entityClass) {
// TODO Auto-generated method stub
String sql = "select en from " + entityClass.getSimpleName() + " en";
return find(sql);
}
@Override
public long findCount(Class 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 find(String hql) {
return getSessionFactory().
getCurrentSession().createQuery(hql).list();
}
/**
* 根据带占位符参数的HQL语句查询实体
* @param hql
* @param params
* @return
*/
@SuppressWarnings("unchecked")
protected List 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 findByPage(String hql, int pageNo, int pageSize) {
return getSessionFactory().getCurrentSession()
.createQuery(hql).setFirstResult((pageNo-1)*pageSize)
.setMaxResults(pageSize).list();
}
protected List 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 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文件夹下
success.jsp
error.jsp
{1}.jsp
web.xml,在WEB-INF文件夹下
TestSSH
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
/WEB-INF/applicationContext.xml
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
applicationContext.xml在WEB-INF文件夹下
com.domain.Book
org.hibernate.dialect.MySQL5InnoDBDialect
update
true
true
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
添加图书
之后还要写success.jsp和error.jsp,用来标明是否插入成功了
做好了之后的项目文件结构是这样的
值得注意的是struts.xml的class要用bean的id还有在web.xml中指定applicationContext.xml文件的路径才可以正确将action从struts中转到spring