首先要去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;
}
}
HibernateUtil.java是建立起專案與DataBase連結的部份
※撰寫 MemberAction.java
package Action;
import model.Member;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import DAO.MemberManager;
public class MemberAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private Member Member;
private List<Member> memberList;
private Long id;
private MemberManager linkController;
public MemberAction(){
this.linkController = new MemberManager();
}
@Override
public String execute() throws Exception {
this.memberList = linkController.list();
return SUCCESS;
}
public String list(){
this.memberList =linkController.list();
return SUCCESS;
}
public String detail(){
this.Member =linkController.detail(getId());
return SUCCESS;
}
public String add(){
System.out.println(getMember());
try{
linkController.add(getMember());
}catch(Exception e){
e.printStackTrace();
}
// return SUCCESS;
return "list";
}
public String update(){
linkController.update(getMember());
return SUCCESS;
}
public String delete(){
linkController.delete(getId());
return SUCCESS;
}
public Member getMember() {
return Member;
}
public void setMember(Member Member) {
this.Member = Member;
}
public List<Member> getMemberList() {
return memberList;
}
public void setMemberList(List<Member> MemberList) {
this.memberList = MemberList;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
MemberAction.java 是屬於整個專案的中央控制,透過MemberManager.java與DataBase連結資料
※撰寫 MemberManager.java
package DAO;
import model.Member;
import util.HibernatetUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
public class MemberManager extends HibernatetUtil {
public Member add(Member Member){
Session session = HibernatetUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(Member);
session.getTransaction().commit();
return Member;
}
public Member delete(Long id){
Session session = HibernatetUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Member Member = (Member) session.load(Member.class, id);
if(null != Member){
session.delete(Member);
}
session.getTransaction().commit();
return Member;
}
public List list(){
Session session = HibernatetUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<Member> memberList = null;
try{
memberList = session.createQuery("from Member").list();
}catch(HibernateException e){
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return memberList;
}
public Member detail(Long id){
Session session = HibernatetUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Member Member = (Member) session.load(Member.class, id);
System.out.println("傳回來的使用者為: " + Member.getName());//若不加這一行,則detail.jsp僅顯示id,尚未找到解決方式 2013/05/17
session.getTransaction().commit();
return Member;
}
public void update(Member Member){
Session session = HibernatetUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.update(Member);
session.getTransaction().commit();
}
}
※撰寫addUser.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=BIG5">
<title>Insert title here</title>
</head>
<body>
<s:form action="add">
<s:textfield name="member.name" label="姓名" />
<s:radio name="member.gender" label="性別" list="genders" />
<s:textfield name="member.bday" label="生日"/>
<s:checkbox name="member.over20" label="已成年"/>
<s:checkboxlist name="member.kobby" label="興趣" list="kobby" />
<s:select name="member.grade" label="學歷" list="grade" />
<s:submit value="註冊"/>
</s:form>
<a href="<s:url action='list'/>">列出所有會員</a>
</body>
</html>
addUser.jsp中嚐試使用了Struts中的各種Form
※撰寫show.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>Show Record</title>
</head>
<body>
<h1>Struts2 Hibernate Example</h1>
<h3>Show Records</h3>
<s:actionerror/>
<h2>Records</h2>
<table id="contact" border="1">
<tr>
<th>Name</th>
<th>gender</th>
<th>bday</th>
<th>over20</th>
<th>kobby</th>
<th>grade</th>
<th>Delete</th>
<th>Update</th>
</tr>
<s:iterator value="memberList">
<tr>
<td><s:property value="Name" /></td>
<td><s:property value="gender" /></td>
<td><s:property value="bday" /></td>
<td><s:property value="over20"/></td>
<td><s:property value="kobby"/></td>
<td><s:property value="grade"/></td>
<td><a href="delete.action?id=<s:property value="id" />">delete</a></td>
<td><a href="detail.action?id=<s:property value="id" />">detail</a></td>
</tr>
</s:iterator>
</table>
</body>
</html>
※撰寫 detail.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#member{
border-collapse: collapse;
width:550px;
}
th{
height: 40px;
background-color: @AAB6B3;
}
</style>
<title>Show Detail</title>
</head>
<body>
<h1>Struts2 Hibernate4 練習</h1>
<h3>更新資料</h3>
<s:actionerror/>
<s:form action="update" method="post" >
<s:textfield name="member.id" value="%{member.id}" readonly="true"/>
<s:textfield name="member.Name" value="%{member.name}" label="Name"/>
<s:textfield name="member.gender" value="%{member.gender}" label="gender" />
<s:textfield name="member.bday" value="%{member.bday}" label="bday"/>
<s:textfield name="member.over20" value="%{member.over20}" label="over20"/>
<s:textfield name="member.kobby" value="%{member.kobby}" label="kobby"/>
<s:textfield name="member.grade" value="%{member.grade}" label="grade" />
<s:submit value="Update member" align="center"/>
</s:form>
</body></html>
The Casino of the Immortal: The Immortal - DrmCD
回覆刪除› music › hd › music › hd Buy The Casino 김제 출장샵 of the Immortal: 통영 출장마사지 The Immortal. Drmcd has 의왕 출장마사지 released a new album called 여주 출장샵 The Immortal: The Immortal: The Immortal by the 남양주 출장마사지 band of Immortal.