1. 程式人生 > >SSH+oracle開發環境搭建。MyEclipse 10+Struts2+Hibernate3.3+Spring3.2.3+tomcat-6.0.35

SSH+oracle開發環境搭建。MyEclipse 10+Struts2+Hibernate3.3+Spring3.2.3+tomcat-6.0.35

我的工程匯出來的jar包的下載地址為點選開啟連結

一,開發環境準備工作。

0,oracle資料庫的表名和表結構如圖:

       1,我這裡用的各個軟體版本如下:MyEclipse 10,tomcat-6.0.35 ,struts-2.2.1.1,spring-framework-3.2.3.RELEASE-dist,這裡struts-2.2.1.1因為超過60M,傳不了CSDN,所以大家自己去下載一下,spring-framework-3.2.3.RELEASE-dist下載地址:http://download.csdn.net/detail/liujianian/8612689,Hibernate3.3我是直接在MyEclipse中載入的,操作步驟如下:

               ①:建立一個新的web project工程,選擇Java EE6.0,點選完成。

               ②:這裡我們需要引入外部的驅動jar包(ojdbc14.jar),下載地址:http://download.csdn.net/detail/liujianian/8612779。將ojdbc14.jar包拷入“test”工程中WebRoot/WEB-INF/lib下

               ③:選擇“test”工程,右擊選擇“myEclipse”-->"Add Hibernate Capabilities",選擇Hibernate3.3,

               ④:選擇“next”

               ⑤:選擇“next”,填寫資料庫連線的相關資訊,這個以後在hibernate.cfg.xml中還可以修改的。

               ⑥:選擇“next”,,我們不建立Session Factory類(將上面的勾去掉),等後面工程裡面我自己新建,點選“finish”完成hibernate包的載入。完成後如圖會出現以下jar包:參照後面的目錄截圖

        2,外部引入我們下載的Struts包。

              ①:選擇工程右擊“Build Path”-->"Add Libraries",,選擇“User Library”-->"next",選擇“UserLibraries",命名為Struts2,選擇struts下lib下面的這些包,點選OK這樣struts包就載入好了。如圖:參照後面的目錄截圖

 3,準備工作做好了,下面我們來進行Struts和hibernate的整合開發,spring最後再整合。

     檔案目錄如下:

     ①:LoginAction.java(action類)

package com.ssh.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.ssh.forms.UserForm;
import com.ssh.service.UserManager;
import com.ssh.serviceImpl.UserManagerImpl;

public class LoginAction extends ActionSupport implements Preparable{
	//該類繼承了ActionSupport類。這樣就可以直接使用SUCCESS, LOGIN等變數和重寫execute等方法
	/**
	 * 
	 */
	private static final long serialVersionUID = 724458459147961157L;
	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;  
    }  

	@Override
    public String execute() {
        try{
        	this.setUserManager(new UserManagerImpl());
        	user.setUserId("1");
            userManager.regUser(user);
            return SUCCESS;
        }catch(Exception e){
        	e.printStackTrace();
        	return ERROR;
        }
	}
	//清除LoginAction-validation.xml爆出的錯誤資訊
	public void prepare(){
		clearErrorsAndMessages();
	};
}

②:LoginAction-validation.xml(check前臺頁面的配置檔案,和action在一個目錄下面)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"  "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">  
<validators>  
    <!-- 新增對使用者名稱的校驗 -->  
    <field name="user.username">  
        <field-validator type="requiredstring">  
            <param name="trim">true</param>  
            <message>使用者名稱不能為空</message>  
        </field-validator>  
        <field-validator type="regex">  
            <param name="expression"><![CDATA[(\w{4,16})]]></param>  
            <message>使用者名稱輸入不合法,必須為長度在4~16中間的數字或字母</message>  
        </field-validator>  
    </field>  
      
    <!-- 新增對密碼的校驗 -->  
    <field name="user.password">  
        <field-validator type="requiredstring">  
            <param name="trim">true</param>  
            <message>密碼不能為空</message>  
        </field-validator>  
        <field-validator type="regex">  
            <param name="expression"><![CDATA[(\w{4,16})]]></param>  
            <message>密碼輸入不合法,必須為長度在4~16之間的數字或者字母</message>  
        </field-validator>  
    </field>  
