学习SSH框架 博客分类: java SSH框架java
1.SSH框架的认知
在做相关的java的网页的开发制作时,良好的层次分解是十分有比要的,所以我们在云涌第三方的框架之下来简化还有名了我们相关的网站的开发。
SSH框架实则为Struct + spring + hibernate 的三个组成的,其中struct,专注与前台的相关的请求的所对应的ActionForm还有其相关跳转的Action来处理得到相关的JSP页面,从而来更新或是条状到相关用户的请求的服务页面,或是信息页面。而Hibernate的作用是体现在数据的持久化的层次中,我们对于页面,通过其特定的方式来对相关程序的数据惊醒I/O的持久化操作。在其次是相关spring的应用,是对与中间层次的相关的控制,处理相关业务的数据的依赖注入问题,还有就是融合其他的联大框架来实现相关程序的层次化的结构。
2.struct框架的使用
-
在web.xml中进行配置,相关配置如下:
- <filter>
- <filter-name>SSH</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>SSH</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
-
Struct.xml的相关配置如下
- <?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <includefile="struts-default.xml"/>
- <packagename="ynwi"extends="struts-default">
- <actionname="register"class="com.ynwi.ssh.action.RegisterAction">
- <resultname="input">/Register.jsp</result>
- <resultname="success">/Success.jsp</result>
- <resultname="error">/Fail.jsp</result>
- </action>
- </package>
- </struts>
- 其上两处的配置的做用时。当在browser中发出相关的请求时候,Struct会把相关的请求转到Struct的特定的filter中去,然后把数据映射到在struct.xml中所示的ActionForm中去,然后在更具配置吧,数据还有其他的相关的参数转交给相关的Action来做业务的处理,软后在更具结果进行跳转的。所以我们在Struct.xml中的相关的配置,实际上就是相关的请求所对应要使用到的ActionForm还有就是Action和相关跳转页面的配置。
-
程序的书写代码如下:
- packagecom.ynwi.ssh.beans;
- publicclassUserForm {
- privateString username;
- privateString password;
- privateintgender;
- publicString getUsername() {
- returnusername;
- }
- publicvoidsetUsername(String username) {
- this.username = username;
- }
- publicString getPassword() {
- returnpassword;
- }
- publicvoidsetPassword(String password) {
- this.password = password;
- }
- publicintgetGender() {
- returngender;
- }
- publicvoidsetGender(intgender) {
- this.gender = gender;
- }
- } //相关的ActionForm类的书写范例。
-
处理业务的书写如下:
- packagecom.ynwi.ssh.action;
- importcom.opensymphony.xwork2.ActionSupport;
- importcom.ynwi.ssh.beans.UserForm;
- importcom.ynwi.ssh.service.UserManager;
- importcom.ynwi.ssh.serviceImpl.UserManagerImpl;
- publicclassRegisterAction extendsActionSupport {
- privatestaticfinallongserialVersionUID = 1L;
- privateUserForm user;
- privateUserManager userManager;
- publicUserForm getUser() {
- returnuser;
- }
- publicvoidsetUser(UserForm user) {
- this.user = user;
- }
- publicUserManager getUserManager() {
- returnuserManager;
- }
- publicvoidsetUserManager(UserManager userManager) {
- this.userManager = userManager;
- }
- publicString execute() {
- try{
- this.setUserManager(newUserManagerImpl());
- userManager.regUser(user);
- returnSUCCESS;
- } catch(Exception e) {
- e.printStackTrace();
- returnERROR;
- }
- }
- } //相关的Action的书写范例。
- 以上便是struct的书写的范例。Struct的其原理可查询struct的官网站,或者是相关的文档。
3.Hibernate的使用
-
hibernate的相关的配置如下:
- <?xmlversion='1.0'encoding='utf-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
- <hibernate-configuration>
- <session-factory>
- <!-- Database connection settings -->
- <propertyname="connection.driver_class">com.mysql.jdbc.Driver</property>
- <propertyname="connection.url">jdbc:mysql://localhost:3306/project</property>
- <propertyname="connection.username">root</property>
- <propertyname="connection.password">root</property>
- <!-- JDBC connection pool (use the built-in) -->
- <!-- <property name="connection.pool_size">1</property> -->
- <!-- SQL dialect -->
- <propertyname="dialect">org.hibernate.dialect.MySQLDialect</property>
- <!-- Enable Hibernate's automatic session context management -->
- <!-- <property name="current_session_context_class">thread</property> -->
- <!-- Disable the second-level cache -->
- <!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> -->
- <!-- Echo all executed SQL to stdout -->
- <propertyname="show_sql">true</property>
- <!-- Drop and re-create the database schema on startup -->
- <!-- <property name="hbm2ddl.auto">update</property> -->
- <mappingresource="com/ynwi/ssh/beans/User.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
- //hibernate-configuration的相关的配置实际上就是配置县官的Hibernate的相关数据库ide链接用户名还有密码。同时还有一些相关的设置的问题。还有就是Mapping的配置(对象性的数据到关系型数据映射,例子见2)
-
mapping的配置:
- <?xmlversion="1.0"encoding='UTF-8'?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
- <hibernate-mappingpackage="com.ynwi.ssh.beans">
- <classname="User"table="user">
- <idname="userId"column="userId">
- <generatorclass="native"></generator>
- </id>
- <propertyname="username"column="userName"type="java.lang.String"
- not-null="true"length="16"></property>
- <propertyname="password"column="password"type="java.lang.String"
- not-null="true"length="16"/>
- <propertyname="gender"column="gender"type="java.lang.Integer"length="1"/>
- </class>
- </hibernate-mapping>
- //其中ID是变种对应的主键,而其他的为元素的应用。
- //代码<generator class="native"></generator>说明将根据本地数据库的设置来创建userId,如MySQL中将表user的userId设置为自动增长,则在保存记录是,userId将自动增长。对于需要在程序中指定主键的值,则将generator的class属性设置为assigned。
-
相关的代码书写如下:
- packagecom.ynwi.ssh.dao;
- importorg.hibernate.HibernateException;
- importorg.hibernate.Session;
- publicinterfaceBaseDao {
- publicvoidsaveObject(Object obj) throwsHibernateException;
- publicSession getSession();
- publicvoidsetSession(Session session);
- }
- //数据持久化曾的相关的接口。
- packagecom.ynwi.ssh.daoImpl;
- importorg.hibernate.HibernateException;
- importorg.hibernate.Session;
- importcom.ynwi.ssh.dao.BaseDao;
- publicclassUserDao implementsBaseDao {
- privateSession session;
- @Override
- publicSession getSession() {
- returnsession;
- }
- @Override
- publicvoidsetSession(Session session) {
- this.session = session;
- }
- @Override
- publicvoidsaveObject(Object obj) throwsHibernateException {
- session.save(obj);
- }
- }
- //数据持久层的相关的实现。
- packagecom.ynwi.ssh.daoImpl;
- importorg.hibernate.HibernateException;
- importorg.hibernate.Session;
- importorg.hibernate.SessionFactory;
- importorg.hibernate.cfg.Configuration;
- importorg.hibernate.service.ServiceRegistry;
- importorg.hibernate.service.ServiceRegistryBuilder;
- publicclassHibernateSessionFactory {
- privatestaticfinalString CFG_FILE_LOCATION = "/Hibernate.cfg.xml";
- privatestaticfinalThreadLocal<Session> threadLocal = newThreadLocal<Session>();
- privatestaticfinalConfiguration cfg = newConfiguration()
- .configure(CFG_FILE_LOCATION);
- privatestaticServiceRegistryBuilder builder = newServiceRegistryBuilder()
- .applySettings(cfg.getProperties());
- privatestaticServiceRegistry registry;
- privatestaticSessionFactory sessionFactory;
- publicstaticSession currentSession() throwsHibernateException {
- Session session = threadLocal.get();
- if(session == null|| session.isOpen() == false) {
- if(sessionFactory == null) {
- try{
- registry = builder.buildServiceRegistry();
- sessionFactory = cfg.buildSessionFactory(registry);
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- session = sessionFactory.openSession();
- threadLocal.set(session);
- }
- returnsession;
- }
- publicstaticvoidcloseSession() throwsHibernateException {
- Session session = threadLocal.get();
- threadLocal.set(null);
- if(session != null) {
- session.close();
- }
- }
- }
- //工厂类SessionFactory的内容。(这是使用Hibernate4时候的SessionFactory,Hibernate3时候sessionFactory的创建估计会不一样,请自行查阅。)
- packagecom.ynwi.ssh.serviceImpl;
- importorg.hibernate.HibernateException;
- importorg.hibernate.Session;
- importorg.hibernate.Transaction;
- importcom.ynwi.ssh.beans.User;
- importcom.ynwi.ssh.dao.BaseDao;
- importcom.ynwi.ssh.daoImpl.HibernateSessionFactory;
- importcom.ynwi.ssh.daoImpl.UserDao;
- importcom.ynwi.ssh.forms.UserForm;
- importcom.ynwi.ssh.service.UserManager;
- publicclassUserManagerImpl implementsUserManager {
- privateBaseDao dao;
- privateSession session;
- publicUserManagerImpl() {
- dao = newUserDao();
- }
- @Override
- publicvoidregUser(UserForm userForm) throwsHibernateException {
- session = HibernateSessionFactory.currentSession();
- dao.setSession(session);
- // 获取事务
- Transaction ts = session.beginTransaction();
- // 构造User对象
- User user = newUser();
- user.setUsername(userForm.getUsername());
- user.setPassword(userForm.getPassword());
- user.setGender(userForm.getGender());
- // 保存User对象
- dao.saveObject(user);
- // 提交事务
- ts.commit();
- // 关闭Session
- HibernateSessionFactory.closeSession();
- }
- }
- //相关的业务逻辑。
4.Hibernate的总结:
Hibernate实际上是在configuration方法的读取之下,得到相关的变量然后在通过此变量得到相关的sessionfactory类,通过SessionFactory类来读到会话类(Session)然后Session中的系列方法类进行数据库中的对应增,删,改,查的操作。当然session还可以开启事物的相关的操作。
4.Spring整合:
-
ApplicationContext.xml相关配置:
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <!-- 定义数据源的信息 -->
- <beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"
- destroy-method="close">
- <propertyname="driverClass">
- <value>com.mysql.jdbc.Driver</value>
- </property>
- <propertyname="jdbcUrl">
- <value>jdbc:mysql://localhost/project</value>
- </property>
- <propertyname="user">
- <value>root</value>
- </property>
- <propertyname="password">
- <value>root</value>
- </property>
- <propertyname="maxPoolSize">
- <value>80</value>
- </property>
- <propertyname="minPoolSize">
- <value>1</value>
- </property>
- <propertyname="initialPoolSize">
- <value>1</value>
- </property>
- <propertyname="maxIdleTime">
- <value>20</value>
- </property>
- </bean>
- <!--定义Hibernate的SessionFactory -->
- <!-- SessionFactory使用的数据源为上面的数据源 -->
- <!-- 指定了Hibernate的映射文件和配置信息 -->
- <beanid="sessionFactory"
- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <propertyname="dataSource">
- <reflocal="dataSource"/>
- </property>
- <propertyname="mappingResources">
- <list>
- <value>com/ynwi/ssh/beans/User.hbm.xml</value>
- </list>
- </property>
- <propertyname="hibernateProperties">
- <props>
- <propkey="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
- <propkey="show_sql">true</prop>
- <propkey="hibernate.jdbc.batch_size">20</prop>
- </props>
- </property>
- </bean>
- <beanid="transactionManager"
- class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <propertyname="sessionFactory"ref="sessionFactory"/>
- </bean>
- <beanid="baseDao"class="com.ynwi.ssh.daoImpl.UserDao">
- <propertyname="sessionFactory">
- <refbean="sessionFactory"/>
- </property>
- </bean>
- <!--用户注册业务逻辑类 -->
- <beanid="userManager"class="com.ynwi.ssh.serviceImpl.UserManagerImpl">
- <propertyname="dao">
- <refbean="baseDao"/>
- </property>
- </bean>
- <!-- 用户注册的Action -->
- <beanid="regAction"class="com.ynwi.ssh.action.RegisterAction">
- <propertyname="userManager">
- <refbean="userManager"/>
- </property>
- </bean>
- <!-- more bean definitions go here -->
- </beans>
- //对于用户中的业务逻辑还有持久化操作的逻辑的相关类,我们放到spring的相关的容器中进行统一的管理。
-
以上相关的修改结果如下(相对于之前的类来说):BaseDao.java
[java]view plain copy print ?
- packagecom.ynwi.ssh.dao;
- importorg.hibernate.HibernateException;
- publicinterfaceBaseDao {
- publicvoidsaveObject(Object obj) throwsHibernateException;
- }
UserDao.java
[java]view plain copy print ?
- packagecom.ynwi.ssh.daoImpl;
- importorg.hibernate.HibernateException;
- importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
- importcom.ynwi.ssh.dao.BaseDao;
- publicclassUserDao extendsHibernateDaoSupport implementsBaseDao {
- @Override
- publicvoidsaveObject(Object obj) throwsHibernateException {
- getHibernateTemplate().save(obj);
- }
- }
//getHibernateTemplate():HibernateTemplate 提供非常多的常用方法来完成基本的操作,比如通常的增加、删除、修改、查询等操作,Spring 2.0更增加对命名SQL查询的支持,也增加对分页的支持。大部分情况下,使用Hibernate的常规用法,就可完成大多数DAO对象的CRUD操作。 下面是HibernateTemplate的常用方法简介:
q void delete(Object entity):删除指定持久化实例
-
q deleteAll(Collection entities):删除集合内全部持久化类实例
-
q find(String queryString):根据HQL查询字符串来返回实例集合
-
q findByNamedQuery(String queryName):根据命名查询返回实例集合
-
q get(Class entityClass, Serializable id):根据主键加载特定持久化类的实例
-
q save(Object entity):保存新的实例
-
q saveOrUpdate(Object entity):根据实例状态,选择保存或者更新
-
q update(Object entity):更新实例的状态,要求entity是持久状态
-
q setMaxResults(int maxResults):设置分页的大小·····························································································································································在dao层用到getSession()方法来操作数据库记录,但是他还有个方法getHibernateTemplate(),这两个方法究竟有什么区别呢?
1.使用getSession()方法你只要继承 sessionFactory,而使用getHibernateTemplate()方法必须继承HibernateDaoSupport当然包括 sessionFactory,这点区别都不是特别重要的,下面这些区别就很重要了
2.getSession()方法是没有经过spring包装 的,spring会把最原始的session给你,在使用完之后必须自己调用相应的close方法,而且也不会对声明式事务进行相应的管理,一旦没有及时 关闭连接,就会导致数据库连接池的连接数溢出,getHibernateTemplate()方法是经过spring封装的,例如添加相应的声明式事务管 理,由spring管理相应的连接。
在实际的使用过程中发现的确getHibernateTemplate()比getSession()方法要好很多,但是有些方法在getHibernateTemplate()并没有提供,这时我们用HibernateCallback 回调的方法管理数据库.
例如如下代码:
/** * 使用 hql 语句进行操作
-
* @param hql HSQL 查询语句(使用回调函数访问外部变量,必须是final的)
-
* @param offset 开始取数据的下标
-
* @param length 读取数据记录数
-
* @return List 结果集
-
*/
-
public List getListForPage ( final String hql , final int offset , final int length ) {
List list = getHibernateTemplate().executeFind ( new HibernateCallback ( ) {
-
public Object doInHibernate ( Session session ) throws HibernateException, SQLException {
-
Query query = session.createQuery ( hql ) ; query.setFirstResult ( offset ) ; query.setMaxResults ( length ) ; List list = query.list ( ) ; return list ;
-
}
-
}) ;
-
return list ;}
- 修改后的业务逻辑实现类UserManagerImpl的内容。
[java]view plain copy print ?
- packagecom.ynwi.ssh.serviceImpl;
- importorg.hibernate.HibernateException;
- importorg.springframework.beans.BeanUtils;
- importcom.ynwi.ssh.beans.User;
- importcom.ynwi.ssh.dao.BaseDao;
- importcom.ynwi.ssh.forms.UserForm;
- importcom.ynwi.ssh.service.UserManager;
- publicclassUserManagerImpl implementsUserManager {
- privateBaseDao dao;
- publicvoidsetDao(BaseDao dao) {
- this.dao = dao;
- }
- @Override
- publicvoidregUser(UserForm userForm) throwsHibernateException {
- User user = newUser();
- BeanUtils.copyProperties(userForm, user);
- dao.saveObject(user);
- }
- }
- 修改后的用户注册Action类RegisterAction的内容。
[java]view plain copy print ?
- packagecom.ynwi.ssh.action;
- importcom.opensymphony.xwork2.ActionSupport;
- importcom.ynwi.ssh.forms.UserForm;
- importcom.ynwi.ssh.service.UserManager;
- publicclassRegisterAction extendsActionSupport {
- privatestaticfinallongserialVersionUID = 1L;
- privateUserForm user;
- privateUserManager userManager;
- publicUserForm getUser() {
- returnuser;
- }
- publicvoidsetUser(UserForm user) {
- this.user = user;
- }
- publicvoidsetUserManager(UserManager userManager) {
- this.userManager = userManager;
- }
- publicString execute() {
- try{
- userManager.regUser(user);
- returnSUCCESS;
- } catch(Exception e) {
- e.printStackTrace();
- returnERROR;
- }
- }
- }
- 修改后的web.xml的内容。
[html]view plain copy print ?
- <?xmlversion="1.0"encoding="UTF-8"?>
- <web-appid="WebApp_9"version="2.4"xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <display-name>SSH Project</display-name>
- <filter>
- <filter-name>SSH</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>SSH</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- </welcome-file-list>
- </web-app>
- 修改后的Struts配置文件struts.xml的内容。
[html]view plain copy print ?
- <?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <includefile="struts-default.xml"/>
- <packagename="ynwi"extends="struts-default">
- <actionname="register"class="regAction">
- <resultname="input">/Register.jsp</result>
- <resultname="success">/Success.jsp</result>
- <resultname="error">/Fail.jsp</result>
- </action>
- </package>
- </struts>
5.总结
有待改善。
技术分享:www.kaige123.com
推荐阅读
-
学习SSH框架 博客分类: java SSH框架java
-
JVM学习(2)-JVM垃圾回收算法 博客分类: java虚拟机 java虚拟机java垃圾回收算法
-
学习SSH框架 博客分类: java SSH框架java
-
Java虚拟机原理学习 博客分类: JVM Java虚拟机
-
JVM学习(1)-JVM运行时数据区 博客分类: java虚拟机 java虚拟机javajvm
-
java学习资料收集 博客分类: 乱写 JavawebbeansHTML
-
Murach's Java Servlet and JSP 2nd Edition是再续经典还是鸡肋 博客分类: 专家文章翻译 JSPServletJava框架音乐
-
Rapid-framework代码自动生成器 博客分类: java SpringFlexiBATISHibernate框架
-
SSH框架总结 博客分类: 网站链接地址大全
-
使用ssh框架写一个基本的登录注册页面 博客分类: 项目代码