创建项目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">HelloWorldparam>
<param name="namespace">/exampleparam>
result>
action>
package>
struts>
"-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
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.jspwelcome-file>
welcome-file-list>
<filter>
<filter-name>struts2filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
filter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
listener-class>
listener>
web-app>
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">
org.apache.struts2.dispatcher.FilterDispatcher
org.springframework.web.context.ContextLoaderListener
到目前为止我们的整合工作已经完成。我们可以将该工程打包,以备下次直接使用。
这里有一个问题,就是如果采用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创建方式
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
length="20">
(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">
<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>
<property name="defaultAutoCommit"value="true">property>
bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"ref="dataSource">property>
<property name="hibernateProperties">
<props>
<prop key="connection.useUnicode">trueprop>
<prop key="connection.characterEncoding">utf-8prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
<prop key="hibernate.show_sql">trueprop>
props>
property>
<property name="mappingResources">
<list>
<value>test/s2sh/bean/Person.hbm.xmlvalue>
list>
property>
bean>
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">
乱码问题解决方案
1、
<property name="hibernateProperties">
<props>
<prop key="connection.useUnicode">trueprop>
<prop key="connection.characterEncoding">utf-8prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
<prop key="hibernate.show_sql">trueprop>
props>
property>
2、
<property name="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
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
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
String sql = " fromperson p order by p.id desc";
return (List
}
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
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
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
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 Persontitle>
<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" %>
操作成功页面
saveSuccess.jsp
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<title>Save OKtitle>
head>
<body>
保存成功!<br>
body>
html>
<%@page language="java" import="java.util.*"pageEncoding="utf-8"%>
保存成功
配置struts.xml
<action name="savePerson"class="savePersonAction">
<result>saveSuccess.jspresult>
<result name="input">save.jspresult>
action>
由于现在的action的创建已经由spring所接管,所以这里class里面使用的是别名,该别名与applicationContext.xml中的id对应.
配置applicationContext的ioc
<bean id="personDAO" class="com.s2sh.dao.impl.PersonDAOImpl"
scope="singleton">
<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>
这里说明一下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,始终带着这个错误,所以就提交不过去了。
到目前为止这个整合已经完成了。