</validators>  
③:User.java(beans)
package com.ssh.beans;

public class User {
	private String userId;
	private String username;  
    private String password;  
    
    public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	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;  
    }  
}
④User.hbm.xml配置檔案
<?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.ssh.beans">  <!-- 資料庫表名和java類名的對映 -->
    <class name="User" table="t_user">  
        <id name="userId" column="user_id">  
        </id>  
        <property name="username" column="user_name" type="java.lang.String"  
            not-null="true" length="16"></property>  
        <property name="password" column="user_password" type="java.lang.String"  
            not-null="true" length="16" />  
    </class>  
</hibernate-mapping>  
⑤:BaseDao.java:
package com.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);  
}
⑥:HibernateSessionFactory.java
package com.ssh.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

⑦UserDao.java:
package com.ssh.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.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);  
    }  
}

⑧UserForm.java
package com.ssh.forms;

public class UserForm {
	private String userId;
	private String username;  
    private String password;  
    public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
    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;  
    }  
}
⑨:
package com.ssh.service;

import com.ssh.forms.UserForm;

public interface  UserManager {
	public void regUser(UserForm user);  
}
⑩:
package com.ssh.serviceImpl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.ssh.beans.User;
import com.ssh.dao.BaseDao;
import com.ssh.dao.impl.HibernateSessionFactory;
import com.ssh.dao.impl.UserDao;
import com.ssh.forms.UserForm;
import com.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.getSession(); 
        dao.setSession(session);
        // 獲取事務  
        Transaction ts = session.beginTransaction();  
        // 構造User物件  
        User user = new User();  
        user.setUserId(userForm.getUserId());
        user.setUsername(userForm.getUsername());  
        user.setPassword(userForm.getPassword());
        
        // 儲存User物件  
        dao.saveObject(user);  
        // 提交事務  
        ts.commit();  
        // 關閉Session  
        HibernateSessionFactory.closeSession();  
    }  
}
11,hibernate.cfg.xml(hibernate的住配置檔案)
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
        <property name="connection.username">使用者名稱</property>
        <property name="connection.password">密碼</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="show_sql">true</property>
        <mapping resource="com/ssh/beans/User.hbm.xml"/><!-- 配置資料表對映檔案 -->
    </session-factory>

</hibernate-configuration>
12,
<?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"></include>
<constant name="struts.devMode" value="true" /><!-- 開發模式 -->
    <package name="default"  extends="struts-default" namespace="/">
        <action name="login" class="com.ssh.action.LoginAction" method="execute">
            <result name="success">/welcome.jsp</result>
            <result name="error">/error.jsp</result>
            <result name="input">/input.jsp</result>
        </action>
    </package>
</struts>

13,web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	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_3_0.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
       <filter-name>struts2</filter-name>
       <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
   </filter>
   <filter-mapping>
       <filter-name>struts2</filter-name>
       <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

14,index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  <body>
   <s:form action="login" method="post">
    <s:label value="系統登陸"></s:label>
    <s:textfield name="user.username" label="賬號" />
    <s:password name="user.password" label="密碼" />
    <s:submit value="登入" />
   </s:form>
  </body>
</html>
15,error.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'success.jsp' starting page</title>
    
	<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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    error
  </body>
</html>
16,input.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  <body>
   <s:form action="login" method="post">
    <s:label value="系統再登陸"></s:label>
    <s:textfield name="user.username" label="賬號" />
    <s:password name="user.password" label="密碼" />
    <s:submit value="登入" />
   </s:form>
  </body>
</html>

17,welcome.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'success.jsp' starting page</title>
    
	<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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    successfully,歡迎${username}!
  </body>
</html>

這樣我們的struts+hibernate的實驗工程就OK了,下面我們執行一下如圖:

登陸到資料庫的資料:

4,下面我們再來外部載入spring報,參照struts包外部引入,這裡就不再重複了。引入的包是spring\libs下面除了javadoc和sources的所有包

引入完了。

