亚洲色大18成人网站WWW在线播放,亚洲日韩av无码中文,精品久久久久久亚洲http://www.tkk7.com/faithwind/category/8323.htmlLove Java ,because you are my first lady !^_^zh-cnFri, 02 Mar 2007 00:35:37 GMTFri, 02 Mar 2007 00:35:37 GMT60Velocity簡介http://www.tkk7.com/faithwind/articles/35091.html黑咖啡黑咖啡Mon, 13 Mar 2006 09:30:00 GMThttp://www.tkk7.com/faithwind/articles/35091.htmlhttp://www.tkk7.com/faithwind/comments/35091.htmlhttp://www.tkk7.com/faithwind/articles/35091.html#Feedback0http://www.tkk7.com/faithwind/comments/commentRss/35091.htmlhttp://www.tkk7.com/faithwind/services/trackbacks/35091.html 1.Velocity 的使用
Velocity是一個開放源嗎的模版引擎,由apache.org小組負責開發(fā),現(xiàn)在最新的版本是Velocity1.3.1,http://jakarta.apache.org/velocity/index.html 可以了解Velocity的最新信息。
Velocity允許我們在模版中設(shè)定變量,然后在運行時,動態(tài)的將數(shù)據(jù)插入到模版中,替換這些變量。
例如:
<html>
<body>HELLO $CUSTOMERNAME</body>
</html>
我們可以在運行時得到客戶的名字,然后把它插入到這個模版中替換變量$CUSTOMERNAME,整個替換過程是由Velocity進行控制的,而且java的調(diào)用代碼也非常簡單,如我們可以在java代碼中這樣調(diào)用
/***********************************************************/
//這個文件中設(shè)定了Velocity使用的log4j的配置和Velocity的模版文件所在的目錄
Velocity.init("D:\\Template\\resource\\jt.properties");
//模版文件名,模版文件所在的路徑在上一條語句中已經(jīng)設(shè)置了
Template template = Velocity.getTemplate("hello.vm", "gb2312");
//實例化一個Context
VelocityContext context = new VelocityContext();
//把模版變量的值設(shè)置到context中
context.put("CUSTOMERNAME", "My First Template Engine ---- Velocity.");
//開始模版的替換
template.merge(context, writer);
//寫到文件中
PrintWriter filewriter = new PrintWriter(new FileOutputStream(outpath),true);
filewriter.println(writer.toString());
filewriter.close();
/***********************************************************/

這就是整個java的代碼,非常的簡單。如果我們有多個模版變量,我們僅需要把這些模版變量的值設(shè)置到context中。
下面我們簡單的分析一下,Velocity引擎讀取模板文件時,它直接輸出文件中所有的文本,但以$字符開頭的除外,$符號標識著一個模版變量位置,
context.put("CUSTOMERNAME", "My First Template Engine ---- Velocity.");
當 Velocity 模板引擎解析并輸出模板的結(jié)果時,模板中所有出現(xiàn)$CUSTOMERNAME的地方都將插入客戶的名字,即被加入到VelocityContext的對象的toString()方法返回值將替代Velocity變量(模板中以$開頭的變量)。
模板引擎中最強大、使用最頻繁的功能之一是它通過內(nèi)建的映像(Reflection)引擎查找對象信息的能力。這個映像引擎允許用一種方便的Java“.”類似的操作符,提取任意加入到VelocityContext的對象的任何公用方法的值,或?qū)ο蟮娜我鈹?shù)據(jù)成員。
映像引擎還帶來了另外一個改進:快速引用JavaBean的屬性。使用JavaBean屬性的時候,我們可以忽略get方法和括號。請看下面這個模板的例子。
<html>
<body>
Name:$Customer.Name()
Address:$Customer.Address()
Age:$Customer.Age()
</body>
</html>

java的代碼:
/***********************************************************/
//設(shè)置客戶信息
Customer mycustomer = new Customer();
mycustomer.setName("Velocity");
mycustomer.setAddress("jakarta.apache.org/velocity/index.html");
mycustomer.setAge(2);
//這個文件中設(shè)定了 Velocity 使用的 Log4j 的配置和Velocity的模版文件所在的目錄Velocity.init("D:\\Template\\resource\\jt.properties");
//模版文件名,模版文件所在的路徑在上一條語句中已經(jīng)設(shè)置了
Template template = Velocity.getTemplate("hello.vm", "gb2312");
//實例化一個Context
VelocityContext context = new VelocityContext();
//把模版變量的值設(shè)置到context中
context.put("Customer", mycustomer);
//開始模版的替換
template.merge(context, writer);
//寫到文件中
PrintWriter filewriter = new PrintWriter(new FileOutputStream(outpath),true);
filewriter.println(writer.toString());
filewriter.close();
輸出結(jié)果:
<html>
<body>
Name:Velocity
Address:jakarta.apache.org/velocity/index.html
Age:2
</body>
</html>
除了替換變量之外,象Velocity高級引擎還能做其他許多事情,它們有用來比較和迭代的內(nèi)建指令,通過這些指令我們可以完成程序語言中的條件判斷語句和循環(huán)語句等。
例如,我們想要輸出年齡等于2的所有客戶的信息,我們可以這樣定義我們的模版
模版:
<html>
<body>
<table>
<tr>
<td>名稱</td>
<td>地址</td>
<td>年齡</td>
</tr>
#foreach ($Customer in $allCustomer)
#if($Customer.Age()=="2")
<tr>
<td>$Customer.Name()</td>
<td>$Customer.Address()</td>
<td>$Customer.Age()</td>
</tr>
#end
#end
</table>
</body>
</html>

