2013年8月25日 星期日

Hibernate程式練習

這次要練習Struts form的表單以及Hibernate

首先要去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連結的部份


2013年8月20日 星期二

簡單的用struts2框架做一個 Hello World 練習網站


※Struts2基礎練習(Hello Struts)


在這一篇中會帶領大家建置簡單的Struts架構網站,主要是要讓各位了解Struts的架構


在建立專案時,我們會需要用到一些Struts的jar檔,所以要到Struts的官網http://struts.apache.org/download.cgi#struts2320下載


Eclipse和JDK的部份,在另一個網誌中有整個環境的配置方式,在這就不多說了(傳送門

我們到tomcat的官網http://tomcat.apache.org/download-70.cgi下載我們所需要東西,這次我們下載的是核心的版本,你可以斟酌選擇自己需要的版本下載即可


下載後我們隨便找一個磁碟區將tomcat放進去,然後打開eclipse進行環境設置

首先,我們開一個Dynamic Web Project,專案名稱設置為Hello Struts2,容器的部份,點選New Runtime後,將路徑指向剛下載好的tomcat資料夾,以及jre的版本

-------------------------------------------------------------------------------------------------------------------------

最後請再次確認你的系統環境變數

Server(伺服器):apache-tomcat-7.0.26

環境:JDK7、Struts2

-------------------------------------------------------------------------------------------------------------------------

※Struts2 : Hello World 練習


開始之前,請將系統架構建置完成,並且將本次練習會用到的jar檔放到lib中




完成了前置作業,可以開始來撰寫程式部份

下面會解說每一程式在Struts2中扮演的角色


2013年8月14日 星期三

建立與資料庫的連結

建立與資料庫的連結

一、下載mysql-connector-java-*.jar的檔案後放入專案的lib中

備用檔案

二、註冊與連結資料庫

註冊資料庫
Class.forName("com.mysql.jdbc.Driver")

登入資料庫
String url = "jdbc:mysql://localhost:3306/資料庫名稱";
String user = "使用都名稱";
String password = "輸入你的密碼"
Connection conn = DriverManager.getConnection(url,user,password)

三、與資料庫連結

參考mysql指令MySQL指令

四、建立連結(敘述)

Connection conn =DriverManager.getConnection(url, user, password);
Statement stmt =  conn.createStatement();

五、JDBC與SQL基礎指令

1.建立一個新的資料表
            建立資料庫:stmt.executeUpdate("CREATE DATABASE 建立的資料庫名稱")
            建立資料表:stmt.executeUpdate("CREATE TABLE 建立的資料表名稱")
           
            若希望數據不重覆可設定為主鍵
            1.宣告資料型態
            2.指定為主鍵 PRIMARY KEY(ID)

2.加入值
           stmt.execute("INSERT INTO 資料表 VALUES('欄位ID = 值')");

3.查詢
           ResultSet result = stmt.executeQuery("SELECT * FROM 資料表");

4.列出
           while(result.next()){
                        System.out.print(result.getString("欄位ID"));
                        System.out.println(result.getString("name"));

5.插入數據
            stmt.execute("INSERT INTO 資料表 VALUES('"+變數+"')");

6.刪除
            stmt.executeUpdate("DELETE FROM 資料表 WHERE 欄位");

7.修改
           stmt.execteUpdate("UPDATE 資料表 SET 要修改的欄位 WHERE 參考的位址);

P.S

參考網站

1. PRIMARY KEY的資料型態要是not null

2.雙引號("")中間要用單引號('')

3.SELECT *的*是代表列出所有數據

4.若值為變數要用"(+變數+)"把變數串起

5.WHERE是指定那一筆資料
zh-CN → zh
位址