Struts 1.3 + Spring 3.2 + Hibernate 3.6 安裝筆記

王者歸來 Java Web 整合開發 (第二版)」小蛙以為買了這本書可以很快速的打通任督二脈,實際上也花了非常多的時間才把環境架起來,還是必須透過其他的書籍或是網路上的資料才足夠(附在本篇末的參考資料中),這邊粗略的記錄一下整個安裝流程,一直卡關鬱卒到極點,導致一些紀錄可能不那麼完整,正確性有待商榷,但至少在小蛙的環境裡是可以跑的,供參考囉!

  1. 下載 Struts, Spring, Hibernate

    Struts:http://struts.apache.org/download.cgi#struts1310
    Spring:http://www.springsource.org/node/3720
    Hibernate:http://www.hibernate.org/downloads

  2. 建立 Dynamic Web Project

    在 Eclipse 中的 File
    -> New -> Other…
    -> Web -> Dynamic Web Project
    -> 輸入完專案名稱後,Next
    -> 設定 Default output folder: WebContent/WEB-INF/classes
    -> Next -> Generate web.xml deployment descriptor 打勾
    -> Finish

  3. 設定Tomcat Context

    在 Tomcat 安裝目錄下/conf/ Server.xml 中設定剛剛的專案,把路徑改成自己的路徑,小蛙沒有把專案建立在 Tomcat 安裝目錄下的 webapps 中

    <Host name="localhost"  appBase="" unpackWARs="true" autoDeploy="true">
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
        <Context path="/" docBase="G:\spring\mvc\WebContent" reloadable="true" />
    </Host>
  4. 加入JSTL 1.2

    把 jstl-1.2.jar 放在 專案/WebContent/WEB-INF/lib 目錄下,才可以用以下 jstl 功能,之前查到很多像是要把 tld 放在哪哩,要下載一堆有的沒的檔案,後來發現其實從 JSTL 1.2  下載 javax.servlet.jsp.jstl-1.2.1.jar 跟 javax.servlet.jsp.jstl-api-1.2.1.jar 就可以了。在有使用到 JSTL 的頁面最上方加入宣告

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="xml" %>
  5. 設置JNDI

    在 Tomcat 安裝目錄/conf/context.xml 中加入

    <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
        maxActive="5" maxIdle="2" maxWait="60"
        username="your_account" password="your_password" driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://your_domain:3306/your_database?characterEncoding=UTF-8"/>

    小蛙之前不管設定在 server.xml 的 <GlobalNamingResources> 標籤中、設定在 <Host> 標籤下或是設定在 localhost/context.xml 下都會出現錯誤,所以就乾脆設定在上述路徑的 context.xml 中。如果用這個方法要把 mysql-connector-java-5.1.22-bin.jar 複製到 Tomcat安裝目錄/conf/ 資料夾下。可參考 Struts 1.3 + Spring 3.2 + Hibernate 3.6 錯誤筆記

  6. 在web.xml中加入外部資源設定

    網路上查到的資料是說要加入該設定,但小蛙沒加也沒有出錯,保險起見還是加上去吧!

    <description>MySQL Test App</description>
    <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/TestDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
  7. 加入並檢查必須的Jar檔

    小蛙的 lib 資料夾下包括以下檔案(省得有時候會有少 class 的麻煩 … 小蛙直接把所有的 jar 丟進去):

    antlr-2.7.2.jar                           bsf-2.3.0.jar
    commons-beanutils-1.8.0.jar               commons-chain-1.2.jar
    commons-digester-1.8.jar                  commons-fileupload-1.2.2.jar
    commons-io-2.4.jar                        commons-lang3-3.1.jar
    commons-logging-1.0.4.jar                 commons-validator-1.3.1.jar
    javax.servlet.jsp.jstl-1.2.1.jar          javax.servlet.jsp.jstl-api-1.2.1.jar
    mysql-connector-java-5.1.22-bin.jar       oro-2.0.8.jar
    spring-aop-3.2.0.M1.jar                   spring-asm-3.2.0.M1.jar
    spring-aspects-3.2.0.M1.jar               spring-beans-3.2.0.M1.jar
    spring-context-3.2.0.M1.jar               spring-context-support-3.2.0.M1.jar
    spring-core-3.2.0.M1.jar                  spring-expression-3.2.0.M1.jar
    spring-instrument-3.2.0.M1.jar            spring-instrument-tomcat-3.2.0.M1.jar
    spring-jdbc-3.2.0.M1.jar                  spring-jms-3.2.0.M1.jar
    spring-orm-3.2.0.M1.jar                   spring-oxm-3.2.0.M1.jar
    spring-struts-3.2.0.M1.jar                spring-test-3.2.0.M1.jar
    spring-tx-3.2.0.M1.jar                    spring-web-3.2.0.M1.jar
    spring-webmvc-3.2.0.M1.jar                spring-webmvc-portlet-3.2.0.M1.jar
    struts-core-1.3.10.jar                    struts-el-1.3.10.jar
    struts-extras-1.3.10.jar                  struts-faces-1.3.10.jar
    struts-mailreader-dao-1.3.10.jar          struts-scripting-1.3.10.jar
    struts-taglib-1.3.10.jar                  struts-tiles-1.3.10.jar
  8. 設定讓Struts接管*.do請求

    在 web.xml 加入註解的那段,其他原本的 web.xml 設定別動到。

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        <!-- Standard Action Servlet Configuration -->
        <servlet>
            <!-- 從這裡開始複製 -->
    	<servlet-name>action</servlet-name>
    	<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    	<init-param>
    		<param-name>config</param-name>
    		<param-value>/WEB-INF/struts-conf.xml</param-value>
    	</init-param>
    	<init-param>
    		<param-name>debug</param-name>
    		<param-value>3</param-value>
    	</init-param>
    	<init-param>
    		<param-name>detail</param-name>
    		<param-value>3</param-value>
    	</init-param>
    	<load-on-startup>0</load-on-startup>
        <!-- Standard Action Servlet Mapping -->
        <servlet-mapping>
            <servlet-name>action</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
        <!-- 複製到這裡 -->
        </servlet>
    </web-app>
  9. 新增struts-conf.xml

    在專案/WebContent/WEB-INF/ 下新增 struts-conf.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>
        <!-- 設定放在這邊 -->
    </struts-config>
  10. 測試.do轉向

    在 WebContent 下建立 index.jsp ,測試 Struts 是否能將正常做 .do 轉向。在 struts-conf.xml 中加入

    <action-mappings>
        <action path="/index" type="org.apache.struts.actions.ForwardAction" parameter="/index.jsp"></action>
    </action-mappings>

    重新啟動 Tomcat,試試看透過 htpp://localhost:8080/index.do 能不能正確轉向到設定的 index.jsp。

  11. 設定過濾器,解決中文亂碼-Tomcat預設過濾器 (跟 12. 選一個使用即可)

    在 tomcat 安裝目錄/conf/web.xml,找到下面這段,把它反註解(預設應該是被註解起來的)

    <filter>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <async-supported>true</async-supported>
    </filter>
    <filter-mapping>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  12. 設定過濾器,解決中文亂碼-Spring過濾器 (跟 11. 選一個使用即可)

    在 專案/WebContent/WEB-INF/web.xml 中加入

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  13. 新增spring-conf.xml

    在 專案/WebContent/WEB-INF/ 下新增 spring-conf.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"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    </beans>
  14. Spring接合Struts

    在 struts-conf.xml 加入 (有另外的方法是 Listener 這邊不提)

    <action-mappings>
        <action path="/hello2">
            <forward name="helloUser" path="/index.jsp"></forward>
        </action>
    </action-mappings>
    <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"></controller>
    <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
        <set-property value="/WEB-INF/spring-conf.xml" property="contextConfigLocation"/>
    </plug-in>

    在 spring-conf.xml 加入 (bean name 要跟上面的 action path 一致)
    (範例參考自良葛格學習筆記,userChecker 及 HelloAction 請參考 良葛格學習筆記)

    <bean id="userChecker" class="com.hans.pojo.UserChecker"></bean>
    <bean name="/hello2" class="com.hans.struts.action.HelloAction2">
        <property name="userChecker" ref="userChecker" />
    </bean>
  15. 測試使用代理方式與ActionForm

    index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
    <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
    <!DOCTYPE html>
    <html lang="zh-TW">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Login</title>
    </head>
    <body>
    	<html:form action="/login">
    		<html:text property="username"></html:text><br />
    		<html:password property="password"></html:password><br />
    		<html:submit>送出</html:submit> <html:reset>清除</html:reset>
    	</html:form>
    </body>
    </html>

    LoginForm.java

    import javax.servlet.http.HttpServletRequest;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionMapping;
    public class LoginForm extends ActionForm {
    	private String username;
    	private String password;
    	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;
    	}
    	@Override
    	public void reset(ActionMapping mapping, HttpServletRequest request) {
    		username = null;
    		password = null;
    	}
    }

    LoginAction.java

    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.hans.struts.action.form.LoginForm;
    public class LoginAction extends Action {
    	@Override
    	public ActionForward execute(ActionMapping mapping, ActionForm form,
    			HttpServletRequest request, HttpServletResponse response)
    			throws Exception {
    		LoginForm loginForm = (LoginForm)form;
    		if("hans".equals(loginForm.getUsername()) && "123456".equals(loginForm.getPassword())){
    			return mapping.findForward("success");
    		}
    		return mapping.findForward("error");
    	}
    }

    struts-conf.xml 加上

    <!-- 這行沒加會一直提醒找不到 /login -->
    <form-beans>
        <form-bean name="LoginForm" type="com.hans.struts.action.form.LoginForm"></form-bean>
    </form-beans>
    <action-mappings>
        <action path="/index" type="org.apache.struts.actions.ForwardAction" parameter="/index.jsp"></action>
        <!-- scope 要寫 -->
        <action path="/login" name="LoginForm" scope="request">
    	<forward name="success" path="/WEB-INF/pages/login_success.jsp"></forward>
    	<forward name="error" path="/index.do" redirect="true"></forward>
        </action>
    </action-mappings>

    spring-conf.xml

    <bean name="/login" class="com.hans.struts.action.LoginAction"></bean>
  16. 加入Hibernate

    小蛙的 lib 下包含

    antlr-2.7.6.jar                            bsf-2.3.0.jar
    c3p0-0.9.1.jar                             commons-beanutils-1.8.0.jar
    commons-chain-1.2.jar                      commons-collections-3.1.jar
    commons-digester-1.8.jar                   commons-fileupload-1.2.2.jar
    commons-io-2.4.jar                         commons-lang3-3.1.jar
    commons-logging-1.0.4.jar                  commons-validator-1.3.1.jar
    dom4j-1.6.1.jar                            hibernate-jpa-2.0-api-1.0.1.Final.jar
    hibernate3.jar                             javassist-3.12.0.GA.jar
    javax.servlet.jsp.jstl-1.2.1.jar           javax.servlet.jsp.jstl-api-1.2.1.jar
    jta-1.1.jar                                mysql-connector-java-5.1.22-bin.jar
    oro-2.0.8.jar                              slf4j-api-1.6.1.jar
    spring-aop-3.2.0.M1.jar                    spring-asm-3.2.0.M1.jar
    spring-aspects-3.2.0.M1.jar                spring-beans-3.2.0.M1.jar
    spring-context-3.2.0.M1.jar                spring-context-support-3.2.0.M1.jar
    spring-core-3.2.0.M1.jar                   spring-expression-3.2.0.M1.jar
    spring-instrument-3.2.0.M1.jar             spring-instrument-tomcat-3.2.0.M1.jar
    spring-jdbc-3.2.0.M1.jar                   spring-jms-3.2.0.M1.jar
    spring-orm-3.2.0.M1.jar                    spring-oxm-3.2.0.M1.jar
    spring-struts-3.2.0.M1.jar                 spring-test-3.2.0.M1.jar
    spring-tx-3.2.0.M1.jar                     spring-web-3.2.0.M1.jar
    spring-webmvc-3.2.0.M1.jar                 spring-webmvc-portlet-3.2.0.M1.jar
    standard-1.0.6.jar                         struts-core-1.3.10.jar
    struts-el-1.3.10.jar                       struts-extras-1.3.10.jar
    struts-faces-1.3.10.jar                    struts-mailreader-dao-1.3.10.jar
    struts-scripting-1.3.10.jar                struts-taglib-1.3.10.jar
    struts-tiles-1.3.10.jar
  17. 設定Hibernate環境

    這邊討厭鬼的這篇文章 – Struts2+Spring+Hibernate架構配置教學(Hibernate)上 @ 討厭鬼教學 寫的非常清楚。

  18. 測試Hibernate

    先建立一個資料庫環境,資料表隨便設定(不一定要照小蛙的,可以越簡單越好,只要有id, m_id, email, name就好),note: 這只是一個很無聊的範例,確定一下 Hibernate, Struts, Spring 是否三者已經可以結合使用。小蛙自己的 table 為

    CREATE TABLE IF NOT EXISTS `member` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `m_id` varchar(50) DEFAULT NULL,
      `name` varchar(20) DEFAULT NULL,
      `gender` char(1) DEFAULT NULL,
      `email` varchar(50) NOT NULL,
      `cdate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
      `oriPlace` varchar(30) DEFAULT NULL,
      `nowPlace` varchar(30) DEFAULT NULL,
      `birthday` date DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `m_id` (`m_id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

    index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
    <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
    <!DOCTYPE html>
    <html lang="zh-TW">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Login</title>
    </head>
    <body>
    	<html:form action="/login">
    		<html:text property="username"></html:text><br />
    		<html:password property="password"></html:password><br />
    		<html:submit>送出</html:submit> <html:reset>清除</html:reset>
    	</html:form>
    </body>
    </html>

    LoginAction.java

    package com.hans.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.hans.dao.IMemberDao;
    import com.hans.entity.Member;
    import com.hans.struts.action.form.LoginForm;
    public class LoginAction extends Action {
    	private IMemberDao dao;
    	@Override
    	public ActionForward execute(ActionMapping mapping, ActionForm form,
    			HttpServletRequest request, HttpServletResponse response)
    			throws Exception {
    		LoginForm loginForm = (LoginForm)form;
    		if("search".equals(loginForm.getUsername())){
    			// 如果是 search 就取出第一筆資料的 mid
    			Member m = dao.find(1);
    			if(m != null)
    				request.setAttribute("ID", m.getMId());
    			return mapping.findForward("success");
    		}else if("add".equals(loginForm.getUsername())){
    			// 如果是 add,就新增一筆 abc, [email protected] 的資料
    			Member m = new Member();
    			m.setEmail("[email protected]");
    			m.setName("abc");
    			dao.insert(m);
    			request.setAttribute("ID", "新增完成");
    			return mapping.findForward("success");
    		}
    		return mapping.findForward("error");
    	}
    	public IMemberDao getDao() {
    		return dao;
    	}
    	public void setDao(IMemberDao dao) {
    		this.dao = dao;
    	}
    }

    IMemberDao.java

    package com.hans.dao;
    import com.hans.entity.Member;
    public interface IMemberDao {
    	public void insert(Member member);
    	public Member find(Integer id);
    }

    Member.java (這個是 Hibernate Tool 直接透過資料庫產生的)

    package com.hans.entity;
    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import static javax.persistence.GenerationType.IDENTITY;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
    /**
     * Member generated by hbm2java
     */
    @Entity
    @Table(name = "member", catalog = "letsgo")
    public class Member implements java.io.Serializable {
    	private Integer id;
    	private String MId;
    	private String name;
    	private Character gender;
    	private String email;
    	private Date cdate;
    	private String oriPlace;
    	private String nowPlace;
    	private Date birthday;
    	public Member() {
    	}
    	public Member(String email) {
    		this.email = email;
    	}
    	public Member(String MId, String name, Character gender, String email,
    			Date cdate, String oriPlace, String nowPlace, Date birthday) {
    		this.MId = MId;
    		this.name = name;
    		this.gender = gender;
    		this.email = email;
    		this.cdate = cdate;
    		this.oriPlace = oriPlace;
    		this.nowPlace = nowPlace;
    		this.birthday = birthday;
    	}
    	@Id
    	@GeneratedValue(strategy = IDENTITY)
    	@Column(name = "id", unique = true, nullable = false)
    	public Integer getId() {
    		return this.id;
    	}
    	public void setId(Integer id) {
    		this.id = id;
    	}
    	@Column(name = "m_id", length = 50)
    	public String getMId() {
    		return this.MId;
    	}
    	public void setMId(String MId) {
    		this.MId = MId;
    	}
    	@Column(name = "name", length = 20)
    	public String getName() {
    		return this.name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	@Column(name = "gender", length = 1)
    	public Character getGender() {
    		return this.gender;
    	}
    	public void setGender(Character gender) {
    		this.gender = gender;
    	}
    	@Column(name = "email", nullable = false, length = 50)
    	public String getEmail() {
    		return this.email;
    	}
    	public void setEmail(String email) {
    		this.email = email;
    	}
    	@Temporal(TemporalType.TIMESTAMP)
    	@Column(name = "cdate", length = 19)
    	public Date getCdate() {
    		return this.cdate;
    	}
    	public void setCdate(Date cdate) {
    		this.cdate = cdate;
    	}
    	@Column(name = "oriPlace", length = 30)
    	public String getOriPlace() {
    		return this.oriPlace;
    	}
    	public void setOriPlace(String oriPlace) {
    		this.oriPlace = oriPlace;
    	}
    	@Column(name = "nowPlace", length = 30)
    	public String getNowPlace() {
    		return this.nowPlace;
    	}
    	public void setNowPlace(String nowPlace) {
    		this.nowPlace = nowPlace;
    	}
    	@Temporal(TemporalType.DATE)
    	@Column(name = "birthday", length = 10)
    	public Date getBirthday() {
    		return this.birthday;
    	}
    	public void setBirthday(Date birthday) {
    		this.birthday = birthday;
    	}
    }

    MemberDao.java

    package com.hans.dao;
    import java.util.List;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    import com.hans.entity.Member;
    public class MemberDao extends HibernateDaoSupport implements IMemberDao {
    	@Override
    	public void insert(Member member) {
    		this.getHibernateTemplate().persist(member);
    	}
    	@Override
    	public Member find(Integer id) {
    		List<Member> list = this.getHibernateTemplate().find("from Member");
    		if(list.size() > 0)
    			return list.get(0);
    		return null;
    	}
    }

    login_success.xml (放在 WEB-INF/pages/ 下)

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html lang="zh-TW">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Login Success</title>
    </head>
    <body>
    <%=request.getAttribute("ID") %>
    </body>
    </html>

    struts-conf.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>
        <form-beans>
            <form-bean name="LoginForm" type="com.hans.struts.action.form.LoginForm"></form-bean>
        </form-beans>
    	<action-mappings>
                    <!-- 直接轉 -->
    		<action path="/index" type="org.apache.struts.actions.ForwardAction" parameter="/index.jsp"></action>
                    <!-- 設定路徑, form-bean, scope 及轉向 -->
    		<action path="/login" name="LoginForm" scope="request">
    		    <forward name="success" path="/WEB-INF/pages/login_success.jsp"></forward>
    		    <forward name="error" path="/index.do" redirect="true"></forward>
    		</action>
    	</action-mappings>
    	<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"></controller>
    	<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
    		<set-property value="/WEB-INF/spring-conf.xml" property="contextConfigLocation"/>
    	</plug-in>
    </struts-config>

    spring-conf.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"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
            <!-- 當使用者送出表單到 /login.do 後,注入 dao,該 dao 參考到最下面設定的 memberDao -->
    	<bean name="/login" class="com.hans.struts.action.LoginAction">
    	    <property name="dao" ref="memberDao"></property>
    	</bean>
    	<!-- 吃 tomcat 內部設定的 jndi 不然就要自己設定 -->
    	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
                <property name="jndiName" value="java:comp/env/jdbc/TestDB"></property>
    	</bean>
    	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    	    <property name="dataSource" ref="dataSource"></property>
    	    <property name="annotatedClasses">
    	        <list>
    	            <value>com.hans.entity.Member</value>
    	        </list>
    	    </property>
    	    <property name="hibernateProperties">
    	        <props>
    	            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
    	            <prop key="hibernate.format_sql">true</prop>
    	            <prop key="hibernate.show_sql">true</prop>
    	        </props>
    	    </property>
    	</bean>
    	<bean id="memberDao" class="com.hans.dao.MemberDao">
    	    <property name="sessionFactory" ref="sessionFactory"></property>
    	</bean>
        <context:annotation-config/>
    </beans>

    當使用者在 index.do 表單輸入 search,則列出資料表第一筆資料的 m_id,若輸入 add,則新增一筆 email 為 [email protected] 且 name 為 abc 的資料,執行的結果可以自行到資料庫中查看。

到這邊已經把整個基本入門的環境架起來了,剩下的 … 要加油囉!說起來慚愧,小蛙總共花了 2 個星期才把環境及 Struts, Spring, Hibernate 串聯起來(還不太會使用喔) … 希望之後越來越順手!!!!過程中有發生錯誤情況,可參考 Struts 1.3 + Spring 3.2 + Hibernate 3.6 錯誤筆記 @ 蛙齋,Good Luck!!!
參考資料:

  1. 程式設計SSH分類 @ 討厭鬼教學
    http://nerdyworld.pixnet.net/blog/category/429960
  2. JSP Standard Tag Library
    http://jstl.java.net/download.html
  3. Struts @ The Apache Software Foundation
    http://struts.apache.org/download.cgi#struts1310
  4. Spring @ SpringSource Community
    http://www.springsource.org/node/3720
  5. Hibernate @ JBoss Community
    http://wazai.net/2306
  6. Struts 1.3 + Spring 3.2 + Hibernate 3.6 錯誤筆記 @ 蛙齋
    http://wazai.net/2418/struts-1-3-spring-3-2-hibernate-3-6-錯誤筆記
  7. Spring Gossip: 在 Struts 中整合 Spring @ 良葛格學習筆記
    http://caterpillar.onlyfun.net/Gossip/SpringGossip/StrutsSpring.html

    發佈留言

    發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

    這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料