java的代碼:
/******************************************************/
//設(shè)置客戶信息
ArrayList allMyCustomer = new ArrayList();
//客戶1
Customer mycustomer1 = new Customer();
mycustomer1.setName("Velocity");
mycustomer1.setAddress("jakarta.apache.org/velocity/index.html");
mycustomer1.setAge(2);
//客戶2
Customer mycustomer2 = new Customer();
mycustomer2.setName("Tomcat");
mycustomer2.setAddress("jakarta.apache.org/tomcat/index.html");
mycustomer2.setAge(3);
//客戶3
Customer mycustomer3 = new Customer();
mycustomer3.setName("Log4J");
mycustomer3.setAddress("jakarta.apache.org/log4j/docs/index.html");
mycustomer3.setAge(2);
//添加到allMyCustomer(ArrayList)中.
allMyCustomer.add(mycustomer1);
allMyCustomer.add(mycustomer2);
allMyCustomer.add(mycustomer3);
//這個文件中設(shè)定了Velocity使用的log4j的配置和Velocity的模版文件所在的目
Velocity.init("D:\\Template\\resource\\jt.properties");
//模版文件名,模版文件所在的路徑在上一條語句中已經(jīng)設(shè)置了
Template template =Velocity.getTemplate("hello.vm", "gb2312");
//實例化一個Context
VelocityContext context = new VelocityContext();
/** 注意這里我們僅僅需要給一個模版變量負值 */
context.put("allCustomer", allMyCustomer);
//開始模版的替換
template.merge(context, writer);
//寫到文件中
PrintWriter filewriter = new PrintWriter(new FileOutputStream(outpath),true);
filewriter.println(writer.toString());
filewriter.close();
/******************************************************/
結(jié)果:
<html>
<body>
<table>
<tr>
<td>名稱</td>
<td>地址</td>
<td>年齡</td>
</tr>
<tr>
<td>Velocity</td>
<td>jakarta.apache.org/velocity/index.html</td>
<td>2</td>
</tr>
<tr>
<td>Log4J</td>
<td>jakarta.apache.org/log4j/docs/index.html</td>
<td>2</td>
</tr>
</table>
</body>
</html>

#if 語句完成邏輯判斷,這個我想不用多說了。
allCustomer對象包含零個或者多個Customer對象。由于ArrayList (List, HashMap, HashTable, Iterator, Vector等)屬于Java Collections Framework的一部分,我們可以用#foreach指令迭代其內(nèi)容。我們不用擔心如何定型對象的類型——映像引擎會為我們完成這個任務(wù)。#foreach指令的一般格式是“#foreach in ”。#foreach指令迭代list,把list中的每個元素放入item參數(shù),然后解析#foreach塊內(nèi)的內(nèi)容。對于list內(nèi)的每個元素,#foreach塊的內(nèi)容都會重復解析一次。從效果上看,它相當于告訴模板引擎說:“把list中的每一個元素依次放入item變量,每次放入一個元素,輸出一次#foreach塊的內(nèi)容”。

2.MVC設(shè)計模型

