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>
/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">
<bean id="UserDAO" class="com.qdu.sun.hibernate.UserDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</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>
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");
}
}
/SSHLoginDemo/src/com/qdu/sun/struts/form/LoginForm.java
*/
package com.qdu.sun.struts.form;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
* @struts.form name="loginForm"
public class LoginForm extends ActionForm {
* Generated fields
*/
/** password property */
private String password;
/** username property */
private String username;
* Method validate
* @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
public void reset(ActionMapping mapping, HttpServletRequest request) {
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.
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;
hibernate
/SSHLoginDemo/src/com/qdu/sun/hibernate/UserDAO.java
package com.qdu.sun.hibernate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
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");
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
log.error("delete failed", re);
public User findById(java.lang.Integer id) {
log.debug("getting User instance with id: " + id);
User instance = (User) getHibernateTemplate().get(
"com.qdu.sun.hibernate.User", id);
return instance;
log.error("get failed", re);
public List findByExample(User instance) {
log.debug("finding User instance by example");
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
log.error("find by example failed", re);
public List findByProperty(String propertyName, Object value) {
log.debug("finding User instance with property: " + propertyName
+ ", value: " + value);
String queryString = "from User as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
log.error("find by property name failed", 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");
String queryString = "from User";
return getHibernateTemplate().find(queryString);
log.error("find all failed", re);
public User merge(User detachedInstance) {
log.debug("merging User instance");
User result = (User) getHibernateTemplate().merge(detachedInstance);
log.debug("merge successful");
return result;
log.error("merge failed", re);
public void attachDirty(User instance) {
log.debug("attaching dirty User instance");
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
log.error("attach failed", re);
public void attachClean(User instance) {
log.debug("attaching clean User instance");
getHibernateTemplate().lock(instance, LockMode.NONE);
public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
return (UserDAO) ctx.getBean("UserDAO");
本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1080799