Struts和Hibernate的簡單示例

最近給一個很是好學卻找不到方向的朋友講struts和hibernate框架的基礎入門,忽然發現本身對這兩個框架有些生疏了。這一年來的工做中都沒有使用過struts和hibernate作開發,因此在給他講解的同時也是本身複習和加深印象的過程,有些技術細節確實須要用心記憶。
今天去面試,收穫了3點感想:javascript

  1. 在學習技術的過程當中,博學是好事,但專精更加劇要。
  2. 不要過於依賴搜索引擎和API手冊,這樣會使本身對任何事情都拿不許主意,老是模棱兩可,並且會養成惰性,養成不肯意記憶的壞毛病。
  3. 增強對技術細節的掌握,只有對技術細節有着精準的掌握以後再在此基礎上進行更高層次的擴展和延伸,才能成爲一個優秀的架構師。

下面把給朋友講的struts和hibernate框架的基本使用的代碼貼上來,主要是貼代碼,須要注意的地方會另外文字說明。
參考了北大青鳥的教材《開發基於Struts/Spring/Hibernate/Ajax的網上信息發佈平臺》一書中的示例項目,在此我作了精簡。
主要功能就是會員登錄、註冊,還對有房屋信息的CRUD操做。css

須要用的lib有這些:html

antlr-2.7.6.jar
c3p0-0.9.1.jar
commons-beanutils.jar
commons-collections-3.1.jar
commons-digester.jar
commons-fileupload.jar
commons-logging.jar
commons-validator.jar
dom4j-1.6.1.jar
hibernate3.jar
jakarta-oro.jar
javassist-3.9.0.GA.jar
jta-1.1.jar
log4j-1.2.15.jar
mysql-connector-java-5.0.4-bin.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.5.6.jar
struts.jarjava

數據庫SQL腳本(MySQL):mysql

CREATE DATABASE IF NOT EXISTS house DEFAULT CHARACTER SET = 'utf8';
USE house;

CREATE TABLE IF NOT EXISTS member
(
    id INT UNSIGNED AUTO_INCREMENT NOT NULL,
    login_id VARCHAR(32) NOT NULL,
    login_pwd VARCHAR(32) NOT NULL,
    PRIMARY KEY (id)
) ENGINE = 'InnoDB' CHARACTER SET 'utf8';

CREATE TABLE IF NOT EXISTS house_type
(
    id INT UNSIGNED AUTO_INCREMENT NOT NULL,
    type_name VARCHAR(32) NOT NULL,
    PRIMARY KEY (id)
) ENGINE = 'InnoDB' CHARACTER SET = 'utf8';

CREATE TABLE IF NOT EXISTS house_info
(
    id INT UNSIGNED AUTO_INCREMENT NOT NULL,
    member_id INT UNSIGNED NOT NULL,
    type_id INT UNSIGNED NOT NULL,
    living_room INT UNSIGNED NOT NULL,
    bedroom INT UNSIGNED NOT NULL,
    information VARCHAR(500) NOT NULL,
    rent DECIMAL(10, 4) NOT NULL,
    title VARCHAR(200) NOT NULL,
    post_date DATETIME NOT NULL,
    telephone VARCHAR(11) NOT NULL,
    real_name VARCHAR(20) NOT NULL,
    PRIMARY KEY (id),
    FOREIGN KEY (member_id) REFERENCES member(id),
    FOREIGN KEY (type_id) REFERENCES house_type(id)
) ENGINE = 'InnoDB' CHARACTER SET 'utf8';

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="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">
        <![CDATA[
            jdbc:mysql://127.0.0.1/house?useUnicode=true&characterEncoding=utf-8
        ]]>
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="c3p0.min_size">5</property>
        <property name="c3p0.max_size">20</property>
        <property name="c3p0.timeout">300</property>
        <property name="c3p0.max_statements">50</property>
        <property name="c3p0.idle_test_period">3000</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>

        <mapping resource="com/house/entity/HouseInfo.hbm.xml" />
        <mapping resource="com/house/entity/HouseType.hbm.xml" />
        <mapping resource="com/house/entity/Member.hbm.xml" />
    </session-factory>
</hibernate-configuration>

Hibernate的SessionFactory工具類,代碼來自《Hibernate實戰 第2版 (Java Persistence with Hibernate)》:sql

package com.house.util;

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

public class HibernateUtil {

    private static SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}

下面是HouseInfo.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.house.entity">
    <class name="HouseInfo" table="house_info">
        <id name="id" column="id" type="integer">
            <generator class="identity" />
        </id>
        <property name="livingRoom" column="living_room" not-null="true"
            type="integer" />
        <property name="bedroom" column="bedroom" not-null="true"
            type="integer" />
        <property name="information" column="information" not-null="true"
            type="string" />
        <property name="rent" column="rent" not-null="true" type="big_decimal" />
        <property name="title" column="title" not-null="true" type="string" />
        <property name="postDate" column="post_date" not-null="true"
            type="date" />
        <property name="telephone" column="telephone" not-null="true"
            type="string" />
        <property name="realName" column="real_name" not-null="true"
            type="string" />

        <many-to-one name="member" column="member_id" not-null="true"
            class="Member" lazy="false" />
        <many-to-one name="houseType" column="type_id" not-null="true"
            class="HouseType" lazy="false" />
    </class>
</hibernate-mapping>

InitUpdateAction代碼,這步是更新初始化的操做。
咱們須要先進行查詢將值放入其對應的form中,而後JSP頁面中就可使用struts標籤來顯示form中的值。apache

package com.house.action.house;