使用模板引擎最大的好處在于,它分離了代碼(或程序邏輯)和表現(xiàn)(輸出)。由于這種分離,你可以修改程序邏輯而不必擔心郵件消息本身;類似地,你(或公關(guān)部門的職員)可以在不重新編譯程序的情況下,重新編寫客戶列表。實際上,我們分離了系統(tǒng)的數(shù)據(jù)模式(Data Model,即提供數(shù)據(jù)的類)、控制器(Controller,即客戶列表程序)以及視圖(View,即模板)。這種三層體系稱為Model-View-Controller模型(MVC)。
如果遵從MVC模型,代碼分成三個截然不同的層,簡化了軟件開發(fā)過程中所有相關(guān)人員的工作。
結(jié)合模板引擎使用的數(shù)據(jù)模式可以是任何Java對象,最好是使用Java Collection Framework的對象。控制器只要了解模板的環(huán)境(如VelocityContext),一般這種環(huán)境都很容易使用。
一些關(guān)系數(shù)據(jù)庫的“對象-關(guān)系”映射工具能夠和模板引擎很好地協(xié)同,簡化JDBC操作;對于EJB,情形也類似。 模板引擎與MVC中視圖這一部分的關(guān)系更為密切。模板語言的功能很豐富、強大,足以處理所有必需的視圖功能,同時它往往很簡單,不熟悉編程的人也可以使用它。模板語言不僅使得設(shè)計者從過于復雜的編程環(huán)境中解脫出來,而且它保護了系統(tǒng),避免了有意或無意帶來危險的代碼。例如,模板的編寫者不可能編寫出導致無限循環(huán)的代碼,或侵占大量內(nèi)存的代碼。不要輕估這些安全機制的價值;大多數(shù)模板編寫者不懂得編程,從長遠來看,避免他們接觸復雜的編程環(huán)境相當于節(jié)省了你自己的時間。 許多模板引擎的用戶相信,在采用模板引擎的方案中,控制器部分和視圖部分的明確分離,再加上模板引擎固有的安全機制,使得模板引擎足以成為其他內(nèi)容發(fā)布系統(tǒng)(比如JSP)的替代方案。因此,Java模板引擎最常見的用途是替代JSP也就不足為奇了。

3.HTML處理

由于人們總是看重模板引擎用來替換JSP的作用,有時他們會忘記模板還有更廣泛的用途。到目前為止,模板引擎最常見的用途是處理HTML Web內(nèi)容。但我還用模板引擎生成過SQL、email、XML甚至Java源代碼。
    


黑咖啡 2006-03-13 17:30 發(fā)表評論
]]>
一篇Velocity入門文章http://www.tkk7.com/faithwind/articles/34990.html黑咖啡黑咖啡Mon, 13 Mar 2006 02:44:00 GMThttp://www.tkk7.com/faithwind/articles/34990.htmlhttp://www.tkk7.com/faithwind/comments/34990.htmlhttp://www.tkk7.com/faithwind/articles/34990.html#Feedback0http://www.tkk7.com/faithwind/comments/commentRss/34990.htmlhttp://www.tkk7.com/faithwind/services/trackbacks/34990.html
使用Velocity 模板引擎開發(fā)網(wǎng)站

Velocity 是如何工作的呢? 雖然大多 Velocity 的應用都是基于 Servlet 的網(wǎng)頁制作。但是為了說明 Velocity 的使用,我決定采用更通用的 Java application 來說明它的工作原理。
  似乎所有語言教學的開頭都是采用 HelloWorld 來作為第一個程序的示例。這里也不例外。

  任何 Velocity 的應用都包括兩個方面:
  第一是: 模板制作,在我們這個例子中就是 hellosite.vm:
  它的內(nèi)容如下(雖然不是以 HTML 為主,但是這很容易改成一個 html 的頁面)

Hello $name! Welcome to $site world!
  第二是 Java 程序部分:
  下面是 Java 代碼
程序代碼 程序代碼
import java.io.StringWriter;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
public class HelloWorld{
 public static void main( String[] args )throws Exception{
  /* first, get and initialize an engine */
  VelocityEngine ve = new VelocityEngine();
  ve.init();
  /* next, get the Template */
  Template t = ve.getTemplate( "hellosite.vm" );
  /* create a context and add data */
  VelocityContext context = new VelocityContext();
  context.put("name", "Eiffel Qiu");
  context.put("site", "http://www.eiffelqiu.com");
  /* now render the template into a StringWriter */
  StringWriter writer = new StringWriter();
  t.merge( context, writer );
  /* show the World */
  System.out.println( writer.toString() );
 }
}

將兩個文件放在同一個目錄下,編譯運行,結(jié)果是:
Hello Eiffel Qiu! Welcome to http://www.eiffelqiu.com world

  為了保證運行順利,請從 Velocity 的網(wǎng)站 http://jakarta.apache.org/velocity/ 上下載 Velocity 的運行包,將其中的 Velocity Jar 包的路徑放在系統(tǒng)的 Classpath 中,這樣就可以編譯和運行以上的程序了。

這個程序很簡單,但是它能讓你清楚的了解 Velocity 的基本工作原理。程序中其他部分基本上很固定,最主要的部分在以下代碼

  這里 Velocity 獲取模板文件,得到模板引用

程序代碼 程序代碼
/* next, get the Template */
Template t = ve.getTemplate( "hellosite.vm" );

  這里,初始化環(huán)境,并將數(shù)據(jù)放入環(huán)境

程序代碼 程序代碼
/* create a context and add data */
VelocityContext context = new VelocityContext();
context.put("name", "Eiffel Qiu");
context.put("site", "http://www.eiffelqiu.com");

  其他代碼比較固定,但是也非常重要,但是對于每個應用來說寫法都很相同:
