首先要去http://download.jboss.org/jbosstools/updates/stable/helios/下載 Hibernate tools
最後的helios是你eclips的版本,下載前要先確認版本是否正確
在eclips中Help” >> “Install New Software後輸入下載位址後點選Hibernate tools
版本:struts-2.3.14-all + hibernate-release-4.2.1.Final
專案結構:
※編輯web.xml
解開struts2壓縮檔,在 apps 資料夾內有一個 struts2-blank.war ,解開後可以在 WEB-INF 下找到一個 web.xml ,修改成下列內容(注意:<filter-class>要改成 StrutsPrepareAndExecuteFilter )。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID"
version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" >
<display-name>struts2 hibernate4 CRUD </display-name>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
※撰寫 index.jsp
<%@ page language="java" contentType="text/html; charset=BIG5"
pageEncoding="BIG5"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
body,input {
font-family: Calibri, Arial;
}
table#contact {
border-collapse: collapse;
width: 550px;
}
th {
height: 40px;
background-color: @AAB6B3;
}
</style>
<title>歡迎</title>
</head>
<body>
<h1>Struts2 Hibernate4 Form練習</h1>
<h3>進入首頁</h3>
<s:actionerror />
<p>
<a href="<s:url action='addUser'/>">註冊</a>
</p>
</body>
</html>
index只將路徑指向struts.xml中的addUser
※撰寫 struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" namespace="/" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="addUser" class="Action.Register" method="execute">
<result name="success">/addUser.jsp</result>
</action>
<action name="add" class="Action.MemberAction" method="add">
<result name="success">/show.jsp</result>
<result name="list" type="chain">list</result>
</action>
<action name="list" class="Action.MemberAction" method="list">
<result name="success">/show.jsp</result>
</action>
<action name="delete" class="Action.MemberAction" method="delete">
<result name="success" type="chain">list</result>
</action>
<action name="detail" class="Action.MemberAction" method="detail">
<result name="success">/detail.jsp</result>
</action>
<action name="update" class="Action.MemberAction" method="update">
<result name="success" type="chain">list</result>
</action>
</package>
</struts>
struts.xml是dynamic web project的核心
程式在執行前會先來確定struts.xml中
所有路徑都有找到物件
※撰寫 Member.java
- 建立 Contact.java ,輸入各項靜態屬性後,用eclipse 產生 getter 和 setter(右鍵/source/Generate Getters and Setters )
- 加入 hibernate annotation (注意欄位對應是寫在 getter 前)
package model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Member")
public class Member implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String gender;
private String bday;
private boolean over20;
private String kobby;
private String grade;
@Id
@GeneratedValue
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "gender")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Column(name = "bday")
public String getBday() {
return bday;
}
public void setBday(String bday) {
this.bday = bday;
}
@Column(name = "over20")
public boolean isOver20() {
return over20;
}
public void setOver20(boolean over20) {
this.over20 = over20;
}
@Column(name = "kobby")
public String getKobby() {
return kobby;
}
public void setKobby(String kobby) {
this.kobby = kobby;
}
@Column(name = "grade")
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
※使用Hibernate Tools 產生 Member.hbm.xml
- 在 model package 圖示上按右鍵/new/other/Hibernate/Hibernate XML Mapping file(hbm.xml)/Next>/Add Package/將 model 選入/Next>/Class name 選 Contact/Finish
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2013/5/15 ?W?? 08:44:24 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="model.Contact" table="CONTACT">
<id name="id" type="java.lang.Long">
<column name="ID" />
<generator class="increment" />
</id>
<property name="firstName" type="java.lang.String">
<column name="FIRSTNAME" />
</property>
<property name="lastName" type="java.lang.String">
<column name="LASTNAME" />
</property>
<property name="emailId" type="java.lang.String">
<column name="EMAILID" />
</property>
<property name="cellNo" type="java.lang.String">
<column name="CELLNO" />
</property>
<property name="birthDate" type="java.sql.Date">
<column name="BIRTHDATE" />
</property>
<property name="website" type="java.lang.String">
<column name="WEBSITE" />
</property>
<property name="created" type="java.sql.Date">
<column name="CREATED" />
</property>
</class>
</hibernate-mapping>
※在 src 下建立 source folder 命名為 resources
※使用Hibernate Tools 產生 hibernate.cfg.xml,並修改如下:
<?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">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.password">修改為您的密碼</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</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.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 class="model.Member" />
</session-factory>
</hibernate-configuration>
※撰寫 Register.java
package Action;
import javax.xml.crypto.Data;
import model.Member;
import com.opensymphony.xwork2.ActionSupport;
public class Register extends ActionSupport {
private static final long serialVersionUID = 1L;
private Member member;
private String[] genders = {"man", "feman", "unknow"};
private String[] kobby = {"a","b","c","d"};
private String name;
private Data bday;
private boolean over20;
private String[] grade = {"小學","初中","高中","大學","研究所"};
@Override
public String execute() throws Exception {
member = new Member();
return SUCCESS;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
public String[] getGenders() {
return genders;
}
public void setGenders(String[] genders) {
this.genders = genders;
}
public String[] getKobby() {
return kobby;
}
public void setKobby(String[] kobby) {
this.kobby = kobby;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Data getBday() {
return bday;
}
public void setBday(Data bday) {
this.bday = bday;
}
public boolean isOver20() {
return over20;
}
public void setOver20(boolean over20) {
this.over20 = over20;
}
public String[] getGrade() {
return grade;
}
public void setGrade(String[] grade) {
this.grade = grade;
}
}
Register.java是將addUser.jsp中的所有Form需要用到的靜態變數設計好,之後內容有什麼需要改的話直接在這個地方修正就可以了
※撰寫 HibernateUtil.java
package util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernatetUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
Configuration configuration = new Configuration();
configuration = configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}