import java.util.List;
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.house.dao.HouseInfoDao;
import com.house.dao.HouseTypeDao;
import com.house.entity.HouseInfo;
import com.house.entity.HouseType;
import com.house.form.UpdateHouseForm;

public class InitUpdateAction extends Action {

    private HouseInfoDao houseInfoDao;
    private HouseTypeDao houseTypeDao;

    public InitUpdateAction() {
        houseInfoDao = new HouseInfoDao();
        houseTypeDao = new HouseTypeDao();
    }

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Integer id = Integer.valueOf(request.getParameter("id"));
        // initialize houseInfo
        HouseInfo houseInfo = houseInfoDao.searchHouseInfo(id);
        UpdateHouseForm updateHouseForm = (UpdateHouseForm) form;
        // initialize houseInfo form
        updateHouseForm.setId(id);
        updateHouseForm.setMember(houseInfo.getMember());
        updateHouseForm.setHouseType(houseInfo.getHouseType());
        updateHouseForm.setLivingRoom(houseInfo.getLivingRoom());
        updateHouseForm.setBedroom(houseInfo.getBedroom());
        updateHouseForm.setInformation(houseInfo.getInformation());
        updateHouseForm.setRent(houseInfo.getRent());
        updateHouseForm.setTitle(houseInfo.getTitle());
        updateHouseForm.setTelephone(houseInfo.getTelephone());
        updateHouseForm.setRealName(houseInfo.getRealName());
        // initialize houseType
        List<HouseType> houseTypeList = houseTypeDao.searchAllHouseType();
        request.setAttribute("houseTypeList", houseTypeList);
        return mapping.findForward("update");
    }

}

上面的Action所對應的UpdateHouseForm代碼以下:api

package com.house.form;

import java.math.BigDecimal;
import java.util.Date;
import org.apache.struts.action.ActionForm;
import com.house.entity.HouseType;
import com.house.entity.Member;

public class UpdateHouseForm extends ActionForm {

    private static final long serialVersionUID = 1L;

    private Integer id;
    private Member member = new Member();
    private HouseType houseType = new HouseType();
    private Integer livingRoom;
    private Integer bedroom;
    private String information;
    private BigDecimal rent;
    private String title;
    private Date postDate;
    private String telephone;
    private String realName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Member getMember() {
        return member;
    }

    public void setMember(Member member) {
        this.member = member;
    }

    public HouseType getHouseType() {
        return houseType;
    }

    public void setHouseType(HouseType houseType) {
        this.houseType = houseType;
    }

    public Integer getLivingRoom() {
        return livingRoom;
    }

    public void setLivingRoom(Integer livingRoom) {
        this.livingRoom = livingRoom;
    }

    public Integer getBedroom() {
        return bedroom;
    }

    public void setBedroom(Integer bedroom) {
        this.bedroom = bedroom;
    }

    public String getInformation() {
        return information;
    }

    public void setInformation(String information) {
        this.information = information;
    }

    public BigDecimal getRent() {
        return rent;
    }

    public void setRent(BigDecimal rent) {
        this.rent = rent;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Date getPostDate() {
        return postDate;
    }

    public void setPostDate(Date postDate) {
        this.postDate = postDate;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

}

注意上面的UpdateHouseForm,裏面的包含有其它類型的對象,但在這個地方被初始化了。其目的是由於在更新操做的form提交時,若表單中包含有相似以member.loginId的元素,則其對應的form中的member必須是被實例化,不然會引起異常。

下面是Struts標籤庫中的html標籤的基本實用,這裏實現了表單元素的value值的初始化。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Expires" content="0" />
<link type="text/css" href="/house/style/style.css" rel="stylesheet" />
<script type="text/javascript">
function validateForm() {
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].value == "") {
            alert("請將表單信息補充完整!");
            return false;
        }
    }
    return true;
}
</script>
<title>編輯房屋信息</title>
</head>

<body>
<h1>歡迎使用房屋信息管理系統</h1>
<html:form action="/updateHouseInfo" method="post"
    onsubmit="return validateForm();">
    <table border="0" cellspacing="1" cellpadding="0" class="detail">
        <tr>
            <th colspan="2"><h2>編輯房屋信息</h2></th>
        </tr>
        <tr>
            <th>編號</th>
            <td><html:text property="id" readonly="true" /></td>
        </tr>
        <tr>
            <th>發佈者</th>
            <td>
                <html:text property="member.loginId" readonly="true" />
                <html:hidden property="member.id" />
            </td>
        </tr>
        <tr>
            <th>類型</th>
            <td>
            <html:select property="houseType.id">
                <html:optionsCollection name="houseTypeList"
                    label="typeName" value="id" />
            </html:select>
            </td>
        </tr>
        <tr>
            <th>廳</th>
            <td><html:text property="livingRoom" /></td>
        </tr>
        <tr>
            <th>室</th>
            <td><html:text property="bedroom" /></td>
        </tr>
        <tr>
            <th>描述</th>
            <td><html:text property="information" /></td>
        </tr>
        <tr>
            <th>租金</th>
            <td><html:text property="rent" /></td>
        </tr>
        <tr>
            <th>標題</th>
            <td><html:text property="title" /></td>
        </tr>
        <tr>
            <th>電話</th>
            <td><html:text property="telephone" /></td>
        </tr>
        <tr>
            <th>聯繫人</th>
            <td><html:text property="realName" /></td>
        </tr>
        <tr>
            <th colspan="2" style="text-align: right;">
                <input type="submit" value="更新" />
                <input type="button" value="返回" />
            </th>
        </tr>
    </table>
</html:form>
</body>
</html>
頁面效果以下圖(表單元素都已經有默認值):

內容很基礎,不囉嗦了,明天還要上班。

相關文章
相關標籤/搜索