這是初始化 Velocity 模板引擎

程序代碼 程序代碼
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.init();

  這是用來將環(huán)境變量和輸出部分結(jié)合。

程序代碼 程序代碼
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* show the World */
System.out.println( writer.toString() );

  記住,這在將來的 servlet 應用中會有所區(qū)別,因為網(wǎng)頁輸出并不和命令行輸出相同,如果用于網(wǎng)頁輸出,將并不通過 System.out 輸出。這會在以后的教程中給大家解釋的。

那讓我來總結(jié)一下 Velocity 真正的工作原理:
  Velocity 解決了如何在 Servlet 和 網(wǎng)頁之間傳遞數(shù)據(jù)的問題,當然這種傳輸數(shù)據(jù)的機制是在 MVC 模式上進行的,也就是View 和 Modle , Controller 之間相互獨立工作,一方的修改不影響其他方變動,他們之間是通過環(huán)境變量(Context)來實現(xiàn)的,當然雙方網(wǎng)頁制作一方和后臺程序一方要相互約定好對所傳遞變量的命名約定,比如上個程序例子中的 site, name 變量,它們在網(wǎng)頁上就是 $name ,$site 。 這樣只要雙方約定好了變量名字,那么雙方就可以獨立工作了。 無論頁面如何變化,只要變量名不變,那么后臺程序就無需改動,前臺網(wǎng)頁也可以任意由網(wǎng)頁制作人員修改。這就是 Velocity 的工作原理。

  你會發(fā)現(xiàn)簡單變量名通常無法滿足網(wǎng)頁制作顯示數(shù)據(jù)的需要,比如我們經(jīng)常會循環(huán)顯示一些數(shù)據(jù)集,或者是根據(jù)一些數(shù)據(jù)的值來決定如何顯示下一步的數(shù)據(jù), Velocity 同樣提供了循環(huán),判斷的簡單語法以滿足網(wǎng)頁制作的需要。Velocity 提供了一個簡單的模板語言以供前端網(wǎng)頁制作人員使用,這個模板語言足夠簡單(大部分懂得 javascript 的人就可以很快掌握,其實它比 javascript 要簡單的多),當然這種簡單是刻意的,因為它不需要它什么都能做, View 層其實不應該包含更多的邏輯,Velocity 的簡單模板語法可以滿足你所有對頁面顯示邏輯的需要,這通常已經(jīng)足夠了,這里不會發(fā)生象 jsp 那樣因為一個無限循環(huán)語句而毀掉系統(tǒng)的情況,jsp 能做很多事情,Sun 在制定 Jsp 1.0 標準的時候,沒有及時的限定程序員在 jsp 插入代碼邏輯,使得早期的jsp 代碼更象是 php 代碼,它雖然強大,但是對顯示層邏輯來說,并不必要,而且會使 MVC 三層的邏輯結(jié)構(gòu)發(fā)生混淆。

黑咖啡 2006-03-13 10:44 發(fā)表評論
]]>
spring+velocity自動發(fā)送郵件http://www.tkk7.com/faithwind/articles/34987.html黑咖啡黑咖啡Mon, 13 Mar 2006 02:35:00 GMThttp://www.tkk7.com/faithwind/articles/34987.htmlhttp://www.tkk7.com/faithwind/comments/34987.htmlhttp://www.tkk7.com/faithwind/articles/34987.html#Feedback0http://www.tkk7.com/faithwind/comments/commentRss/34987.htmlhttp://www.tkk7.com/faithwind/services/trackbacks/34987.html1.下載spring及velocity類庫,

email配置文件:mail.properties:
mail.default.from=jfishsz@163.com
mail.host=smtp.163.com
mail.username=xxxxxx
mail.password=xxxxxx
mail.smtp.auth=true
mail.smtp.timeout=25000

spring配置文件: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>
  <!-- For mail settings and future properties files -->
  <bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:mail.properties</value>
        </list>
    </property>
  </bean>
  <bean id="mailSender"
    class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host">
        <value>${mail.host}</value>
    </property>
    <property name="username">
        <value>${mail.username}</value>
    </property>
    <property name="password">
        <value>${mail.password}</value>
    </property>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
            <prop key="mail.smtp.timeout">
              ${mail.smtp.timeout}
            </prop>
        </props>
    </property>
  </bean>
  <bean id="mailMessage"
    class="org.springframework.mail.SimpleMailMessage"
    singleton="false">
    <property name="from">
        <value>${mail.default.from}</value>
    </property>
   
  </bean>
  <bean id="sendMail" class="net.pms.email.SendMail">
    <property name="mailSender" ref="mailSender" />
    <property name="message" ref="mailMessage" />
    <property name="velocityEngine" ref="velocityEngine" />
  </bean>
  <!-- Configure Velocity for sending e-mail -->
  <bean id="velocityEngine"
    class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
    <property name="velocityProperties">
        <props>
            <prop key="resource.loader">class</prop>
            <prop key="class.resource.loader.class">
              org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
            </prop>
            <prop key="velocimacro.library"></prop>
        </props>
    </property>
  </bean>
