创建项目s2sh 添加Hibernate 3.2默认就可以,不要忘记将jar包加入到/WebRoot/WEB-INF/lib接着next 实际上这里的hibernate.cfg.xml不起作用,因为该配置文件的内容由后面的...
创建项目s2sh
添加Hibernate 3.2
默认就可以,不要忘记将jar包加入到/WebRoot/WEB-INF/lib
接着next
实际上这里的hibernate.cfg.xml不起作用,因为该配置文件的内容由后面的spring配置文件进行管理,我们可以在创建之后将其删除
默认next
我们根本不用hibernate.cfg.xml,所以这里根本不需要进行数据库配置,当然默认也无所谓。
继续next
sessionFactory我们在之后也会直接使用spring为我们提供的,所以这里不需要创建。
finish
添加Spring2.0
不要忘记选中这5个库包:
Spring 2.0 AOP Libraries
Spring 2.0 Core Libraries
Spring 2.0 Persistence Core Libraries
Spring 2.0 Persistence JDBC Libraries
Spring 2.0 Web Libraries
也不要忘记将jar包加入到/WebRoot/WEB-INF/lib。
next
这里我们不需要Enable AOP 所以不需要选中
不要忘记将配置文件applicationContext.xml指定在/WEB-INF目录下,不然服务器启动时无法加载
next
这里的sessionFactory我们也不需要,之后会手动配置。
finish
添加Struts2
由于MyEclipse并没有加入Struts2的支持,所以我们需要手动导入相关jar包。
需要的相关jar包如下:
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.11.jar
xwork-2.0.4.jar
struts2-spring-plugin-2.0.11.jar
struts.xml
在src下加入struts的配置文件struts.xml
<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE strutsPUBLIC
"-//ApacheSoftware Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation"value="false" />
<constant name="struts.devMode"value="false" />
<include file="example.xml"/>
<package name="default"namespace="/" extends="struts-default">
<default-action-ref name="index"/>
<action name="index">
<result type="redirectAction">
<param name="actionName">HelloWorld</param>
<param name="namespace">/example</param>
</result>
</action>
</package>
</struts>
<?xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPEstruts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="s2sh"extends="struts-default">
</package>
</struts>
web.xml
<?xml version="1.0"encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置struts2的过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置spring的监听器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app><?xml version="1.0"encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置struts2的过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置spring的监听器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
到目前为止我们的整合工作已经完成。我们可以将该工程打包,以备下次直接使用。
这里有一个问题,就是如果采用myeclipse加载hibernate和spring的lib包形式发布项目的时候会出现异常,我们可以手动去掉一个asm-2.2.3jar即可。
测试
sql
(1)使用mysql,记得将mysql-jdbc的jar包导入到工程中
创建s2sh数据库,并创建表person
CREATE TABLE `person` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
--Table "person" DDL
CREATETABLE `person` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
(2)创建com.s2sh.bean包,创建person表对应的Entity Bean及其映射文件
Person.java
package com.s2sh.bean;
publicclass person {
private Integer id;
private String name;
privateintage;
public Integer getId() {
returnid;
}
publicvoid setId(Integer id) {
this.id = id;
}
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age = age;
}
}
packagetest.s2sh.bean;
publicclass Person {
private Integer id;
private String name;
private int age;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Person.hbm.xml
<?xml version="1.0"encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.s2sh.bean.Person" table="person">
<id name="id"type="java.lang.Integer" column="id">
<generator class="increment"></generator>
</id>
<property name="name"type="string" column="name"
length="20"></property>
<property name="age"type="java.lang.Integer" column="age"></property>
</class>
</hibernate-mapping>
sessionFactory创建方式 <?xml version="1.0"encoding="utf-8"?>
<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="test.s2sh.bean.Person" table="person">
<id name="id"type="java.lang.Integer" column="id">
<generatorclass="increment"></generator>
</id>
<property name="name"type="string" column="name"
length="20"></property>
<property name="age"type="java.lang.Integer" column="age"></property>
</class>
</hibernate-mapping>
(3)在spring配置文件applicationContext.xml配置hibernate的连接数据库信息及sessionFactory创建方式
<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!-- apache.dbcp连接池的配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/s2sh?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username"value="root"></property>
<property name="password"value="1234"></property>
<!-- 最大活动连接数 -->
<property name="maxActive"value="100"></property>
<!-- 最大可空闲连接数 -->
<property name="maxIdle"value="30"></property>
<!-- 最大可等待连接数 -->
<property name="maxWait"value="500"></property>
<!-- 默认的提交方式(如果不需要事务可以设置成true,在实际应用中一般设置为false,默认为false) -->
<property name="defaultAutoCommit"value="true"></property>
</bean>
<!-- 这里直接使用spring对hibernate3支持的sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"ref="dataSource"></property>
<!-- hibernate方言等相关配置 -->
<property name="hibernateProperties">
<props>
<prop key="connection.useUnicode">true</prop>
<prop key="connection.characterEncoding">utf-8</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<!-- hbm.xml的映射文件 -->
<property name="mappingResources">
<list>
<value>test/s2sh/bean/Person.hbm.xml</value>
</list>
</property>
</bean>
</beans>
<?xmlversion="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!--apache.dbcp连接池的配置 -->
<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
<property name="driverClassName"value="com.mysql.jdbc.Driver"></property>
<property name="url"value="jdbc:mysql://localhost:3306/s2sh?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username"value="root"></property>
<property name="password"value=""></property>
<!-- 最大活动连接数-->
<property name="maxActive"value="100"></property>
<!-- 最大可空闲连接数-->
<property name="maxIdle"value="30"></property>
<!-- 最大可等待连接数-->
<property name="maxWait"value="500"></property>
<!-- 默认的提交方式(如果不需要事务可以设置成true,在实际应用中一般设置为false,默认为false) -->
<property name="defaultAutoCommit"value="true"></property>
</bean>
<!--这里直接使用spring对hibernate3支持的sessionFactory -->
<beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"ref="dataSource"></property>
<!-- hibernate方言等相关配置 -->
<propertyname="hibernateProperties">
<props>
<propkey="connection.useUnicode">true</prop>
<propkey="connection.characterEncoding">utf-8</prop>
<propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<propkey="hibernate.show_sql">true</prop>
</props>
</property>
<!-- hbm.xml的映射文件 -->
<propertyname="mappingResources">
<list>
<value>test/s2sh/bean/Person.hbm.xml</value>
</list>
</property>
</bean>
</beans>
乱码问题解决方案
1、
<property name="hibernateProperties">
<props>
<prop key="connection.useUnicode">true</prop>
<prop key="connection.characterEncoding">utf-8</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<propertyname="hibernateProperties">
<props>
<propkey="connection.useUnicode">true</prop>
<propkey="connection.characterEncoding">utf-8</prop>
<propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<propkey="hibernate.show_sql">true</prop>
</props>
</property>
2、
<property name="url" value="jdbc:mysql://localhost:3306/s2sh?
useUnicode=true&characterEncoding=UTF-8"></property><propertyname="url"value="jdbc:mysql://localhost:3306/s2sh?useUnicode=true&characterEncoding=UTF-8"></property>
(4)下面我们开始写DAO层,首先创建com.s2sh.dao包放置Dao类的接口,创建com.s2sh.dao.impl包放置Dao类的实现。
PersonDAO.java
package com.s2sh.dao;
import java.util.List;
import com.s2sh.bean.Person;
publicinterface PersonDAO {
void savePerson(Person p);
void removePerson(Person p);
Person findPersonById(Integer id);
List<Person> findAllPerson();
void updatePerson(Person p);
}
packagetest.s2sh.dao;
importjava.util.List;
importtest.s2sh.bean.Person;
publicinterface PersonDAO {
void savePerson(Person p);
void removePerson(Person p);
Person findPersonById(Integer id);
List<Person> findAllPersons();
void updatePerson(Person p);
}
由于使用了spring,所以DAO的实现类可以继承HibernateDaoSupport进行实现
PersonDAOImpl.java
package com.s2sh.dao.impl;
import java.util.List;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.s2sh.bean.Person;
import com.s2sh.dao.PersonDAO;
publicclass PersonDAOImpl extends HibernateDaoSupport implements PersonDAO {
public List<Person> findAllPerson() {
String sql = " fromperson p order by p.id desc";
return (List<Person>)this.getHibernateTemplate().find(sql);
}
public Person findPersonById(Integer id) {
Person p = (Person) this.getHibernateTemplate().get(Person.class, id);
return p;
}
publicvoid removePerson(Person p) {
this.getHibernateTemplate().delete(p);
}
publicvoid savePerson(Person p) {
this.getHibernateTemplate().save(p);
}
publicvoid updatePerson(Person p) {
this.getHibernateTemplate().update(p);
}
}
(5)下面开始进行service层的设计,这里的service层仅是简单调用DAO层的的方法。
同样是创建接口包(com.s2sh.service),实现包和接口类(com.s2sh.service.impl),实现类
PersonService.java
package com.s2sh.service;
import java.util.List;
import com.s2sh.bean.Person;
publicinterface PersonService {
List<Person> findAll();
void save(Person p);
void delete(Person p);
Person findById(Integer id);
void update(Person p);
}
packagetest.s2sh.service;
importjava.util.List;
importtest.s2sh.bean.Person;
publicinterface PersonService {
List<Person> findAll();
void save(Person p);
void delete(Person p);
Person findById(Integer id);
void update(Person p);
}
这里需要使用spring的ioc将DAO诸如到service中,所以要在service实现类中加入DAO作为属性。
PersonServiceImpl.java
package com.s2sh.service.impl;
import java.util.List;
import com.s2sh.bean.Person;
import com.s2sh.dao.PersonDAO;
import com.s2sh.service.PersonService;
publicclass PersonServiceImpl implements PersonService {
private PersonDAO personDao;
publicvoid delete(Person p) {
personDao.removePerson(p);
}
public List<Person> findAll() {
returnpersonDao.findAllPerson();
}
public Person findById(Integer id) {
returnpersonDao.findPersonById(id);
}
publicvoid save(Person p) {
personDao.savePerson(p);
}
publicvoid update(Person p) {
personDao.updatePerson(p);
}
public PersonDAO getPersonDao() {
returnpersonDao;
}
publicvoid setPersonDao(PersonDAO personDao) {
this.personDao = personDao;
}
}
(6)接下来开始对action层进行设置,实际项目中的action可能会有很多,所以需要对action进行分包,这里针对Person进行操作,创建com.s2sh.action.person.
这里先做保存操作
savePersonAction.java
package com.s2sh.action.person;
import com.opensymphony.xwork2.ActionSupport;
import com.s2sh.bean.Person;
import com.s2sh.service.PersonService;
publicclass savePersonAction extends ActionSupport {
private Person p;
private PersonService personService;
public Person getP() {
returnp;
}
publicvoid setP(Person p) {
this.p = p;
}
public PersonService getPersonService() {
returnpersonService;
}
publicvoid setPersonService(PersonService personService) {
this.personService =personService;
}
public String execute() throws Exception{
personService.save(p);
returnSUCCESS;
}
publicvoid validate(){
if(p.getName()==null || "".equals(p.getName())){
this.addFieldError("p.name", "name is notnull!");
}
}
}
save.jsp
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<%
String path =request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s"uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Save Person</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<s:form action="savePerson">
<s:textfield name="p.name" label="name"></s:textfield>
<s:textfield name="p.age" label="age"></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>
<%@page language="java" import="java.util.*"pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Save Person</title>
</head>
<body>
<s:formaction="savePerson">
<s:textfieldname="p.name" label="name"></s:textfield>
<s:textfieldname="p.age" label="age"></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>
操作成功页面
saveSuccess.jsp
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<title>Save OK</title>
</head>
<body>
保存成功!<br>
</body>
</html>
<%@page language="java" import="java.util.*"pageEncoding="utf-8"%>
<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Save OK</title>
</head>
<body>
保存成功<br>
</body>
</html>
配置struts.xml
<action name="savePerson"class="savePersonAction">
<result>saveSuccess.jsp</result>
<result name="input">save.jsp</result>
</action>
<actionname="savePerson" class="savePersonAction">
<result name="success"type="redirect">/save-success.jsp</result>
<resultname="input">/save.jsp</result>
</action>
由于现在的action的创建已经由spring所接管,所以这里class里面使用的是别名,该别名与applicationContext.xml中的id对应.
配置applicationContext的ioc
<bean id="personDAO" class="com.s2sh.dao.impl.PersonDAOImpl"
scope="singleton">
<!-- 由于该类是继承于HibernateDaoSupport,所以需要将sessionFactory注入 -->
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="personService" class="com.s2sh.service.impl.PersonServiceImpl">
<property name="personDao"ref="personDAO"></property>
</bean>
<bean id="savePersonAction" class="com.s2sh.action.person.savePersonAction"
scope="prototype">
<property name="personService"ref="personService"></property>
</bean>
<beanid="personDAO" class="test.s2sh.dao.impl.PersonDAOImpl"scope="singleton">
<!-- 由于该类是继承于HibernateDaoSupport,所以需要将sessionFactory注入 -->
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<beanid="personService" class="test.s2sh.service.impl.PersonServiceImpl">
<property name="personDAO"ref="personDAO"></property>
</bean>
<beanid="savePersonAction"class="test.s2sh.action.person.SavePersonAction"scope="prototype">
<property name="service"ref="personService"></property>
</bean>
这里说明一下spring中的单例与设计模式中的单例不同,设计模式的单例是在jvm中只产生一个实例,而spring中的单例
是针对每个ioc容器来言,如果存在两个ioc容器,那么每个ioc容器都会生成唯一的类实例
将sessionFactory注入Dao中,这里的Dao来说是无状态的,可以设置为单例singleton。这里的action是使用spring创建的。
struts2与struts1的action有所不同,因为struts2中的action中可能存在属性,这里是Person,所以struts2的action可能是有状态的。
如果是有状态的我们就需要将scope设置成原型模式,即每次请求都新建一个action。
不然可能会出现如果表单提交的第一次出错,之后就再也提交不过去了,值就是应为使用默认的singleton,
当第一次的时候就将FieldError中加入了错误,每次都是这个action,始终带着这个错误,所以就提交不过去了。
到目前为止这个整合已经完成了。
创建项目s2sh
添加Hibernate 3.2
默认就可以,不要忘记将jar包加入到/WebRoot/WEB-INF/lib
接着next
实际上这里的hibernate.cfg.xml不起作用,因为该配置文件的内容由后面的spring配置文件进行管理,我们可以在创建之后将其删除
默认next
我们根本不用hibernate.cfg.xml,所以这里根本不需要进行数据库配置,当然默认也无所谓。
继续next
sessionFactory我们在之后也会直接使用spring为我们提供的,所以这里不需要创建。
finish
添加Spring2.0
不要忘记选中这5个库包:
Spring 2.0 AOP Libraries
Spring 2.0 Core Libraries
Spring 2.0 Persistence Core Libraries
Spring 2.0 Persistence JDBC Libraries
Spring 2.0 Web Libraries
也不要忘记将jar包加入到/WebRoot/WEB-INF/lib。
next
这里我们不需要Enable AOP 所以不需要选中
不要忘记将配置文件applicationContext.xml指定在/WEB-INF目录下,不然服务器启动时无法加载
next
这里的sessionFactory我们也不需要,之后会手动配置。
finish
添加Struts2
由于MyEclipse并没有加入Struts2的支持,所以我们需要手动导入相关jar包。
需要的相关jar包如下:
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.11.jar
xwork-2.0.4.jar
struts2-spring-plugin-2.0.11.jar
struts.xml
在src下加入struts的配置文件struts.xml
<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE strutsPUBLIC
"-//ApacheSoftware Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation"value="false" />
<constant name="struts.devMode"value="false" />
<include file="example.xml"/>
<package name="default"namespace="/" extends="struts-default">
<default-action-ref name="index"/>
<action name="index">
<result type="redirectAction">
<param name="actionName">HelloWorld</param>
<param name="namespace">/example</param>
</result>
</action>
</package>
</struts>
<?xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPEstruts PUBLIC
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="s2sh"extends="struts-default">
</package>
</struts>
web.xml
<?xml version="1.0"encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置struts2的过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置spring的监听器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app><?xml version="1.0"encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 配置struts2的过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置spring的监听器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
到目前为止我们的整合工作已经完成。我们可以将该工程打包,以备下次直接使用。
这里有一个问题,就是如果采用myeclipse加载hibernate和spring的lib包形式发布项目的时候会出现异常,我们可以手动去掉一个asm-2.2.3jar即可。
测试
sql
(1)使用mysql,记得将mysql-jdbc的jar包导入到工程中
创建s2sh数据库,并创建表person
CREATE TABLE `person` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
--Table "person" DDL
CREATETABLE `person` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
(2)创建com.s2sh.bean包,创建person表对应的Entity Bean及其映射文件
Person.java
package com.s2sh.bean;
publicclass person {
private Integer id;
private String name;
privateintage;
public Integer getId() {
returnid;
}
publicvoid setId(Integer id) {
this.id = id;
}
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
publicint getAge() {
returnage;
}
publicvoid setAge(int age) {
this.age = age;
}
}
packagetest.s2sh.bean;
publicclass Person {
private Integer id;
private String name;
private int age;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Person.hbm.xml
<?xml version="1.0"encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.s2sh.bean.Person" table="person">
<id name="id"type="java.lang.Integer" column="id">
<generator class="increment"></generator>
</id>
<property name="name"type="string" column="name"
length="20"></property>
<property name="age"type="java.lang.Integer" column="age"></property>
</class>
</hibernate-mapping>
sessionFactory创建方式 <?xml version="1.0"encoding="utf-8"?>
<!DOCTYPEhibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="test.s2sh.bean.Person" table="person">
<id name="id"type="java.lang.Integer" column="id">
<generatorclass="increment"></generator>
</id>
<property name="name"type="string" column="name"
length="20"></property>
<property name="age"type="java.lang.Integer" column="age"></property>
</class>
</hibernate-mapping>
(3)在spring配置文件applicationContext.xml配置hibernate的连接数据库信息及sessionFactory创建方式
<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!-- apache.dbcp连接池的配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/s2sh?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username"value="root"></property>
<property name="password"value="1234"></property>
<!-- 最大活动连接数 -->
<property name="maxActive"value="100"></property>
<!-- 最大可空闲连接数 -->
<property name="maxIdle"value="30"></property>
<!-- 最大可等待连接数 -->
<property name="maxWait"value="500"></property>
<!-- 默认的提交方式(如果不需要事务可以设置成true,在实际应用中一般设置为false,默认为false) -->
<property name="defaultAutoCommit"value="true"></property>
</bean>
<!-- 这里直接使用spring对hibernate3支持的sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"ref="dataSource"></property>
<!-- hibernate方言等相关配置 -->
<property name="hibernateProperties">
<props>
<prop key="connection.useUnicode">true</prop>
<prop key="connection.characterEncoding">utf-8</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<!-- hbm.xml的映射文件 -->
<property name="mappingResources">
<list>
<value>test/s2sh/bean/Person.hbm.xml</value>
</list>
</property>
</bean>
</beans>
<?xmlversion="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!--apache.dbcp连接池的配置 -->
<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
<property name="driverClassName"value="com.mysql.jdbc.Driver"></property>
<property name="url"value="jdbc:mysql://localhost:3306/s2sh?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username"value="root"></property>
<property name="password"value=""></property>
<!-- 最大活动连接数-->
<property name="maxActive"value="100"></property>
<!-- 最大可空闲连接数-->
<property name="maxIdle"value="30"></property>
<!-- 最大可等待连接数-->
<property name="maxWait"value="500"></property>
<!-- 默认的提交方式(如果不需要事务可以设置成true,在实际应用中一般设置为false,默认为false) -->
<property name="defaultAutoCommit"value="true"></property>
</bean>
<!--这里直接使用spring对hibernate3支持的sessionFactory -->
<beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"ref="dataSource"></property>
<!-- hibernate方言等相关配置 -->
<propertyname="hibernateProperties">
<props>
<propkey="connection.useUnicode">true</prop>
<propkey="connection.characterEncoding">utf-8</prop>
<propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<propkey="hibernate.show_sql">true</prop>
</props>
</property>
<!-- hbm.xml的映射文件 -->
<propertyname="mappingResources">
<list>
<value>test/s2sh/bean/Person.hbm.xml</value>
</list>
</property>
</bean>
</beans>
乱码问题解决方案
1、
<property name="hibernateProperties">
<props>
<prop key="connection.useUnicode">true</prop>
<prop key="connection.characterEncoding">utf-8</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<propertyname="hibernateProperties">
<props>
<propkey="connection.useUnicode">true</prop>
<propkey="connection.characterEncoding">utf-8</prop>
<propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<propkey="hibernate.show_sql">true</prop>
</props>
</property>
2、
<property name="url" value="jdbc:mysql://localhost:3306/s2sh?
useUnicode=true&characterEncoding=UTF-8"></property><propertyname="url"value="jdbc:mysql://localhost:3306/s2sh?useUnicode=true&characterEncoding=UTF-8"></property>
(4)下面我们开始写DAO层,首先创建com.s2sh.dao包放置Dao类的接口,创建com.s2sh.dao.impl包放置Dao类的实现。
PersonDAO.java
package com.s2sh.dao;
import java.util.List;
import com.s2sh.bean.Person;
publicinterface PersonDAO {
void savePerson(Person p);
void removePerson(Person p);
Person findPersonById(Integer id);
List<Person> findAllPerson();
void updatePerson(Person p);
}
packagetest.s2sh.dao;
importjava.util.List;
importtest.s2sh.bean.Person;
publicinterface PersonDAO {
void savePerson(Person p);
void removePerson(Person p);
Person findPersonById(Integer id);
List<Person> findAllPersons();
void updatePerson(Person p);
}
由于使用了spring,所以DAO的实现类可以继承HibernateDaoSupport进行实现
PersonDAOImpl.java
package com.s2sh.dao.impl;
import java.util.List;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.s2sh.bean.Person;
import com.s2sh.dao.PersonDAO;
publicclass PersonDAOImpl extends HibernateDaoSupport implements PersonDAO {
public List<Person> findAllPerson() {
String sql = " fromperson p order by p.id desc";
return (List<Person>)this.getHibernateTemplate().find(sql);
}
public Person findPersonById(Integer id) {
Person p = (Person) this.getHibernateTemplate().get(Person.class, id);
return p;
}
publicvoid removePerson(Person p) {
this.getHibernateTemplate().delete(p);
}
publicvoid savePerson(Person p) {
this.getHibernateTemplate().save(p);
}
publicvoid updatePerson(Person p) {
this.getHibernateTemplate().update(p);
}
}
(5)下面开始进行service层的设计,这里的service层仅是简单调用DAO层的的方法。
同样是创建接口包(com.s2sh.service),实现包和接口类(com.s2sh.service.impl),实现类
PersonService.java
package com.s2sh.service;
import java.util.List;
import com.s2sh.bean.Person;
publicinterface PersonService {
List<Person> findAll();
void save(Person p);
void delete(Person p);
Person findById(Integer id);
void update(Person p);
}
packagetest.s2sh.service;
importjava.util.List;
importtest.s2sh.bean.Person;
publicinterface PersonService {
List<Person> findAll();
void save(Person p);
void delete(Person p);
Person findById(Integer id);
void update(Person p);
}
这里需要使用spring的ioc将DAO诸如到service中,所以要在service实现类中加入DAO作为属性。
PersonServiceImpl.java
package com.s2sh.service.impl;
import java.util.List;
import com.s2sh.bean.Person;
import com.s2sh.dao.PersonDAO;
import com.s2sh.service.PersonService;
publicclass PersonServiceImpl implements PersonService {
private PersonDAO personDao;
publicvoid delete(Person p) {
personDao.removePerson(p);
}
public List<Person> findAll() {
returnpersonDao.findAllPerson();
}
public Person findById(Integer id) {
returnpersonDao.findPersonById(id);
}
publicvoid save(Person p) {
personDao.savePerson(p);
}
publicvoid update(Person p) {
personDao.updatePerson(p);
}
public PersonDAO getPersonDao() {
returnpersonDao;
}
publicvoid setPersonDao(PersonDAO personDao) {
this.personDao = personDao;
}
}
(6)接下来开始对action层进行设置,实际项目中的action可能会有很多,所以需要对action进行分包,这里针对Person进行操作,创建com.s2sh.action.person.
这里先做保存操作
savePersonAction.java
package com.s2sh.action.person;
import com.opensymphony.xwork2.ActionSupport;
import com.s2sh.bean.Person;
import com.s2sh.service.PersonService;
publicclass savePersonAction extends ActionSupport {
private Person p;
private PersonService personService;
public Person getP() {
returnp;
}
publicvoid setP(Person p) {
this.p = p;
}
public PersonService getPersonService() {
returnpersonService;
}
publicvoid setPersonService(PersonService personService) {
this.personService =personService;
}
public String execute() throws Exception{
personService.save(p);
returnSUCCESS;
}
publicvoid validate(){
if(p.getName()==null || "".equals(p.getName())){
this.addFieldError("p.name", "name is notnull!");
}
}
}
save.jsp
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<%
String path =request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s"uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Save Person</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<s:form action="savePerson">
<s:textfield name="p.name" label="name"></s:textfield>
<s:textfield name="p.age" label="age"></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>
<%@page language="java" import="java.util.*"pageEncoding="utf-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Save Person</title>
</head>
<body>
<s:formaction="savePerson">
<s:textfieldname="p.name" label="name"></s:textfield>
<s:textfieldname="p.age" label="age"></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>
操作成功页面
saveSuccess.jsp
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<title>Save OK</title>
</head>
<body>
保存成功!<br>
</body>
</html>
<%@page language="java" import="java.util.*"pageEncoding="utf-8"%>
<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Save OK</title>
</head>
<body>
保存成功<br>
</body>
</html>
配置struts.xml
<action name="savePerson"class="savePersonAction">
<result>saveSuccess.jsp</result>
<result name="input">save.jsp</result>
</action>
<actionname="savePerson" class="savePersonAction">
<result name="success"type="redirect">/save-success.jsp</result>
<resultname="input">/save.jsp</result>
</action>
由于现在的action的创建已经由spring所接管,所以这里class里面使用的是别名,该别名与applicationContext.xml中的id对应.
配置applicationContext的ioc
<bean id="personDAO" class="com.s2sh.dao.impl.PersonDAOImpl"
scope="singleton">
<!-- 由于该类是继承于HibernateDaoSupport,所以需要将sessionFactory注入 -->
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="personService" class="com.s2sh.service.impl.PersonServiceImpl">
<property name="personDao"ref="personDAO"></property>
</bean>
<bean id="savePersonAction" class="com.s2sh.action.person.savePersonAction"
scope="prototype">
<property name="personService"ref="personService"></property>
</bean>
<beanid="personDAO" class="test.s2sh.dao.impl.PersonDAOImpl"scope="singleton">
<!-- 由于该类是继承于HibernateDaoSupport,所以需要将sessionFactory注入 -->
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<beanid="personService" class="test.s2sh.service.impl.PersonServiceImpl">
<property name="personDAO"ref="personDAO"></property>
</bean>
<beanid="savePersonAction"class="test.s2sh.action.person.SavePersonAction"scope="prototype">
<property name="service"ref="personService"></property>
</bean>
这里说明一下spring中的单例与设计模式中的单例不同,设计模式的单例是在jvm中只产生一个实例,而spring中的单例
是针对每个ioc容器来言,如果存在两个ioc容器,那么每个ioc容器都会生成唯一的类实例
将sessionFactory注入Dao中,这里的Dao来说是无状态的,可以设置为单例singleton。这里的action是使用spring创建的。
struts2与struts1的action有所不同,因为struts2中的action中可能存在属性,这里是Person,所以struts2的action可能是有状态的。
如果是有状态的我们就需要将scope设置成原型模式,即每次请求都新建一个action。
不然可能会出现如果表单提交的第一次出错,之后就再也提交不过去了,值就是应为使用默认的singleton,
当第一次的时候就将FieldError中加入了错误,每次都是这个action,始终带着这个错误,所以就提交不过去了。
到目前为止这个整合已经完成了。