這次主要使用MyEclpse對Spring Hibernate JSF作簡單的備忘過程,
首先自行安裝 jdk, tomcat, mysql, eclipse.
http://java.sun.com/j2se/1.5.0/download.jsp
http://jakarta.apache.org/site/downloads/downloads_tomcat-5.html
http://dev.mysql.com/downloads/mysql/5.0.html
http://www.eclipse.org/downloads/
在Mysql建立資料庫及表格:
DB user: root password: rootpassword
create database mysurvey;
create table survey(
id int(10) not null auto_increment,
name varchar(50) not null,
email varchar(30) not null,
result varchar(1) not null,
primary key(id)
);
安裝MyEclipse:
http://www.myeclipseide.com/ContentExpress-display-ceid-10.html
安裝Eclipse Property File GUI Editor:
http://sourceforge.net/project/showfiles.php?group_id=117908
建立Web project:
File -> New -> project ->> MyEclipse -> J2EE Project -> Web Project ->> Next
輸入Project Name : MySurvey -> Finish
建主package ( 方便日後便用MyEclipse Database generate Persistant Bean ):
選MySurvey -> src -> New -> Package ->>
Name : com.joeyta.mysurvey -> Finish
然後download mysql jdbc driver 放在 MySurvey -> WebRoot -> WEB-INF -> lib :
http://dev.mysql.com/downloads/connector/j/3.1.html
建立 DB Profile (方便日後Hibernate使用 及 Generate Beans):
Window -> Open Perspective -> other ->> MyEclipse Database Explorer
DB Browser View -> New
Profile name: mysurvey
Driver: MMMySQL Driver
URL: jdbc:mysql://localhost:3306/mysurvey ( 在Mysql裡要先建立mysurvey database )
User name: root
Password: rootpassword
Open on Eclipse startup: unchecked
Prompt for password: unchecked
-> Next
Display the selected schemas: checked
按 Add -> check mysurvey -> Finish
Generates Persistants Beans:
DB Browser View -> mysurvey -> Open Connection
->> Connected to mysurvey ->mysurvey -> TABLE -> survey
->> Create Hibernate Mapping
Java src folder: /MySurvey/src
java package: com.joeyta.mysurvey
Update hibernate configuration with mapping file location
-> Finish
打開 Package Explorer -> MySurvey -> src -> com.joeyta.mysurvey
就會看到兩個java ( AbstractSurvey.java, Survey.java ) 及 1個mapping file ( Survey.hbm.xml ).
並將mapping file update 到 Hibernate.cfg.xml
( 平時玩Hibernate,通常玩的是mapping files -> beans 及 mapping files -> table scrip,很少玩tablescript > beans )
修改 Survey.hbm.xml :
由於generate 出來的Survey.hbm.xml 裡 class 裡多了catalog property,這會影響SQL.
在<generator class="assigned" /> 這個不是我會想要的,由於mysql中的id是auto_increment,故需要改成native
<!--------------------- Survey.hbm.xml ------------------------------------------>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
<class name="com.joeyta.mysurvey.Survey" table="survey">
<id name="id" type="integer">
<column name="id" />
<generator class="native" />
</id>
<property name="name" type="string">
<column name="name" length="50" not-null="true" />
</property>
<property name="email" type="string">
<column name="email" length="30" not-null="true" />
</property>
<property name="result" type="string">
<column name="result" length="1" not-null="true" />
</property>
</class>
</hibernate-mapping>
<!--------------------- Survey.hbm.xml ------------------------------------------>
加入 JSF Capabilities:
點選 MySurvey -> MyEclipse -> Add JSF Capabilities
JSF Implementation : MyFaces 1.1.1 -> Finish
有點奇怪的是有些library沒有把它加到WEB-INF/lib裡,
尤其是以下這三個,
jsf-api.jar, jsf-impl.jar, standard.jar
可以到MyEclipse library folder找出來或到
http://java.sun.com/javaee/javaserverfaces/
加入 Hibernate Capabilities:
點選 MySurvey -> MyEclipse -> Add Hibernate Capabilities
Hibernate Specification: Hibernate 3
JAR Library Installation: Copy checked Library Jars to project folder and add to build-path
-> Next
Hibernate config file: New
-> Next
Specify database connection details?: checked
DataSource: Use JDBC Driver
DB Profile: mysurvey ( 這裡就是剛剛建立的DB Profile )
-> Next
Create SessionFactory class: unchecked -> Finish
hibernate.cfg.xml :
<!------------------------- 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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">jdbc:mysql://localhost:3306/mysurvey</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="myeclipse.connection.profile">mysurvey</property>
<property name="connection.password">rootpassword</property>
<property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
<mapping resource="com/joeyta/mysurvey/Survey.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
<!------------------------- hibernate.cfg.xml ------------------------------->
加入 Spring Capabilities:
點選 MySurvey -> MyEclipse -> Add Spring Capabilities
Show MyEclipse Libraries : checked
並選下面這些 libraries:
Spring 1.2 AOP Libraries
Spring 1.2 Core Libraries
Spring 1.2 ORM/DAO/Hibernate3 Libraries
spring 1.2 Web Libraries
Jar Library Installation: Copy checked Library contents to project folder
Library Folder: /WebRoot/WEB-INF/lib
-> Next
Specify new or existing Spring bean configuration file? checked
-> Next
Create Spring LocalSessionFactory that references the hibernate config using a configLocation property? checked
Spring Config: src/applicationContext.xml
SessionFactory id: sessionFactory
-> Finish
建立log4j.properties:
MySurvey -> src -> New -> File
File name: log4j.properties
############# log4j.properties #############
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=INFO, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
com.mchange.v2.log.MLog=com.mchange.v2.log.log4j.Log4jMLog
log4j.logger.mo.org.cpttm.workflow=INFO
############# log4j.properties #############
建立DAO object :
( 日後利用Spring AOP, JSF就能存取DAO Object,
這裡為求簡便,不打算利用Spring AOP處理Transaction )
/*********** ISurveyDAO.java **********/
package com.joeyta.mysurvey;
public interface ISurveyDAO {
public void insert(Survey survey);
public Survey find(Integer id);
public boolean isExist(String name, String email);
}
/*********** ISurveyDAO.java **********/
/*********** SurveyDAO.java **********/
package com.joeyta.mysurvey;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class SurveyDAO extends HibernateDaoSupport implements
ISurveyDAO {
public SurveyDAO() {
super();
}
public void insert(Survey survey) {
getHibernateTemplate().save(survey);
}
public Survey find(Integer id) {
Survey survey = (Survey) getHibernateTemplate()
.get(Survey.class, id);
return survey;
}
public boolean isExist(String name, String email) {
List list = getHibernateTemplate().find(
"from survey s where s.name='"+name+"' or s.email='"+email+"'");
return list.size() > 0;
}
}
/*********** SurveyDAO.java **********/
修改 applicationContext.xml :
<!--------------------- applicationContext.xml ---------------------------->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>/WEB-INF/classes/hibernate.cfg.xml</value>
</property>
</bean>
<bean id="surveyDAO" class="com.joeyta.mysurvey.SurveyDAO">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</beans>
<!--------------------- applicationContext.xml ---------------------------->
修改 Survey.java :
/********************* Survey ************************************/
package com.joeyta.mysurvey;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
public class Survey extends AbstractSurvey implements java.io.Serializable {
private static final long serialVersionUID = -6603171231966815078L;
public Survey() {
}
public Survey(Integer id, String name, String email, String result) {
super(id, name, email, result);
}
private String locale = "zh_TW";
private String message;
private SurveyDAO surveyDAO;
public String getParameter(String name, String sDefaultValue) {
if (FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get(name) != null) {
return (String) FacesContext.getCurrentInstance()
.getExternalContext().getRequestParameterMap().get(name);
}
return sDefaultValue;
}
public String submit() {
if (surveyDAO.isExist(getName(), getEmail())) {
setMessage("每位會員只能參加一次!");
return "failure";
} else {
setMessage("多謝閣下參與!");
this.surveyDAO.insert(this);
return "success";
}
}
public void changeLocale(ValueChangeEvent event) {
if (locale.equals("zh_TW"))
locale = "zh_CN";
else
locale = "zh_TW";
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SurveyDAO getSurveyDAO() {
return surveyDAO;
}
public void setSurveyDAO(SurveyDAO surveyDAO) {
this.surveyDAO = surveyDAO;
}
}
/********************* Survey ************************************/
建立messages.properties:
MySurvey -> src -> New -> File
File name: messages.properties
Right click messages.properties -> Open With -> Property File GUI Editor
( 由於剛剛將了Property File GUI Editor )
打開後按 Add locale
Local: zh_TW -> OK
再按 Add locale
Local: zh_CN -> OK
儲存後就會看到多出兩個檔案 messages_zh_TW.properties 及 messages_zh_CN.properties
其實這三個檔案就會出來國際化訊息使用,即支持繁簡體.
################## messages.properties #####################
titleText=\u6700\u4F73\u54E1\u5DE5\u9078\u8209
zh_TWText=\u7E41\u9AD4
q1=\u6700\u4F73\u54E1\u5DE5(\u6295\u6CE8\u54E1)
q5=\u6700\u4F73\u54E1\u5DE5(\u6295\u6CE8\u54E1)
q4=\u67E5\u8A62\u53CA\u51FA\u5165\u91D1\u6700\u4F73\u54E1\u5DE5
q3=\u5C08\u8CAC\u5C0F\u7D44\u6700\u4F73\u54E1\u5DE5
q2=\u6700\u4F73\u5BA2\u6236\u4E3B\u4EFB
cnText=\u7C21\u9AD4
name=\u59D3\u540D
idcard=\u8EAB\u4EFD\u8B49\u865F\u78BC
slotid=\u4E92\u806F\u901A\u6236\u53E3\u865F\u78BC
tel=\u806F\u7D61\u96FB\u8A71
address=\u5730\u5740
submit=\u9001\u51FA
################## messages.properties #####################
################## messages_zh_TW.properties #####################
titleText=\u6700\u4F73\u54E1\u5DE5\u9078\u8209
zh_TWText=\u7E41\u9AD4
q1=\u6700\u4F73\u54E1\u5DE5(\u6295\u6CE8\u54E1)
q5=\u6700\u4F73\u54E1\u5DE5(\u6295\u6CE8\u54E1)
q4=\u67E5\u8A62\u53CA\u51FA\u5165\u91D1\u6700\u4F73\u54E1\u5DE5
q3=\u5C08\u8CAC\u5C0F\u7D44\u6700\u4F73\u54E1\u5DE5
q2=\u6700\u4F73\u5BA2\u6236\u4E3B\u4EFB
cnText=\u7C21\u9AD4
name=\u59D3\u540D
idcard=\u8EAB\u4EFD\u8B49\u865F\u78BC
slotid=\u4E92\u806F\u901A\u6236\u53E3\u865F\u78BC
tel=\u806F\u7D61\u96FB\u8A71
address=\u5730\u5740
submit=\u9001\u51FA
################## messages_zh_TW.properties #####################
################## messages_zh_CN.properties #####################
titleText=\u6700\u4F73\u5458\u5DE5\u9009\u4E3E
zh_TWText=\u7E41\u4F53
q1=\u6700\u4F73\u5458\u5DE5(\u6295\u6CE8\u5458)
q5=\u6700\u4F73\u5458\u5DE5(\u6295\u6CE8\u5458)
q4=\u67E5\u8BE2\u53CA\u51FA\u5165\u91D1\u6700\u4F73\u5458\u5DE5
q3=\u4E13\u8D23\u5C0F\u7EC4\u6700\u4F73\u5458\u5DE5
q2=\u6700\u4F73\u5BA2\u6237\u4E3B\u4EFB
cnText=\u7B80\u4F53
name=\u59D3\u540D
idcard=\u8EAB\u4EFD\u8BC1\u53F7\u7801
slotid=\u4E92\u8054\u901A\u6237\u53E3\u53F7\u7801
tel=\u8054\u7EDC\u7535\u8BDD
address=\u5730\u5740
submit=\u9001\u51FA
################## messages_zh_CN.properties #####################
建立 survey.jsp :
Mysurvey -> New -> JSP
File Path: /MySurvey/WebRoot/survey
File Name survey.jsp
Template to use: [6] Default JSF template
<%---------------------- survey.jsp ---------------------------%>
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<f:view locale="#{survey.locale}">
<f:loadBundle basename="messages" var="msg" />
<html>
<head>
<base href="<%=basePath%>">
<title><h:outputText value="#{msg.titleText}" /></title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h:outputText value="#{survey.message}" />
<h:form>
<h:selectOneMenu value="#{survey.locale}" immediate="true"
onchange="this.form.submit();" valueChangeListener="#{survey.changeLocale}">
<f:selectItem itemValue="zh_TW" itemLabel="#{msg.zh_TWText}" />
<f:selectItem itemValue="zh_CN" itemLabel="#{msg.cnText}" />
</h:selectOneMenu>
<br />
<TABLE border="1" width="500px">
<TR>
<TD><h:outputText value="#{msg.name}" /></TD>
<TD>
<h:inputText rendered="true" required="true" value="#{survey.name}" />
</TD>
</TR>
<TR>
<TD><h:outputText value="#{msg.email}" /></TD>
<TD>
<h:inputText rendered="true" required="true" value="#{survey.email}" />
</TD>
</TR>
<TR>
<TD><h:outputText value="#{msg.result}" /></TD>
<TD>
<h:inputText rendered="true" required="true" value="#{survey.result}" />
</TD>
</TR>
<TR>
<TD colspan="2">
<h:commandButton value="#{msg.submit}" rendered="true" action="#{survey.submit}" />
</TD>
</TR>
</TABLE>
</h:form>
</body>
</html>
</f:view>
<%---------------------- survey.jsp ---------------------------%>
修改 faces-config.xml
<!----------------------- faces-config.xml ------------------------>
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>
<application>
<locale-config>
<default-locale>zh_TW</default-locale>
<supported-locale>zh_CN</supported-locale>
</locale-config>
<variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>
</application>
<navigation-rule>
<from-view-id>/survey/survey.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/survey/survey.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/survey/survey.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>survey</managed-bean-name>
<managed-bean-class>com.joeyta.mysurvey.Survey</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>surveyDAO</property-name>
<value>#{surveyDAO}</value>
</managed-property>
</managed-bean>
</faces-config>
<!----------------------- faces-config.xml ------------------------>
建立tomcat deployment descriptor
D:\Apache Group\Tomcat 5.0\conf\Catalina\localhost\mysurvey.xml
<Context path="/mysurvey" docBase="D:\eclipse\workspace\MySurvey\WebRoot" reloadable="true"></Context>
<!--------
D:\Apache Group\Tomcat 5.0\ 為 tomcat 安裝位置
D:\eclipse\workspace\MySurvey 為 MySurvey eclipse project 位置
----------->
修改 web.xml
<!----------------------- web.xml ------------------------>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<description>JSF Demo</description>
<display-name>JSF Demo</display-name>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<filter>
<filter-name>MyFacesExtensionsFilter</filter-name>
<filter-class>org.apache.myfaces.component.html.util.ExtensionsFilter</filter-class>
<init-param>
<param-name>maxFileSize</param-name>
<param-value>20m</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<url-pattern>*.faces</url-pattern>
</filter-mapping>
</web-app>
<!----------------------- web.xml ------------------------>
打開tomcat 及 IE:
http://localhost:8083/mysurvey/survey/survey.faces