</beans>
velocity模板文件:accountCreated.vm:
${message}

Username: ${username}
Password: ${Password}

Login at: ${applicationURL}

2.實現(xiàn)類
SendMail.java
package net.pms.email;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class SendMail {
  protected static final Log log = LogFactory.getLog(SendMail.class);

  private MailSender mailSender;

  private SimpleMailMessage message;

  private VelocityEngine velocityEngine;

  public void setVelocityEngine(VelocityEngine velocityEngine) {
    this.velocityEngine = velocityEngine;
  }

  public void setMailSender(MailSender mailSender) {
    this.mailSender = mailSender;
  }

  public void setMessage(SimpleMailMessage message) {
    this.message = message;
  }

  public void sendEmail(Map model) {
    message.setTo("jfishsz@163.com");
    message.setSubject("subject");
    String result = null;
    try {
        result = VelocityEngineUtils.mergeTemplateIntoString(
              velocityEngine, "accountCreated.vm", model);
    } catch (VelocityException e) {
        e.printStackTrace();
    }
    message.setText(result);
    mailSender.send(message);
  }
}
測試類:SendMailTest.java
package net.pms.email;

import java.util.HashMap;
import java.util.Map;

import junit.framework.TestCase;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SendMailTest extends TestCase {
  String[] paths = { "config/applicationContext*.xml" };

  ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);

  SendMail s = (SendMail) ctx.getBean("sendMail");

  protected void setUp() throws Exception {
    super.setUp();
  }

  protected void tearDown() throws Exception {
    super.tearDown();
  }

  /*
  * Test method for 'net.pms.email.SendMail.sendEmail(Map)'
  */
  public void testSendEmail() {
    Map model = new HashMap();
    model.put("message", "msg");
    model.put("username", "jack");
    model.put("Password", "666666");
    model.put("applicationURL", "www.163.com");
    s.sendEmail(model);
  }

}


黑咖啡 2006-03-13 10:35 發(fā)表評論
]]>
Velocity的中文指南http://www.tkk7.com/faithwind/articles/34669.html黑咖啡黑咖啡Fri, 10 Mar 2006 06:56:00 GMThttp://www.tkk7.com/faithwind/articles/34669.htmlhttp://www.tkk7.com/faithwind/comments/34669.htmlhttp://www.tkk7.com/faithwind/articles/34669.html#Feedback0http://www.tkk7.com/faithwind/comments/commentRss/34669.htmlhttp://www.tkk7.com/faithwind/services/trackbacks/34669.html閱讀全文

黑咖啡 2006-03-10 14:56 發(fā)表評論
]]>
Velocity實例http://www.tkk7.com/faithwind/articles/34305.html黑咖啡黑咖啡Wed, 08 Mar 2006 09:21:00 GMThttp://www.tkk7.com/faithwind/articles/34305.htmlhttp://www.tkk7.com/faithwind/comments/34305.htmlhttp://www.tkk7.com/faithwind/articles/34305.html#Feedback0http://www.tkk7.com/faithwind/comments/commentRss/34305.htmlhttp://www.tkk7.com/faithwind/services/trackbacks/34305.htmlVelocity 的介紹請參考 Velocity -- Java Web 開發(fā)新技術(shù)。這里是它的一個應用示例。

這個例子參照了 PHP-Nuke 的結(jié)構(gòu), 即所有 HTTP 請求都以 http://www.some.com/xxx/Modules?name=xxx&arg1=xxx&bbb=xxx 的形式進行處理。例子中所有文件都是 .java 和 .html , 沒有其他特殊的文件格式。除了 Modules.java 是 Java Servlet, 其余的 .java 文件都是普通的 Java Class.

所有 HTTP 請求都通過 Modules.java 處理。Modules.java 通過 Velocity 加載 Modules.htm。 Modules.htm 有頁頭,頁腳,頁左導航鏈接,頁中內(nèi)容幾個部分。其中頁頭廣告、頁中內(nèi)容是變化部分。頁頭廣告由 Modules.java 處理,頁中內(nèi)容部分由 Modules.java dispatch 到子頁面類處理。

1) Modules.java

        import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.velocity.*;
import org.apache.velocity.context.*;
import org.apache.velocity.exception.*;
import org.apache.velocity.servlet.*;
import commontools.*;

