SSH整合

Posted 曹增令

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSH整合相关的知识,希望对你有一定的参考价值。

struts 控制用的

hibernate 操作数据库的

spring 用解耦的

Struts 、 spring 、 Hibernate 在各层的作用

1 ) struts 负责 web 层 .

ActionFormBean 接收网页中表单提交的数据,然后通过 Action 进行处理,再 Forward 到对应的网页。

在 struts-config.xml 中定义 <action-mapping>, ActionServlet 会加载。

2 ) spring 负责业务层管理,即 Service (或 Manager).

1 . service 为 action 提供统计的调用接口,封装持久层的 DAO.

2 .可以写一些自己的业务方法。

3 .统一的 javabean 管理方法

4 .声明式事务管理

5. 集成 Hiberante

3 ) Hiberante ,负责持久化层,完成数据库的 crud 操作

hibernate 为持久层,提供 OR/Mapping 。

它有一组 .hbm.xml 文件和 POJO, 是跟数据库中的表相对应的。然后定义 DAO ,这些是跟数据库打交道的类,它们会使用 PO 。

在 struts+spring+hibernate 的系统中,

对象的调用流程是: jsp-> Action - > Service ->DAO ->Hibernate 。

数据的流向是 ActionFormBean 接受用户的数据, Action 将数据从 ActionFromBean 中取出,封装成 VO 或 PO,

再调用业务层的 Bean 类,完成各种业务处理后再 forward 。而业务层 Bean 收到这个 PO 对象之后,会调用 DAO 接口方法,进行持久化操作。

 

 spring:Aop管理事务控制,IoC管理各个组件的耦合,DaoTemplate作为常规持久层的快速开发模板!

struts:控制层Action,页面标签和Model数据,调用业务层

Hibernate:负责数据库和对象的映射,负责DAO层(Data Access Object:数据访问)

 

spring整合hibernate和struts,只要在配好了applicationContext.xml,在struts的action中直接调用就可以了。hibernate访问数据库的操作都在spring中实现了,spring的调用又在stuts的action中实现了。这个ssh框架就连到了一起……

 

 

一个简单的SSH例子

配置文件

/SSHLoginDemo/WebRoot/WEB-INF/struts-config.xml

代码

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
    <data-sources />
    <form-beans>
        <form-bean name="loginForm"
            type="com.qdu.sun.struts.form.LoginForm" />

    </form-beans>

    <global-exceptions />
    <global-forwards />
    <action-mappings>
        <action attribute="loginForm" input="/login.jsp"
            name="loginForm" path="/login" scope="request"
            type="org.springframework.web.struts.DelegatingActionProxy">
            <forward name="success" path="/success.jsp" />
            <forward name="fail" path="/fail.jsp" />
        </action>

    </action-mappings>

    <message-resources
        parameter="com.qdu.sun.struts.ApplicationResources" />
    <plug-in
        className="org.springframework.web.struts.ContextLoaderPlugIn">
        <set-property property="contextConfigLocation"
            value="/WEB-INF/classes/applicationContext.xml" />
    </plug-in>

</struts-config>

 


复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
<data-sources />
<form-beans>
<form-bean name="loginForm"
type="com.qdu.sun.struts.form.LoginForm" />

</form-beans>

<global-exceptions />
<global-forwards />
<action-mappings>
<action attribute="loginForm" input="/login.jsp"
name="loginForm" path="/login" scope="request"
type="org.springframework.web.struts.DelegatingActionProxy">
<forward name="success" path="/success.jsp" />
<forward name="fail" path="/fail.jsp" />
</action>

</action-mappings>

<message-resources
parameter="com.qdu.sun.struts.ApplicationResources" />
<plug-in
className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/classes/applicationContext.xml" />
</plug-in>

</struts-config>

复制代码

/SSHLoginDemo/src/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-2.0.xsd">
    <bean id="login" class="com.qdu.sun.BO.LoginBO" />
    <bean name="/login" class="com.qdu.sun.struts.action.LoginAction">
        <property name="loginBean">
            <ref bean="login" />
        </property>
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocation"
            value="classpath:hibernate.cfg.xml">
        </property>
    </bean>
    <bean id="UserDAO" class="com.qdu.sun.hibernate.UserDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    
</beans>

 


复制代码
<?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-2.0.xsd">
<bean id="login" class="com.qdu.sun.BO.LoginBO" />
<bean name="/login" class="com.qdu.sun.struts.action.LoginAction">
<property name="loginBean">
<ref bean="login" />
</property>
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
<bean id="UserDAO" class="com.qdu.sun.hibernate.UserDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>

</beans>
复制代码

 

 

 

前端页面

/SSHLoginDemo/WebRoot/login.jsp

代码

<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%> 
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
 
<html> 
    <head>
        <title>JSP for LoginForm form</title>
    </head>
    <body>
        <html:form action="/login">
            password : <html:password property="password"/><html:errors property="password"/><br/>
            username : <html:text property="username"/><html:errors property="username"/><br/>
            <html:submit/><html:cancel/>
        </html:form>
    </body>
</html>

 


复制代码
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

