SSH框架学习
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的相关配置如下
- <?xml version="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>
- <include file="struts-default.xml" />
- <package name="ynwi" extends="struts-default">
- <action name="register" class="com.ynwi.ssh.action.RegisterAction">
- <result name="input">/Register.jsp</result>
- <result name="success">/Success.jsp</result>
- <result name="error">/Fail.jsp</result>
- </action>
- </package>
- </struts>
- 其上两处的配置的做用时。当在browser中发出相关的请求时候,Struct会把相关的请求转到Struct的特定的filter中去,然后把数据映射到在struct.xml中所示的ActionForm中去,然后在更具配置吧,数据还有其他的相关的参数转交给相关的Action来做业务的处理,软后在更具结果进行跳转的。所以我们在Struct.xml中的相关的配置,实际上就是相关的请求所对应要使用到的ActionForm还有就是Action和相关跳转页面的配置。
-
程序的书写代码如下:
- package com.ynwi.ssh.beans;
- public class UserForm {
- private String username;
- private String password;
- private int gender;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public int getGender() {
- return gender;
- }
- public void setGender(int gender) {
- this.gender = gender;
- }
- } //相关的ActionForm类的书写范例。
-
处理业务的书写如下:
- package com.ynwi.ssh.action;
- import com.opensymphony.xwork2.ActionSupport;
- import com.ynwi.ssh.beans.UserForm;
- import com.ynwi.ssh.service.UserManager;
- import com.ynwi.ssh.serviceImpl.UserManagerImpl;
- public class RegisterAction extends ActionSupport {
- private static final long serialVersionUID = 1L;
- private UserForm user;
- private UserManager userManager;
- public UserForm getUser() {
- return user;
- }
- public void setUser(UserForm user) {
- this.user = user;
- }
- public UserManager getUserManager() {
- return userManager;
- }
- public void setUserManager(UserManager userManager) {
- this.userManager = userManager;
- }
- public String execute() {
- try {
- this.setUserManager(new UserManagerImpl());
- userManager.regUser(user);
- return SUCCESS;
- } catch (Exception e) {
- e.printStackTrace();
- return ERROR;
- }
- }
- } //相关的Action的书写范例。
- 以上便是struct的书写的范例。Struct的其原理可查询struct的官网站,或者是相关的文档。
3.Hibernate的使用
-
hibernate的相关的配置如下:
- <?xml version='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 -->
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="connection.url">jdbc:mysql://localhost:3306/project</property>
- <property name="connection.username">root</property>
- <property name="connection.password">root</property>
- <!-- JDBC connection pool (use the built-in) -->
- <!-- <property name="connection.pool_size">1</property> -->
- <!-- SQL dialect -->
- <property name="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 -->
- <property name="show_sql">true</property>
- <!-- Drop and re-create the database schema on startup -->
- <!-- <property name="hbm2ddl.auto">update</property> -->
- <mapping resource="com/ynwi/ssh/beans/User.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
- //hibernate-configuration的相关的配置实际上就是配置县官的Hibernate的相关数据库ide链接用户名还有密码。同时还有一些相关的设置的问题。还有就是Mapping的配置(对象性的数据到关系型数据映射,例子见2)
-
mapping的配置:
- <?xml version="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-mapping package="com.ynwi.ssh.beans">
- <class name="User" table="user">
- <id name="userId" column="userId">
- <generator class="native"></generator>
- </id>
- <property name="username" column="userName" type="java.lang.String"
- not-null="true" length="16"></property>
- <property name="password" column="password" type="java.lang.String"
- not-null="true" length="16" />
- <property name="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。
-
相关的代码书写如下:
- package com.ynwi.ssh.dao;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- public interface BaseDao {
- public void saveObject(Object obj) throws HibernateException;
- public Session getSession();
- public void setSession(Session session);
- }
- //数据持久化曾的相关的接口。
- package com.ynwi.ssh.daoImpl;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import com.ynwi.ssh.dao.BaseDao;
- public class UserDao implements BaseDao {
- private Session session;
- @Override
- public Session getSession() {
- return session;
- }
- @Override
- public void setSession(Session session) {
- this.session = session;
- }
- @Override
- public void saveObject(Object obj) throws HibernateException {
- session.save(obj);
- }
- }
- //数据持久层的相关的实现。
- package com.ynwi.ssh.daoImpl;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.service.ServiceRegistry;
- import org.hibernate.service.ServiceRegistryBuilder;
- public class HibernateSessionFactory {
- private static final String CFG_FILE_LOCATION = "/Hibernate.cfg.xml";
- private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
- private static final Configuration cfg = new Configuration()
- .configure(CFG_FILE_LOCATION);
- private static ServiceRegistryBuilder builder = new ServiceRegistryBuilder()
- .applySettings(cfg.getProperties());
- private static ServiceRegistry registry;
- private static SessionFactory sessionFactory;
- public static Session currentSession() throws HibernateException {
- 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);
- }
- return session;
- }
- public static void closeSession() throws HibernateException {
- Session session = threadLocal.get();
- threadLocal.set(null);
- if (session != null) {
- session.close();
- }
- }
- }
- // 工厂类SessionFactory的内容。(这是使用Hibernate4时候的SessionFactory,Hibernate3时候sessionFactory的创建估计会不一样,请自行查阅。)
- package com.ynwi.ssh.serviceImpl;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.Transaction;
- import com.ynwi.ssh.beans.User;
- import com.ynwi.ssh.dao.BaseDao;
- import com.ynwi.ssh.daoImpl.HibernateSessionFactory;
- import com.ynwi.ssh.daoImpl.UserDao;
- import com.ynwi.ssh.forms.UserForm;
- import com.ynwi.ssh.service.UserManager;
- public class UserManagerImpl implements UserManager {
- private BaseDao dao;
- private Session session;
- public UserManagerImpl() {
- dao = new UserDao();
- }
- @Override
- public void regUser(UserForm userForm) throws HibernateException {
- session = HibernateSessionFactory.currentSession();
- dao.setSession(session);
- // 获取事务
- Transaction ts = session.beginTransaction();
- // 构造User对象
- User user = new User();
- 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相关配置:
- <?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/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <!-- 定义数据源的信息 -->
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
- destroy-method="close">
- <property name="driverClass">
- <value>com.mysql.jdbc.Driver</value>
- </property>
- <property name="jdbcUrl">
- <value>jdbc:mysql://localhost/project</value>
- </property>
- <property name="user">
- <value>root</value>
- </property>
- <property name="password">
- <value>root</value>
- </property>
- <property name="maxPoolSize">
- <value>80</value>
- </property>
- <property name="minPoolSize">
- <value>1</value>
- </property>
- <property name="initialPoolSize">
- <value>1</value>
- </property>
- <property name="maxIdleTime">
- <value>20</value>
- </property>
- </bean>
- <!--定义Hibernate的SessionFactory -->
- <!-- SessionFactory使用的数据源为上面的数据源 -->
- <!-- 指定了Hibernate的映射文件和配置信息 -->
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <property name="dataSource">
- <ref local="dataSource" />
- </property>
- <property name="mappingResources">
- <list>
- <value>com/ynwi/ssh/beans/User.hbm.xml</value>
- </list>
- </property>
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
- <prop key="show_sql">true</prop>
- <prop key="hibernate.jdbc.batch_size">20</prop>
- </props>
- </property>
- </bean>
- <bean id="transactionManager"
- class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory" />
- </bean>
- <bean id="baseDao" class="com.ynwi.ssh.daoImpl.UserDao">
- <property name="sessionFactory">
- <ref bean="sessionFactory" />
- </property>
- </bean>
- <!--用户注册业务逻辑类 -->
- <bean id="userManager" class="com.ynwi.ssh.serviceImpl.UserManagerImpl">
- <property name="dao">
- <ref bean="baseDao" />
- </property>
- </bean>
- <!-- 用户注册的Action -->
- <bean id="regAction" class="com.ynwi.ssh.action.RegisterAction">
- <property name="userManager">
- <ref bean="userManager" />
- </property>
- </bean>
- <!-- more bean definitions go here -->
- </beans>
- //对于用户中的业务逻辑还有持久化操作的逻辑的相关类,我们放到spring的相关的容器中进行统一的管理。
-
以上相关的修改结果如下(相对于之前的类来说):BaseDao.java
- package com.ynwi.ssh.dao;
- import org.hibernate.HibernateException;
- public interface BaseDao {
- public void saveObject(Object obj) throws HibernateException;
- }
- package com.ynwi.ssh.daoImpl;
- import org.hibernate.HibernateException;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- import com.ynwi.ssh.dao.BaseDao;
- public class UserDao extends HibernateDaoSupport implements BaseDao {
- @Override
- public void saveObject(Object obj) throws HibernateException {
- 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的内容。
- package com.ynwi.ssh.serviceImpl;
- import org.hibernate.HibernateException;
- import org.springframework.beans.BeanUtils;
- import com.ynwi.ssh.beans.User;
- import com.ynwi.ssh.dao.BaseDao;
- import com.ynwi.ssh.forms.UserForm;
- import com.ynwi.ssh.service.UserManager;
- public class UserManagerImpl implements UserManager {
- private BaseDao dao;
- public void setDao(BaseDao dao) {
- this.dao = dao;
- }
- @Override
- public void regUser(UserForm userForm) throws HibernateException {
- User user = new User();
- BeanUtils.copyProperties(userForm, user);
- dao.saveObject(user);
- }
- }
- 修改后的用户注册Action类RegisterAction的内容。
- package com.ynwi.ssh.action;
- import com.opensymphony.xwork2.ActionSupport;
- import com.ynwi.ssh.forms.UserForm;
- import com.ynwi.ssh.service.UserManager;
- public class RegisterAction extends ActionSupport {
- private static final long serialVersionUID = 1L;
- private UserForm user;
- private UserManager userManager;
- public UserForm getUser() {
- return user;
- }
- public void setUser(UserForm user) {
- this.user = user;
- }
- public void setUserManager(UserManager userManager) {
- this.userManager = userManager;
- }
- public String execute() {
- try {
- userManager.regUser(user);
- return SUCCESS;
- } catch (Exception e) {
- e.printStackTrace();
- return ERROR;
- }
- }
- }
- 修改后的web.xml的内容。
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app id="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的内容。
- <?xml version="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>
- <include file="struts-default.xml" />
- <package name="ynwi" extends="struts-default">
- <action name="register" class="regAction">
- <result name="input">/Register.jsp</result>
- <result name="success">/Success.jsp</result>
- <result name="error">/Fail.jsp</result>
- </action>
- </package>
- </struts>
5.总结
有待改善。
推荐阅读
-
数据库知识学习之SQL语句多表联合查询
-
vue学习指南:第七篇(详细) - Vue的 组件通信
-
Flask框架 请求与响应 & 模板语法
-
Python学习笔记(五)
-
Django-2.2.1学习感悟
-
Django开发学习BUG记录--RemovedInDjango19Warning:Model class apps.user.models.User doesn't declare an explicit app_label
-
Python3.0科学计算学习之绘图(一)
-
Linux学习笔记(十一)shell基础:管道符、通配符和其他特殊符号
-
如何搭建一个功能复杂的前端配置化框架(一)
-
一起学习造*(三):从零开始写一个React-Redux