public class Modules
  extends VelocityServlet {
  public Template handleRequest(HttpServletRequest request,
                 HttpServletResponse response,
                 Context context) {
    //init
    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("utf-8");

    //prepare function page
    ProcessSubPage page = null;
    ProcessSubPage mainPage = new HomeSubPage();
    String requestFunctionName = (String) request.getParameter("name");
    boolean logined = false;

    String loginaccount = (String) request.getSession(true).getAttribute(
      "loginaccount");
    if (loginaccount != null) {
      logined = true;
    }

    //default page is mainpage
    page = mainPage;
    if (requestFunctionName == null||requestFunctionName.equalsIgnoreCase("home")) {
      page = mainPage;
    }

    //no login , can use these page
    else if (requestFunctionName.equalsIgnoreCase("login")) {
      page = new LoginProcessSubPage();
    }
    else if (requestFunctionName.equalsIgnoreCase("ChangePassword")) {
      page = new ChangePasswordSubPage();
    }
    else if (requestFunctionName.equalsIgnoreCase("ForgetPassword")) {
      page = new ForgetPassword();
    }
    else if (requestFunctionName.equalsIgnoreCase("about")) {
      page = new AboutSubPage();
    }
    else if (requestFunctionName.equalsIgnoreCase("contact")) {
      page = new ContactSubPage();
    }


    //for other page, need login first
    else if (logined == false) {
      page = new LoginProcessSubPage();
    }

    else if (requestFunctionName.equalsIgnoreCase("listProgram")) {
      page = new ListTransactionProgramSubPage();
    }
    else if (requestFunctionName.equalsIgnoreCase(
      "ViewProgramItem")) {
      page = new ViewTransactionProgramItemSubPage();
    }
    else if (requestFunctionName.equalsIgnoreCase(
      "UpdateProgramObjStatus")) {
      page = new UpdateTransactionProgramObjStatusSubPage();
    }
    else if (requestFunctionName.equalsIgnoreCase(
      "Search")) {
      page = new SearchSubPage();
    }

    //check if this is administrator
    else if (Utilities.isAdministratorLogined(request)) {
      //Utilities.debugPrintln("isAdministratorLogined : true");
      if (requestFunctionName.equalsIgnoreCase("usermanagement")) {
        page = new UserManagementSubPage();
      }
      else if (requestFunctionName.equalsIgnoreCase(
        "UploadFiles")) {
        page = new UploadFilesSubPage();
      }
      else if (requestFunctionName.equalsIgnoreCase(
        "DownloadFile")) {
        page = new DownloadFileSubPage();
      }
      else if (requestFunctionName.equalsIgnoreCase(
        "Report")) {
        page = new ReportSubPage();
      }

    }
    else {
      //no right to access.
      //Utilities.debugPrintln("isAdministratorLogined : false");
      page = null;
    }
    //Utilities.debugPrintln("page : " + page.getClass().getName());

    if(page != null){
      context.put("function_page",
            page.getHtml(this, request, response, context));
    }else{
      String msg = "Sorry, this module is for administrator only.You are not administrator.";
      context.put("function_page",msg);
    }
    
    context.put("page_header",getPageHeaderHTML());
    context.put("page_footer",getPageFooterHTML());

    Template template = null;
    try {
      template = getTemplate("/templates/Modules.htm"); //good
    }
    catch (ResourceNotFoundException rnfe) {
      Utilities.debugPrintln("ResourceNotFoundException 2");
      rnfe.printStackTrace();
    }
    catch (ParseErrorException pee) {
      Utilities.debugPrintln("ParseErrorException2 " + pee.getMessage());
    }
    catch (Exception e) {
      Utilities.debugPrintln("Exception2 " + e.getMessage());
    }

    return template;
  }

  /**
   * Loads the configuration information and returns that information as a Properties, e
   * which will be used to initializ the Velocity runtime.
   */
  protected java.util.Properties loadConfiguration(ServletConfig config) throws
    java.io.IOException, java.io.FileNotFoundException {
    return Utilities.initServletEnvironment(this);

  }

}        
2) ProcessSubPage.java , 比較簡單,只定義了一個函數(shù)接口 getHtml

     
  import javax.servlet.http.*;
import org.apache.velocity.context.*;
import org.apache.velocity.servlet.*;
import commontools.*;

public abstract class ProcessSubPage implements java.io.Serializable {
  public ProcessSubPage() {
  }

  public String getHtml(VelocityServlet servlet, HttpServletRequest request,
             HttpServletResponse response,
             Context context) {
    Utilities.debugPrintln(
      "you need to override this method in sub class of ProcessSubPage:"
      + this.getClass().getName());
    return "Sorry, this module not finish yet.";
  }

}
  
     