<html>
<head>
<title>JSP for LoginForm form</title>
</head>
<body>
<html:form action="/login">
password : <html:password property="password"/><html:errors property="password"/><br/>
username : <html:text property="username"/><html:errors property="username"/><br/>
<html:submit/><html:cancel/>
</html:form>
</body>
</html>

复制代码

 

struts

/SSHLoginDemo/src/com/qdu/sun/struts/action/LoginAction.java

代码

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.qdu.sun.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.qdu.sun.BO.LoginBO;
import com.qdu.sun.struts.form.LoginForm;

/** 
 * MyEclipse Struts
 * Creation date: 08-26-2008
 * 
 * XDoclet definition:
 * @struts.action path="/login" name="loginForm" input="/login.jsp" scope="request" validate="true"
 * @struts.action-forward name="success" path="welcome.jsp"
 * @struts.action-forward name="fail" path="fail.jsp"
 */
public class LoginAction extends Action {
    /*
     * Generated Methods
     */

    /** 
     * Method execute
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    private LoginBO loginBean; 
    public LoginBO getLoginBean() {
        return loginBean;
      }
      public void setLoginBean(LoginBO loginBean) {   
        this.loginBean=loginBean;
      } 
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        LoginForm loginForm = (LoginForm) form;// TODO Auto-generated method stub
        LoginBO login=getLoginBean();  
        if(login.validate(loginForm.getUsername(), loginForm.getPassword()))
        {
            request.setAttribute("username", loginForm.getUsername());
        return mapping.findForward("success");
        }
        else
            return mapping.findForward("fail");
    }
}

 


复制代码
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.qdu.sun.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.qdu.sun.BO.LoginBO;
import com.qdu.sun.struts.form.LoginForm;

/**
* MyEclipse Struts
* Creation date: 08-26-2008
*
* XDoclet definition:
* @struts.action path="/login" name="loginForm" input="/login.jsp" scope="request" validate="true"
* @struts.action-forward name="success" path="welcome.jsp"
* @struts.action-forward name="fail" path="fail.jsp"
*/
public class LoginAction extends Action {
/*
* Generated Methods
*/

/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
private LoginBO loginBean;
public LoginBO getLoginBean() {
return loginBean;
}
public void setLoginBean(LoginBO loginBean) {
this.loginBean=loginBean;
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LoginForm loginForm = (LoginForm) form;// TODO Auto-generated method stub
LoginBO login=getLoginBean();
if(login.validate(loginForm.getUsername(), loginForm.getPassword()))
{
request.setAttribute("username", loginForm.getUsername());
return mapping.findForward("success");
}
else
return mapping.findForward("fail");
}
}
复制代码

/SSHLoginDemo/src/com/qdu/sun/struts/form/LoginForm.java

 

代码

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.qdu.sun.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/** 
 * MyEclipse Struts
 * Creation date: 08-26-2008
 * 
 * XDoclet definition:
 * @struts.form name="loginForm"
 */
public class LoginForm extends ActionForm {
    /*
     * Generated fields
     */

    /** password property */
    private String password;

    /** username property */
    private String username;

    /*
     * Generated Methods
     */

    /** 
     * Method validate
     * @param mapping
     * @param request
     * @return ActionErrors
     */
    public ActionErrors validate(ActionMapping mapping,
            HttpServletRequest request) {
        // TODO Auto-generated method stub
        ActionErrors errors=new ActionErrors();
        if(this.username==null||this.username.length()<1)
            errors.add("username", new ActionMessage("login.username"));
        if(this.password==null||this.password.length()<1)
            errors.add("password", new ActionMessage("login.password"));
            return errors;
    }

    /** 
     * Method reset
     * @param mapping
     * @param request
     */
    public void reset(ActionMapping mapping, HttpServletRequest request) {
        // TODO Auto-generated method stub
        this.username=null;
        this.password=null;
    }

    /** 
     * Returns the password.
     * @return String
     */
    public String getPassword() {
        return password;
    }

    /** 
     * Set the password.
     * @param password The password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /** 
     * Returns the username.
     * @return String
     */
    public String getUsername() {
        return username;
    }

