struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
在src下新建struts.xml(也可以从
Struts2/apps/struts2-blank.war/WEB-INF/classes下拷贝)
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
在applicationContext.xml中引入aop、tx、context约束(具体可以从dist包中的xsd-config.html中进行拷贝)
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
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=off, stdout
在Servlet/Filter中获得Spring上下文对象
WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(servletContext);
Configurationconfiguration = new Configuration().configure();
SessionFactorysessionFactory= configuration.buildSessionFactory();
Sessionsession = sessionFactory.openSession()/ getCurrentSession();
Transactiontransaction = session.beginTransaction();
数据库操作
transaction.commit();
hibernate.cfg.xml的约束可以在
hibernate3.jar/org.hibernate/hibernate-configuration-3.0.dtd中找到复制拷贝即可
至于持久类映射文件的约束可以在
hibernate3.jar/org.hibernate/hibernate-mapping-3.0.dtd中找到复制到 *.hbm.xml中即可。
创建包结构
图书名称:
图书价格:
这种方式在Action中获取Service时只需要在Action中声明一Service变量 然后再提供一个Setter方法 并在applicationContext.xml中注册一下Service即可。然后由Struts2自己创建Action后就会自动按照名称为Action注入Service 如下所示在applicationContext.xml中需如下进行配置:
之所以Struts2会自动按照名称为Action注入名称对应的Service 是因为在struts2-spring-plugin-x.x.x.jar下有一配置文件: struts-plugin.xml 在此文件中开启了如下常量
引发了另一个常量的执行:(Spring的工厂类按照名称自动注入)struts.objectFactory.spring.autoWire = name
在applicationContext.xml中配置和伪类名相同的Bean
推荐使用第二种方式,在Spring中管理的类,可以对其进行AOP开发,统一的管理
注意:由Sping统一管理创建Action时 一定要声明为scope="prototype" 否则会有线程安全问题
2. Spring提供了Hibernate的模板,只需要将HibernateTemplate模板注入给DAO(前提是DAO继承自HibernateDaoSupport),注意:注入sessionFactory便可自动设置Hibernate模板
改写DAO,继承自HibernateDaoSupport
public class BookDao extends HibernateDaoSupport {
public void save(Book book) {
System.out.println("DAO层保存图书");
this.getHibernateTemplate().save(book);
}
}
3.创建一个持久化类的映射文件(Book.hbm.xml)
4.使用HibernateTransactionManager管理Spring事务
5.使用
项目名myspring_ssh1 具体代码如下:
package ssh1.test.vo;
public class Book {
private Integer id;
private String name;
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}
Book.hbm.xml
BookDao
package ssh1.test.dao;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import ssh1.test.vo.Book;
public class BookDao extends HibernateDaoSupport {
public void save(Book book) {
System.out.println("DAO层保存图书");
this.getHibernateTemplate().save(book);
}
}
BookService
package ssh1.test.service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ssh1.test.dao.BookDao;
import ssh1.test.vo.Book;
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
public class BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public void add(Book book) {
System.out.println("Service层保存图书......");
bookDao.save(book);
}
}
BookAction
package ssh1.test.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import ssh1.test.service.BookService;
import ssh1.test.vo.Book;
public class BookAction extends ActionSupport implements ModelDriven {
private BookService bookService;
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
// 模型驱动类
private Book book=new Book();
public Book getModel() {
return book;
}
// 请求处理的方法
public String add() {
System.out.println("web层的方法添加执行了......");
bookService.add(book);
return NONE;
}
}
struts.xml
hibernate.cfg.xml
com.mysql.jdbc.Driver
jdbc:mysql:///ssh1
root
root
org.hibernate.dialect.MySQLDialect
true
true
false
update
org.hibernate.connection.C3P0ConnectionProvider
5
20
120
3000
applicationContext.xml
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
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
addBook.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
Insert title here
添加图书
图书名称:
图书价格:
web.xml
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
index.jsp
运行结果如下
2.配置Hibernate常用属性以及持久化类映射文件
org.hibernate.dialect.MySQLDialect
true
true
update
false
none
classpath:ssh2/test/vo
HibernateTemplate的API
OpenSessionInViewFilter
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
OpenSessionInViewFilter
/*
新建项目myspring3_ssh2 项目结构如下:
package ssh2.test.vo;
public class Book {
private Integer id;
private String name;
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
Book.hbm.xml
from Book where name = ?
BookDao
package ssh2.test.dao;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import ssh2.test.vo.Book;
public class BookDao extends HibernateDaoSupport {
public void save(Book book) {
System.out.println("DAO层保存图书");
this.getHibernateTemplate().save(book);
}
public void update(Book book) {
this.getHibernateTemplate().update(book);
}
public void delete(Book book) {
this.getHibernateTemplate().delete(book);
}
public Book findById(Integer id) {
return this.getHibernateTemplate().get(Book.class, id);
}
public List findAll() {
return this.getHibernateTemplate().find("from Book");
}
public List findByCriteria(DetachedCriteria criteria) {
return this.getHibernateTemplate().findByCriteria(criteria);
}
public List findByName(String name) {
return this.getHibernateTemplate().findByNamedQuery("findByName", name);
}
public Book findByIdLazy(Integer id) {
return this.getHibernateTemplate().load(Book.class, id);
}
}
BookService
package ssh2.test.service;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ssh2.test.dao.BookDao;
import ssh2.test.vo.Book;
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
public class BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public void add(Book book) {
System.out.println("Service层保存图书......");
bookDao.save(book);
}
public void update(Book book) {
bookDao.update(book);
}
public void delete(Book book) {
bookDao.delete(book);
}
public Book findById(Integer id) {
return bookDao.findById(id);
}
public List findAll() {
return bookDao.findAll();
}
public List findByCriteria(DetachedCriteria criteria) {
return bookDao.findByCriteria(criteria);
}
public List findByName(String name) {
return bookDao.findByName(name);
}
public Book findByIdLazy(Integer id) {
return bookDao.findByIdLazy(id);
}
}
BookAction
package ssh2.test.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import ssh2.test.service.BookService;
import ssh2.test.vo.Book;
public class BookAction extends ActionSupport implements ModelDriven {
private BookService bookService;
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
// 模型驱动类
private Book book=new Book();
public Book getModel() {
return book;
}
// 请求处理的方法
public String add() {
System.out.println("web层的方法添加执行了......");
bookService.add(book);
return NONE;
}
}
SSHTest
package ssh2.test.junitDemo;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import ssh2.test.service.BookService;
import ssh2.test.vo.Book;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SSHTest {
@Autowired
@Qualifier("bookService")
private BookService bookService;
@Test
public void demo1() {
Book book = new Book();
book.setId(1);
book.setName("Java从入门到精通");
book.setPrice(98d);
bookService.update(book);
}
@Test
public void demo2() {
Book book = new Book();
book.setId(1);
bookService.delete(book);
}
@Test
public void demo3() {
Book book = bookService.findById(2);
System.out.println(book);
}
@Test
public void demo4() {
List books = bookService.findAll();
for (Book book : books) {
System.out.println(book);
}
}
@Test
public void demo5() {
DetachedCriteria criteria = DetachedCriteria.forClass(Book.class);
criteria.add(Restrictions.eq("name", "Struts2开发入门"));
List books = bookService.findByCriteria(criteria);
for (Book book : books) {
System.out.println(book);
}
}
@Test
public void demo6() {
List books = bookService.findByName("SSH整合2");
for (Book book : books) {
System.out.println(book);
}
}
}
struts.xml
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
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
jdbc.proeprties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssh2
jdbc.user=root
jdbc.password=root
applicationContext.xml
org.hibernate.dialect.MySQLDialect
true
true
update
false
none
classpath:ssh2/test/vo
web.xml
OpenSessionInViewFilter
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
OpenSessionInViewFilter
/*
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
index.jsp
addBook.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
Insert title here
添加图书
图书名称:
图书价格:
部署项目后访问如下
2.配置连接池
3.使用AnnotationSessionFactoryBean配置Hibernate属性与映射扫描
org.hibernate.dialect.MySQLDialect
true
true
update
false
none
ssh3.test.vo
4.最后配置Hibernate模板与事务管理
新建项目myspring3_ssh3
package ssh3.test.vo;
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 = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "name")
private String name;
// 注意: 实体类中的属性即使不使用注解,默认也会自动生成和属性名相同的字段
private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
BookDao
package ssh3.test.dao;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import ssh3.test.vo.Book;
@Repository("bookDao")
public class BookDao {
@Autowired
@Qualifier("hibernateTemplate")
HibernateTemplate hibernateTemplate;
public void save(Book book) {
System.out.println("DAO层保存图书");
hibernateTemplate.save(book);
}
}
BookService
package ssh3.test.service;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ssh3.test.dao.BookDao;
import ssh3.test.vo.Book;
@Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, readOnly = false)
@Service("bookService")
public class BookService {
@Autowired
@Qualifier("bookDao")
private BookDao bookDao;
public void add(Book book) {
System.out.println("Service层保存图书......");
bookDao.save(book);
}
}
BookAction
package ssh3.test.action;
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.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import ssh3.test.service.BookService;
import ssh3.test.vo.Book;
//
@Namespace("/")
@ParentPackage("struts-default")
@Controller("bookAction")
@Scope("prototype")
public class BookAction extends ActionSupport implements ModelDriven {
// 模型驱动类
private Book book = new Book();
public Book getModel() {
return book;
}
// 在Action中注入Service
@Autowired
@Qualifier("bookService")
private BookService bookService;
// 请求处理的方法
@Action(value = "book_add")
public String add() {
System.out.println("web层的方法添加执行了......");
bookService.add(book);
return NONE;
}
}
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssh3
jdbc.user=root
jdbc.password=root
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
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
applicationContext.xml
org.hibernate.dialect.MySQLDialect
true
true
update
false
none
ssh3.test.vo
web.xml
OpenSessionInViewFilter
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
OpenSessionInViewFilter
/*
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
index.jsp
addBook.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
Insert title here
添加图书
图书名称:
图书价格:
运行测试 成功