他的 .java 文件基本上是 ProcessSubPage 的子類和一些工具類。 ProcessSubPage 的子類基本上都是一樣的流程, 用類似
context.put("page_footer",getPageFooterHTML());
的寫法置換 .html 中的可變部分即可。如果沒有可變部分,完全是靜態(tài)網(wǎng)頁,比如 AboutSubPage, 就更簡單。

3) AboutSubPage.java

     
  import org.apache.velocity.servlet.VelocityServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.context.Context;

public class AboutSubPage extends ProcessSubPage {
  public AboutSubPage() {
  }

  public String getHtml(VelocityServlet servlet, HttpServletRequest request,
             HttpServletResponse response, Context context) {
    //prepare data
    //context.put("xxx","xxxx");         
             
    Template template = null;
    String fileName = "About.htm";
    try {
      template = servlet.getTemplate(fileName);
      StringWriter sw = new StringWriter();
      template.merge(context, sw);
      return sw.toString();
    }
    catch (Exception ex) {
      return "error get template " + fileName + " " + ex.getMessage();
    }
  }
}
  
     

其他 ProcessSubPage 的子類如上面基本類似,只不過會多了一些 context.put("xxx","xxxx") 的語句。

通過以上的例子,我們可以看到,使用 Velocity + Servlet , 所有的代碼為: 1 個 java serverlet + m 個 java class + n 個 Html 文件。

這里是用了集中處理,然后分發(fā)(dispatch)的機制。不用擔心用戶在沒有登陸的情況下訪問某些頁面。用戶驗證,頁眉頁腳包含都只寫一次,易于編寫、修改和維護。代碼比較簡潔,并且很容易加上自己的頁面緩沖功能。可以隨意將某個頁面的 html 在內(nèi)存中保存起來,緩存幾分鐘,實現(xiàn)頁面緩沖功能。成功、出錯頁面也可以用同樣的代碼封裝成函數(shù),通過參數(shù)將 Message/Title 傳入即可。

因為 Java 代碼與 Html 代碼完全在不同的文件中,美工與java代碼人員可以很好的分工,每個人修改自己熟悉的文件,基本上不需要花時間做協(xié)調(diào)工作。而用 JSP, 美工與java代碼人員共同修改維護 .jsp 文件,麻煩多多,噩夢多多。而且這里沒有用 xml ,說實話,懂 xml/xls 之類的人只占懂 Java 程序員中的幾分之一,人員不好找。

因為所有 java 代碼人員寫的都是標準 Java 程序,可以用任何 Java 編輯器,調(diào)試器,因此開發(fā)速度也會大大提高。美工寫的是標準 Html 文件,沒有 xml, 對于他們也很熟悉,速度也很快。并且,當需要網(wǎng)站改版的時候,只要美工把 html 文件重新修飾排版即可,完全不用改動一句 java 代碼。

爽死了!!

4) 工具類 Utilities.java

     
  import java.io.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import java.util.Date;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.velocity.*;
import org.apache.velocity.app.*;
import org.apache.velocity.context.Context;
import org.apache.velocity.servlet.*;

public class Utilities {
  private static Properties m_servletConfig = null;

  private Utilities() {
  }

  static {
    initJavaMail();
  }

  public static void debugPrintln(Object o) {
    String msg = "proj debug message at " + getNowTimeString() +
      " ------------- ";
    System.err.println(msg + o);
  }

  public static Properties initServletEnvironment(VelocityServlet v) {
    // init only once
    if (m_servletConfig != null) {
      return m_servletConfig;
    }

    //debugPrintln("initServletEnvironment....");

    try {
      /*
       * call the overridable method to allow the
       * derived classes a shot at altering the configuration
       * before initializing Runtime
       */
      Properties p = new Properties();

      ServletConfig config = v.getServletConfig();

      // Set the Velocity.FILE_RESOURCE_LOADED_PATH property
      // to the root directory of the context.
      String path = config.getServletContext().getRealPath("/");
      //debugPrintln("real path of / is : " + path);
      p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);

      // Set the Velocity.RUNTIME_LOG property to be the file
      // velocity.log relative to the root directory
      // of the context.
      p.setProperty(Velocity.RUNTIME_LOG, path +
             "velocity.log");
// Return the Properties object.
//return p;

      Velocity.init(p);
      m_servletConfig = p;
      return p;
    }
    catch (Exception e) {
      debugPrintln(e.getMessage());
      //throw new ServletException("Error initializing Velocity: " + e);
    }
    return null;