    /** 
     * Set the username.
     * @param username The username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }
}

 


复制代码
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.qdu.sun.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
* MyEclipse Struts
* Creation date: 08-26-2008
*
* XDoclet definition:
* @struts.form name="loginForm"
*/
public class LoginForm extends ActionForm {
/*
* Generated fields
*/

/** password property */
private String password;

/** username property */
private String username;

/*
* Generated Methods
*/

/**
* Method validate
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
ActionErrors errors=new ActionErrors();
if(this.username==null||this.username.length()<1)
errors.add("username", new ActionMessage("login.username"));
if(this.password==null||this.password.length()<1)
errors.add("password", new ActionMessage("login.password"));
return errors;
}

/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
this.username=null;
this.password=null;
}

/**
* Returns the password.
* @return String
*/
public String getPassword() {
return password;
}

/**
* Set the password.
* @param password The password to set
*/
public void setPassword(String password) {
this.password = password;
}

/**
* Returns the username.
* @return String
*/
public String getUsername() {
return username;
}

/**
* Set the username.
* @param username The username to set
*/
public void setUsername(String username) {
this.username = username;
}
}
复制代码

 

spring

/SSHLoginDemo/src/com/qdu/sun/BO/LoginBO.java

代码

package com.qdu.sun.BO;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.qdu.sun.hibernate.User;
import com.qdu.sun.hibernate.UserDAO;

public class LoginBO {
    public boolean validate(String username, String password) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        UserDAO dao = (UserDAO) ctx.getBean("UserDAO");
        User user = new User();
        user.setPassword(password);
        user.setUsername(username);
        List list = dao.findByExample(user);
        if (list.size() > 0) {

            return true;

        } else {
            return false;

        }
    }
}

 


复制代码
package com.qdu.sun.BO;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.qdu.sun.hibernate.User;
import com.qdu.sun.hibernate.UserDAO;

public class LoginBO {
public boolean validate(String username, String password) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"applicationContext.xml");
UserDAO dao = (UserDAO) ctx.getBean("UserDAO");
User user = new User();
user.setPassword(password);
user.setUsername(username);
List list = dao.findByExample(user);
if (list.size() > 0) {

return true;

} else {
return false;

}
}
}
复制代码

 

 

 

 

hibernate

/SSHLoginDemo/src/com/qdu/sun/hibernate/UserDAO.java

代码

package com.qdu.sun.hibernate;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * A data access object (DAO) providing persistence and search support for User
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see com.qdu.sun.hibernate.User
 * @author MyEclipse Persistence Tools
 */

public class UserDAO extends HibernateDaoSupport {
    private static final Log log = LogFactory.getLog(UserDAO.class);
    // property constants
    public static final String USERNAME = "username";
    public static final String PASSWORD = "password";

    protected void initDao() {
        // do nothing
    }

    public void save(User transientInstance) {
        log.debug("saving User instance");
        try {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    public void delete(User persistentInstance) {
        log.debug("deleting User instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public User findById(java.lang.Integer id) {
        log.debug("getting User instance with id: " + id);
        try {
            User instance = (User) getHibernateTemplate().get(
                    "com.qdu.sun.hibernate.User", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findByExample(User instance) {
        log.debug("finding User instance by example");
        try {
            List results = getHibernateTemplate().findByExample(instance);
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    public List findByProperty(String propertyName, Object value) {
        log.debug("finding User instance with property: " + propertyName
                + ", value: " + value);
        try {
            String queryString = "from User as model where model."
                    + propertyName + "= ?";
            return getHibernateTemplate().find(queryString, value);
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List findByUsername(Object username) {
        return findByProperty(USERNAME, username);
    }

    public List findByPassword(Object password) {
        return findByProperty(PASSWORD, password);
    }

    public List findAll() {
        log.debug("finding all User instances");
        try {
            String queryString = "from User";
            return getHibernateTemplate().find(queryString);
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public User merge(User detachedInstance) {
        log.debug("merging User instance");
        try {
            User result = (User) getHibernateTemplate().merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(User instance) {
        log.debug("attaching dirty User instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(User instance) {
        log.debug("attaching clean User instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
        return (UserDAO) ctx.getBean("UserDAO");
    }
}

 


复制代码
package com.qdu.sun.hibernate;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
* A data access object (DAO) providing persistence and search support for User
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see com.qdu.sun.hibernate.User
* @author MyEclipse Persistence Tools
*/

public class UserDAO extends HibernateDaoSupport {
private static final Log log = LogFactory.getLog(UserDAO.class);
// property constants
public static final String USERNAME = "username";
public static final String PASSWORD = "password";

protected void initDao() {
// do nothing
}

public void save(User transientInstance) {
log.debug("saving User instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}

public void delete(User persistentInstance) {
log.debug("deleting User instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}

public User findById(java.lang.Integer id) {
log.debug("getting User instance with id: " + id);
try {
User instance = (User) getHibernateTemplate().get(
"com.qdu.sun.hibernate.User", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}

public List findByExample(User instance) {
log.debug("finding User instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}

public List findByProperty(String propertyName, Object value) {
log.debug("finding User instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from User as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}

public List findByUsername(Object username) {
return findByProperty(USERNAME, username);
}

public List findByPassword(Object password) {
return findByProperty(PASSWORD, password);
}

public List findAll() {
log.debug("finding all User instances");
try {
String queryString = "from User";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}

public User merge(User detachedInstance) {
log.debug("merging User instance");
try {
User result = (User) getHibernateTemplate().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

public void attachDirty(User instance) {
log.debug("attaching dirty User instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public void attachClean(User instance) {
log.debug("attaching clean User instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
return (UserDAO) ctx.getBean("UserDAO");
}
}

以上是关于SSH整合的主要内容,如果未能解决你的问题,请参考以下文章

全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段

Java的SSH框架整合

SSH整合总结(OA项目)

dwr与ssh框架整合教程

SSH 框架整合(maven版本 xml配置方式)

Memcached的配置,SSH项目中的整合(com.whalin),Memcached工具类,Memcached的代码调用