整個工程的目錄如下圖:

  1. 將Spring內libs目錄下包含所有的jar包(不需要複製結尾為sources和javadoc的jar包)到SSHProject專案的lib目錄下。
  2. 編寫Spring的配置檔案applicationContext.xml。路徑:src目錄下,需要在web.xml配置context-param指定路徑,或者把該檔案放在WEB-INF下,跟web.xml同目錄。這裡由於Spring配置資料來源的需要,需要把Hibernate內lib/optional/c3p0下的c3p0-0.9.1.jar複製到lib不目下。
  3. 修改BaseDao和UserDao。在引入Spring後,需要用Spring進行統一的事務管理,資料來源和sessionFactory都交給Spring去生成,因此介面類和實現類BaseDao和UserDao都需要做相應的修改。Spring提供了HibernateDaoSupport類來完成對資料的操作,因此UserDao在實現BaseDao的同時還需要繼承HibernateDaoSupport類。並將先前session的操作修改成HibernateTemplate(可通過getHibernateTemplate()方法來獲得)的操作。
  4. 修改業務邏輯實現類。在沒有加入Spring之前,業務邏輯實現類的Session的獲得,dao的例項化,以及事務的管理都是該類執行管理的。加入Spring後,這些都交給Spring去管理。該類的dao的例項化由Spring注入。
  5. 修改使用者註冊的RegisterAction類。同樣,RegisterAction類中的userManager的例項化也由Spring注入。
  6. 刪除Hibernate的配置檔案Hibernate.cfg.xml和工廠類HibernateSesseionFactory類。他們的工作已經交給Spring去做,已經不再有用。
  7. 修改web.xml,載入Spring。要想啟動時載入Spring的配置檔案,需要在web.xml中配置對應的監聽器(listenser),並制定Spring的配置檔案。
  8. 修改Struts的配置檔案struts.xml。把原來指定的名為register的action的class由原來的路徑變為applicationContext.xml檔案中該Action的id。
  9. LoginAction.java如下,LoginAction-validation.xml沒有變化。
    package com.ssh.action;
    
    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.Preparable;
    import com.ssh.forms.UserForm;
    import com.ssh.service.UserManager;
    
    public class LoginAction extends ActionSupport implements Preparable{
    	//該類繼承了ActionSupport類。這樣就可以直接使用SUCCESS, LOGIN等變數和重寫execute等方法
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 724458459147961157L;
    	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;  
        }  
    
    	@Override
        public String execute() {
            try{
            	user.setUserId("2");
                userManager.regUser(user);
                return SUCCESS;
            }catch(Exception e){
            	e.printStackTrace();
            	return ERROR;
            }
    	}
    	//清除LoginAction-validation.xml爆出的錯誤資訊
    	public void prepare(){
    		clearErrorsAndMessages();
    	};
    }
    
  10. User.java如下:User.hbm.xml沒有變化
    package com.ssh.beans;
    
    public class User {
    	private String userId;
    	private String username;  
        private String password;  
        
        public String getUserId() {
    		return userId;
    	}
    	public void setUserId(String userId) {
    		this.userId = userId;
    	}
    	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;  
        }  
    }
    
  11. BaseDao.java
    package com.ssh.dao;
    import org.hibernate.HibernateException;  
    public interface  BaseDao {
    	/*
    	 *插入資料
    	 */
    	public void saveObject(Object obj) throws HibernateException;  
    //	public void selectObject(Object obj) throws HibernateException;  
    //	public void deleteObject(Object obj) throws HibernateException;
    //	public void updateObject(Object obj) throws HibernateException; 
    }
    
  12. UserDao.java
    package com.ssh.dao.impl;
    
    import org.hibernate.HibernateException;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    
    import com.ssh.dao.BaseDao;
    
    public class UserDao extends HibernateDaoSupport implements BaseDao{
        @Override  
        public void saveObject(Object obj) throws HibernateException {  
        	getHibernateTemplate().save(obj);
        }  
    //    @Override  
    //    public void select(Object obj) throws HibernateException {  
    //        session.save(obj);  
    //    } 
    }
    
  13. UserForm.java
    package com.ssh.forms;
    
    public class UserForm {
    	private String userId;
    	private String username;  
        private String password;  
        public String getUserId() {
    		return userId;
    	}
    	public void setUserId(String userId) {
    		this.userId = userId;
    	}
        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;  
        }  
    }
    
  14. UserManager.java
    package com.ssh.service;
    
    import com.ssh.forms.UserForm;
    
    public interface  UserManager {
    	public void regUser(UserForm user);  
    }
    
  15. UserManagerImpl.java
    package com.ssh.service.impl;
    
    import org.hibernate.HibernateException;
    import org.springframework.beans.BeanUtils;
    import com.ssh.beans.User;
    import com.ssh.dao.BaseDao;
    import com.ssh.forms.UserForm;
    import com.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 user = new User(); 
            BeanUtils.copyProperties(userForm,user);
            // 儲存User物件  
            dao.saveObject(user);  
        }  
    }
    
  16. 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"></include>
    <constant name="struts.devMode" value="true" /><!-- 開發模式 -->
        <package name="default"  extends="struts-default" namespace="/">
            <action name="login" class="loginAction" >
                <result name="success">/welcome.jsp</result>
                <result name="error">/error.jsp</result>
                <result name="input">/input.jsp</result>
            </action>
        </package>
    </struts>
  17. 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>oracle.jdbc.driver.OracleDriver</value>  
            </property>  
            <property name="jdbcUrl">  
                <value>jdbc:oracle:thin:@199.10.80.42:1521:orcl</value>  
            </property>  
            <property name="user">  
                <value>dm</value>  
            </property>  
            <property name="password">  
                <value>dm</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/ssh/beans/User.hbm.xml</value>  
                </list>  
            </property>  
            <property name="hibernateProperties">  
                <props>  
                    <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</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.ssh.dao.impl.UserDao">  
            <property name="sessionFactory">  
                <ref bean="sessionFactory" />  
            </property>  
        </bean>  
      
        <!--使用者註冊業務邏輯類 -->  
        <bean id="userManager" class="com.ssh.service.impl.UserManagerImpl">  
            <property name="dao">  
                <ref bean="baseDao" />  
            </property>  
        </bean>  
      
        <!-- 使用者註冊的Action -->  
        <bean id="loginAction" class="com.ssh.action.LoginAction">  
            <property name="userManager">  
                <ref bean="userManager" />  
            </property>  
        </bean>  
      
        <!-- more bean definitions go here -->  
      
    </beans>  
  18. web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.0" 
    	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_3_0.xsd">
      <display-name></display-name> 	
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <filter>
           <filter-name>struts2</filter-name>
           <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
       </filter>
       <filter-mapping>
           <filter-name>struts2</filter-name>
           <url-pattern>/*</url-pattern>
       </filter-mapping>
       <listener>  
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
       </listener> 
       <!-- 指定 applicationContext.xml的路徑
       <context-param>
    	   <param-name>applicationContext.xml</param-name>
    	   <param-value>applicationContext.xml</param-value>
       </context-param>
       -->
    </web-app>
    
  19. index.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <%@ taglib uri="/struts-tags" prefix="s" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
    	<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">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
      </head>
      <body>
       <s:form action="login" method="post">
        <s:label value="系統登陸"></s:label>
        <s:textfield name="user.username" label="賬號" />
        <s:password name="user.password" label="密碼" />
        <s:submit value="登入" />
       </s:form>
      </body>
    </html>
    
  20. input.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <%@ taglib uri="/struts-tags" prefix="s" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
    	<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">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
      </head>
      <body>
       <s:form action="login" method="post">
        <s:label value="系統再登陸"></s:label>
        <s:textfield name="user.username" label="賬號" />
        <s:password name="user.password" label="密碼" />
        <s:submit value="登入" />
       </s:form>
      </body>
    </html>
    
  21. welcome.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'success.jsp' starting page</title>
        
    	<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">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
    
      </head>
      
      <body>
        successfully,歡迎${user.username}!
      </body>
    </html>
    
  22. error.jsp未變
  23. 下面我們執行這個工程如圖:

  24. 資料庫截圖:
  25. 以上就大工告成了。