    //this.getServletContext().getRealPath("/");
  }

  private static void initJavaMail() {
  }

  public static Connection getDatabaseConnection() {
    Connection con = null;
    try {
      InitialContext initCtx = new InitialContext();
      javax.naming.Context context = (javax.naming.Context) initCtx.
        lookup("java:comp/env");
      javax.sql.DataSource ds = (javax.sql.DataSource) context.lookup(
        "jdbc/TestDB");
      //Utilities.debugPrintln("ds = " + ds);
      con = ds.getConnection();
    }
    catch (Exception e) {
      Utilities.debugPrintln("Exception = " + e.getMessage());
      return null;
    }
    //Utilities.debugPrintln("con = " + con);
    return con;
  }

  public static java.sql.ResultSet excuteDbQuery(Connection con, String sql,
    Object[] parameters) {
    //Exception err = null;
    //Utilities.debugPrintln("excuteDbQuery" + parameters[0] + " ,sql=" + sql);

    try {
      java.sql.PreparedStatement ps = con.prepareStatement(sql);
      for (int i = 0; i < parameters.length; i++) {
        processParameter(ps, i + 1, parameters[i]);
      }
      return ps.executeQuery();
    }
    catch (Exception e) {
      //Utilities.debugPrintln(e.getMessage());
      e.printStackTrace();
    }
    return null;
  }

  public static void excuteDbUpdate(String sql, Object[] parameters) {
    Connection con = Utilities.getDatabaseConnection();
    excuteDbUpdate(con, sql, parameters);
    closeDbConnection(con);
  }

  public static void excuteDbUpdate(Connection con, String sql,
                   Object[] parameters) {
    Exception err = null;
    try {
      java.sql.PreparedStatement ps = con.prepareStatement(sql);
      for (int i = 0; i < parameters.length; i++) {
        processParameter(ps, i + 1, parameters[i]);
      }
      ps.execute();
    }
    catch (Exception e) {
      err = e;
      //Utilities.debugPrintln(err.getMessage());
      e.printStackTrace();
    }
  }

  private static void processParameter(java.sql.PreparedStatement ps,
                     int index, Object parameter) {
    try {
      if (parameter instanceof String) {
        ps.setString(index, (String) parameter);
      }
      else {
        ps.setObject(index, parameter);
      }
    }
    catch (Exception e) {
      //Utilities.debugPrintln(e.getMessage());
      e.printStackTrace();
    }
  }

  public static void closeDbConnection(java.sql.Connection con) {
    try {
      con.close();
    }
    catch (Exception e) {
      Utilities.debugPrintln(e.getMessage());
    }
  }

  public static String getResultPage(
    String title, String message, String jumpLink,
    VelocityServlet servlet, HttpServletRequest request,
    HttpServletResponse response, Context context) {

    Template template = null;

    context.put("MessageTitle", title);
    context.put("ResultMessage", message);
    context.put("JumpLink", jumpLink);

    try {
      template = servlet.getTemplate(
        "/templates/Message.htm");
      StringWriter sw = new StringWriter();
      template.merge(context, sw);
      return sw.toString();
    }
    catch (Exception ex) {
      return "error get template Message.htm " + ex.getMessage();
    }

  }

  public static String mergeTemplate(String fileName, VelocityServlet servlet,
                    Context context) {
    Template template = null;

    try {
      template = servlet.getTemplate(fileName);
      StringWriter sw = new StringWriter();
      template.merge(context, sw);
      return sw.toString();
    }
    catch (Exception ex) {
      return "error get template " + fileName + " " + ex.getMessage();
    }
  }

}

  



黑咖啡 2006-03-08 17:21 發(fā)表評論
]]>
主站蜘蛛池模板: 亚洲区日韩精品中文字幕| 中文字幕亚洲激情| 91福利免费视频| 99re热精品视频国产免费| 免费精品国产自产拍在| 日本无吗免费一二区| 四虎在线播放免费永久视频 | 国产精品无码一区二区三区免费 | 国产精品亚洲综合一区| 猫咪www免费人成网站| 国产成人无码区免费网站| 性做久久久久久免费观看| 国产亚洲自拍一区| 国产精品免费久久久久久久久 | 免费国产a国产片高清网站| 亚洲色图视频在线观看| 国产精品亚洲一区二区三区在线观看| 在线毛片片免费观看| 亚洲高清在线播放| 亚洲AV日韩综合一区| 最近中文字幕mv免费高清在线 | 国产乱码免费卡1卡二卡3卡| 亚洲中文字幕无码中文字| 久久99精品视免费看| 亚洲人成国产精品无码| 亚洲日韩精品无码专区加勒比 | 日本免费人成黄页网观看视频 | 成全高清视频免费观看| 亚洲福利视频一区| 国产91免费在线观看| 亚洲av不卡一区二区三区| ww在线观视频免费观看| 亚洲av无码乱码国产精品| 人与动性xxxxx免费| 免费看AV毛片一区二区三区| 亚洲国产午夜电影在线入口| 精品亚洲永久免费精品| 亚洲中文字幕无码永久在线| 春意影院午夜爽爽爽免费| 亚洲激情在线观看| 无码人妻精品中文字幕免费|