以下是我在生成新闻的静态文件时用到的代码.仅供参考.请根据实际情况修改.
模板:  

<html>
<head>

<title>查看文章: ${newsitem.title} </title>
</head>

<body>
<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
<tr><td>
<table width="95%" border="0" align="center" cellpadding="2" cellspacing="6" >
    <tr>
      <td height="10" align="left" colspan=2 ></td>
    </tr>
    <tr>
           <td align="left" width="538" >
           <strong>${newsitem.title}</strong> ( ${newsitem.addtime} )
          </td>
          <td align="right">
            <a href="index.jsp">返回</a>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          </td>
    </tr>
    <tr>                      
         <td align="left" valign=top colspan=2>
         <hr align="left"  width="95%" size="1" noshade color="#cc0000" >
         </td>
    </tr>
    <tr>                      
      <td colspan=2>${newsitem.showContent}
      </td>
    </tr>
</table>            
            
<br>
</td></tr>
</table>
</body>

</html>

 


代码:

 
import java.io.*;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import freemarker.template.*;
/*
* Created on 2005-4-7
 *
 */
 
/**
 * 测试FreeMarker.
 *
 * @author scud
 *
 */
public class FreeMarkerTest
{
 
        private final Log logger = LogFactory.getLog(getClass());
       
        private Configuration freemarker_cfg = null;
       
       
       
        public static void main(String[] args)
        {
            //@todo 自己的一个类
            NewsItem aItem = null;
           
            //@todo 装入新闻
            //NewsItem = loadNewsItem(1);
               
            FreeMarkerTest test = new FreeMarkerTest();
           
            Map root = new HashMap();
            root.put("newsitem", aItem);
 
            String sGeneFilePath = "/tpxw/";
           
            String sFileName = "1.htm";
 
            boolean bOK = test.geneHtmlFile("/tpxw/view.ftl",root, sGeneFilePath,sFileName);
           
        }
       
 
        /**
         * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.
         */
        protected Configuration getFreeMarkerCFG()
        {
            if (null == freemarker_cfg)
            {
                // Initialize the FreeMarker configuration;
                // - Create a configuration instance
                freemarker_cfg = new Configuration();
 
                // - FreeMarker支持多种模板装载方式,可以查看API文档,都很简单:路径,根据Servlet上下文,classpath等等
               
                //htmlskin是放在classpath下的一个目录
                freemarker_cfg.setClassForTemplateLoading(this.getClass(), "/htmlskin");
            }
           
            return freemarker_cfg;
        }
 
        /**
         * 生成静态文件.
         *
         * @param templateFileName 模板文件名,相对htmlskin路径,例如"/tpxw/view.ftl"
         * @param propMap 用于处理模板的属性Object映射
         * @param htmlFilePath 要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/"
         * @param htmlFileName 要生成的文件名,例如 "1.htm"
         */
        public boolean geneHtmlFile(String templateFileName,Map propMap, String htmlFilePath,String htmlFileName )
        {
               //@todo 从配置中取得要静态文件存放的根路径:需要改为自己的属性类调用
            String sRootDir = "e:/webtest/htmlfile" ;
           
            try
            {
                Template t = getFreeMarkerCFG().getTemplate(templateFileName);
 
                //如果根路径存在,则递归创建子目录
                creatDirs(sRootDir,htmlFilePath);
               
                File afile = new File(sRootDir +"/" +htmlFilePath + "/" + htmlFileName);
 
                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(afile)));
 
                t.process(propMap, out);
            }
            catch (TemplateException e)
            {
                logger.error("Error while processing FreeMarker template " + templateFileName,e);
                return false;
            }
            catch (IOException e)
            {
                logger.error("Error while generate Static Html File " + htmlFileName,e);
                return false;
            }
 
            return true;
        }
       
       
 
        /**
         * 创建多级目录
         *
         * @param aParentDir String
         * @param aSubDir  以 / 开头
         * @return boolean 是否成功
         */
        public static boolean creatDirs(String aParentDir, String aSubDir)
        {
            File aFile = new File(aParentDir);
            if (aFile.exists())
            {
                File aSubFile = new File(aParentDir + aSubDir);
                if (!aSubFile.exists())
                {
                    return aSubFile.mkdirs();
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }     
   
}
 

Posted on December 11, 2006 9:37 PM | | Comments (0) | TrackBacks (0)

import java.util.*;

public class A{
    public static void main(String[] args){
        List list=new ArrayList();
        for(int i=0;i<10;i++)
            list.add(i);
        Iterator it=list.iterator();
        while(it.hasNext())
            System.out.println(it.next());
    }
}

Posted on December 11, 2006 4:51 PM | | Comments (0) | TrackBacks (0)

正向使用:native2ascii cn.properties po.properites
反向使用:native2ascii -reverse cn.properties po.properites

cn.properties是未转换前的文件,po.properites是转换后的文件

PropertiesEditor是一个不错的属性编辑器。

Posted on December 8, 2006 10:05 PM | | Comments (0) | TrackBacks (0)

热键篇:

Template:Alt + /

修改处:Window->Preference->Workbench->Keys->Command->Edit->Content Assist。

个人习惯:Shift+SPACE(空白)。

简易说明:编辑程序代码时,打sysout +Template启动键,就

会自动出现:System.out.println(); 。

设定Template的格式:窗口->喜好设定->Java->编辑器->模板。

程序代码自动排版:Ctrl+Shift+F

修改处:窗口->喜好设定->工作台->按键->程序代码->格式。

个人习惯:Alt+Z。

自动排版设定:窗口->喜好设定->Java->程序代码格式制作程序。

样式页面->将插入tab(而非空格键)以内缩,该选项取消勾选

,下面空格数目填4,这样在自动编排时会以空格4作缩排。

快速执行程序:Ctrl + F11

个人习惯:ALT+X

修改处:窗口->喜好设定->工作台->按键->执行->启动前一次的启动作业。

简易说明:第一次执行时,它会询问您执行模式,

设置好后,以后只要按这个热键,它就会快速执行。

<ALT+Z(排版完)、ATL+X(执行)>..我觉得很顺手^___^

自动汇入所需要的类别:Ctrl+Shift+O

简易说明:

假设我们没有Import任何类别时,当我们在程序里打入:

BufferedReader buf =

new BufferedReader(new InputStreamReader(System.in));

此时Eclipse会警示说没有汇入类别,这时我们只要按下Ctrl+Shift+O

,它就会自动帮我们Import类别。

查看使用类别的原始码:Ctrl+鼠标左键点击

简易说明:可以看到您所使用类别的原始码。

将选取的文字批注起来:Ctrl+/

简易说明:Debug时很方便。

修改处:窗口->喜好设定->工作台->按键->程序代码->批注

将选取的文字取消批注:Ctrl+简易说明:同上。

修改处:窗口->喜好设定->工作台->按键->程序代码->取消批注

视景切换:Ctrl+F8

个人习惯:Alt+S。

修改处:窗口->喜好设定->工作台->按键->窗口->下一个视景。

简易说明:可以方便我们快速切换编辑、除错等视景。

3.0里Ctrl+Alt+H可以看到调用当前member的方法,而且可以一层一层上去.

Ctrl+O可以快速切到其他方法.

密技篇:

一套Eclipse可同时切换,英文、繁体、简体显示:

1.首先要先安装完中文化包。

2.在桌面的快捷方式后面加上参数即可,

英文-> -nl "zh_US"

繁体-> -nl "zh_TW"

简体-> -nl "zh_CN"。

(其它语系以此类推)

像我2.1.2中文化后,我在我桌面的Eclipse快捷方式加入参数-n1 "zh_US"。

"C:\Program Files\eclipse\eclipse.exe" -n "zh_US"

接口就会变回英文语系噜。

利用Eclipse,在Word编辑文书时可不必将程序代码重新编排:

将Eclipse程序编辑区的程序代码整个复制下来(Ctrl+C),直接贴(Ctrl+V)到

Word或WordPad上,您将会发现在Word里的程序代码格式,跟Eclipse

所设定的完全一样,包括字型、缩排、关键词颜色。我曾试过JBuilder

、GEL、NetBeans...使用复制贴上时,只有缩排格式一样,字型、颜

色等都不会改变。

外挂篇:

外挂安装:将外挂包下载回来后,将其解压缩后,您会发现features、

plugins这2个数据夹,将里面的东西都复制或移动到Eclipse的features

、plugins数据夹内后,重新启动Eclipse即可。

让Eclipse可以像JBuilderX一样使用拖拉方式建构GUI的外挂:

1.Jigloo SWT/Swing GUI Builder :

http://cloudgarden.com/jigloo/index.html

下载此版本:Jigloo plugin for Eclipse (using Java 1.4 or 1.5)

安装后即可由档案->新建->其它->GUI Form选取要建构的GUI类型。

2.Eclipse Visual Editor Project:

http://www.eclipse.org/vep/

点选下方Download Page,再点选Latest Release 0.5.0进入下载。

除了VE-runtime-0.5.0.zip要下载外,以下这2个也要:

EMF build 1.1.1: (build page) (download zip)

GEF Build 2.1.2: (build page) (download zip)

我只测试过Eclipse 2.1.2版本,使用上是OK的!

3.0版本以上的使用者,请下载:

Eclipse build I20040324:

1.0.0 Stream Integration Build I20040325 Thu, 25 Mar 2004 -- 12:09 (-0500)

1.0.0 Stream Nightly Build N20040323a Tue, 23 Mar 2004 -- 13:53 (-0500)

注意:3.0以上版本,仅build I20040324可正常使用。

安装成功后,即可由新建->Java->AWT与Swing里选择

所要建构的GUI类型开始进行设计。VE必须配合着对应

版本,才能正常使用,否则即使安装成功,使用上仍会

有问题。

使用Eclipse来开发JSP程序:

外挂名称:lomboz(下载页面)

http://forge.objectweb.org/project/showfiles.php?group_id=97

请选择适合自己版本的lomboz下载,lomboz.212.p1.zip表示2.1.2版,

lomboz.3m7.zip表示M7版本....以此类推。

lomboz安装以及设置教学:

Eclipse开发JSP-教学文件

Java转exe篇:

实现方式:Eclipse搭配JSmooth(免费)。

1.先由Eclipse制作包含Manifest的JAR。

制作教学

2.使用JSmooth将做好的JAR包装成EXE。

JSmooth下载页面:

http://jsmooth.sourceforge.net/index.php

3.制作完成的exe文件,可在有装置JRE的Windows上执行。

Eclipse-Java编辑器最佳设定:

编辑器字型设定:工作台->字型->Java编辑器文字字型。

(建议设定Courier New -regular 10)

编辑器相关设定:窗口->喜好设定->Java->编辑器

外观:显示行号、强调对称显示的方括号、强调显示现行行、

显示打印边距,将其勾选,Tab宽度设4,打印编距字段设80。

程序代码协助:采预设即可。

语法:可设定关键词、字符串等等的显示颜色。

附注:采预设即可。

输入:全部字段都勾选。

浮动说明:采预设即可。

导览:采预设即可。

使自动排版排出来的效果,最符合Java设计惯例的设定:

自动排版设定:窗口->喜好设定->Java->程序代码制作格式。

换行:全部不勾选。

分行:行长度上限设:80。

样式:只将强制转型后插入空白勾选。

内缩空格数目:设为4。

Eclipse的教学文件:

扩充Eclipse的Java 开发工具(中文)

使用Eclipse开发J2EE 应用程序(中文)

使用Eclipse平台进行除错(中文)

用Eclipse进行XML 开发(中文)

开发Eclipse外挂程序(中文)

国际化您的Eclipse外挂程序(英文)

将Swing编辑器加入Eclipse(英文)

如何测试你的Eclipse plug-in符合国际市场需求(英文)

Eclipse的相关网站:

http://eclipse-plugins.2y.net/eclipse/index.jsp

http://www.eclipseplugincentral.com/

Eclipse相关教学[简体]

Posted on December 5, 2006 10:55 PM | | Comments (0) | TrackBacks (0)

1.简介
在一般的写bean组件的时候,都必须要写setter和getter方法,当然如果我们事先已经知道bean的相关属性和
方法,写bean是比较简单的,但是组件太多的时候,重复编写常常是枯燥乏味令人厌烦的。但当有些时候我么需
要调用动态对象的属性的时候,我们应该怎么来设定和获取对象的属性呢?BeanUtils就可以帮助我们来解决这
个问题。它需要Collections包和logging包的支持。最新版本1.7,文档还是1.6.1的.
2.已经使用BeanUtils的事例
*构建和java对象模型交互的脚本语言,比如Bean Scripting Framework
*构建web层显示和相似用途的模板语言处理器,如jsp或者Velocity
*构建适用于jsp和xsp环境的自定义标签库,如Jakarta Taglibs,Struts,Cocoon
*处理基于xml的配置资源文件,如Ant创建脚本,应用程序部署文件和Tomcat的xml配置文件
3.API简介
BeanUtils 的 Java API 主要的 package 总共四个
org.apache.commons.beanutils
这个是BeanUtils最基本的包,提供了处理getter和setter方法属性的类
org.apache.commons.beanutils.converters
Converter接口的标准实现,在启动的时候和ConvertUtils一同注册
org.apache.commons.beanutils.locale
组件的本地化处理包
org.apache.commons.beanutils.locale.converters
LocaleConverter接口的标准实现,启动的时候和LocaleConvertUtils 一同注册
4.org.apache.commons.beanutils介绍
这四个包本专题只介绍这一个,其他的使用的时候请自己参考它的文档,文档内容写得很好.
 1.PropertyUtils
 它支持三种类型的属性值-Simple,Indexed,Mapped
 我们先创建一个简单的bean
     public class Employee {
        public Address getAddress(String type);
        public void setAddress(String type, Address address);
        public Employee getSubordinate(int index);
        public void setSubordinate(int index, Employee subordinate);
        public String getFirstName();
        public void setFirstName(String firstName);
        public String getLastName();
        public void setLastName(String lastName);
    }
 *Simple属性访问方法
 PropertyUtils.getSimpleProperty(Object bean, String name)
 PropertyUtils.setSimpleProperty(Object bean, String name, Object value)
 实现代码:
     Employee employee = ...;
    String firstName = (String)
      PropertyUtils.getSimpleProperty(employee, "firstName");
    String lastName = (String)
      PropertyUtils.getSimpleProperty(employee, "lastName");
    ... manipulate the values ...
    PropertyUtils.setSimpleProperty(employee, "firstName", firstName);
    PropertyUtils.setSimpleProperty(employee, "lastName", lastName);
 *Indexed属性访问方法
 PropertyUtils.getIndexedProperty(Object bean, String name)
 PropertyUtils.getIndexedProperty(Object bean, String name, int index)
 PropertyUtils.setIndexedProperty(Object bean, String name, Object value)
 PropertyUtils.setIndexedProperty(Object bean, String name, int index, Object value)
 实现代码:
 Employee employee = ...;
    int index = ...;
    String name = "subordinate[" + index + "]";
    Employee subordinate = (Employee)
    PropertyUtils.getIndexedProperty(employee, name);//根据value取得属性

    Employee employee = ...;
    int index = ...;
    Employee subordinate = (Employee)
    PropertyUtils.getIndexedProperty(employee, "subordinate", index);//根据索引
 值取的属性值
 *Mapped属性访问方法
 PropertyUtils.getMappedProperty(Object bean, String name)
 PropertyUtils.getMappedProperty(Object bean, String name, String key)
 PropertyUtils.setMappedProperty(Object bean, String name, Object value)
 PropertyUtils.setMappedProperty(Object bean, String name, String key, Object value)
 实现代码:
 Employee employee = ...;
    Address address = ...;
    PropertyUtils.setMappedProperty(employee, "address(home)", address);//根据数组
 //内的值来去的相应的属性值
    Employee employee = ...;
    Address address = ...;
    PropertyUtils.setMappedProperty(employee, "address", "home", address);
 *Nested属性访问方法//Nested的意思是参数中包含组件
 PropertyUtils.getNestedProperty(Object bean, String name)
 PropertyUtils.setNestedProperty(Object bean, String name, Object value)
 实现代码:
 String city = (String) PropertyUtils.getNestedProperty(employee,
 "address(home).city");
 2.BeanUtils.DynaBean and BeanUtils.DynaClass 接口介绍
 DynaBean必须有一个bean来实现这个接口,DynaClass必有一个bean的属性集来实现
 *BasicDynaBean and BasicDynaClass - 基本的 Dynamic 类型
 基本的API:
 BasicDynaClass(java.lang.String name, java.lang.Class dynaBeanClass, DynaProperty[] properties)
 BasicDynaBean(DynaClass dynaClass)
 我们线定义一下基本的代码:
 //定义动态属性集
 DynaProperty[] props = new DynaProperty[]{
    new DynaProperty("address", java.util.Map.class),
    new DynaProperty("subordinate", mypackage.Employee[].class),
    new DynaProperty("firstName", String.class),
    new DynaProperty("lastName",  String.class)
      };
 //创建动态类来设定动态属性值
    BasicDynaClass dynaClass = new BasicDynaClass("employee", null, props);
 DynaBean employee = dynaClass.newInstance();
    employee.set("address", new HashMap());
    employee.set("subordinate", new mypackage.Employee[0]);
    employee.set("firstName", "Fred");
    employee.set("lastName", "Flintstone");
 *ResultSetDynaClass (Wraps ResultSet in DynaBeans) - 使用 ResultSet 的
 Dynamic JavaBean
 API:
 ResultSetDynaClass(java.sql.ResultSet resultSet)
 ResultSetDynaClass(java.sql.ResultSet resultSet, boolean lowerCase)
 Connection conn = ...;
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery
    ("select account_id, name from customers");
    Iterator rows = (new ResultSetDynaClass(rs)).iterator();
    while (rows.hasNext()) {
 //利用动态bean进行输出
    DynaBean row = (DynaBean) rows.next();
    System.out.println("Account number is " +
                       row.get("account_id") +
                       " and name is " + row.get("name"));
    }
    rs.close();
    stmt.close();
 *RowSetDynaClass (Disconnected ResultSet as DynaBeans) - 使用 RowSet 的 Dynamic
 JavaBean
 API:
 RowSetDynaClass(java.sql.ResultSet resultSet)
 RowSetDynaClass(java.sql.ResultSet resultSet, boolean lowerCase)
 
    Connection conn = ...;  // 从缓冲池取得连接
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT ...");
    RowSetDynaClass rsdc = new RowSetDynaClass(rs);
    rs.close();
    stmt.close();
    ...;                    //关闭连接返回缓冲池
    List rows = rsdc.getRows();
    ...;                   // 处理得到的行
 2.BeanUtils.ConvertUtils 介绍
 这个包主要用来转换从request传递过来的函数
 主要函数:
 ConvertUtils().convert(java.lang.Object value)
 ConvertUtils().convert(java.lang.String[] values, java.lang.Class clazz)
 ConvertUtils().convert(java.lang.String value, java.lang.Class clazz)
 实现例子:
    HttpServletRequest request = ...;
    MyBean bean = ...;
    HashMap map = new HashMap();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      map.put(name, request.getParameterValues(name));
    }
    BeanUtils.populate(bean, map);//用ConvertUtils进行转换
 目前支持的转换类型:
 sjava.lang.BigDecimal
 java.lang.BigInteger
 boolean and java.lang.Boolean
 byte and java.lang.Byte
 char and java.lang.Character
 java.lang.Class
 double and java.lang.Double
 float and java.lang.Float
 int and java.lang.Integer
 long and java.lang.Long
 short and java.lang.Short
 java.lang.String
 java.sql.Date
 java.sql.Time
 java.sql.Timestamp
5.参考资料或文章:
*http://jakarta.apache.org/commons/beanutils/api/index.html
*http://jakarta.apache.org/commons/beanutils/index.html
*http://apache.linuxforum.net/dist/jakarta/commons/beanutils/binaries/commons-beanutils-1.6.1.zip
本文使用源代码均来自apache

Posted on December 4, 2006 9:49 PM | | Comments (0) | TrackBacks (0)

Jakarta Commons BeanUtils
1.简介
在一般的写bean组件的时候,都必须要写setter和getter方法,当然如果我们事先已经知道bean的相关属性和
方法,写bean是比较简单的,但是组件太多的时候,重复编写常常是枯燥乏味令人厌烦的。但当有些时候我么需
要调用动态对象的属性的时候,我们应该怎么来设定和获取对象的属性呢?BeanUtils就可以帮助我们来解决这
个问题。它需要Collections包和logging包的支持。最新版本1.7,文档还是1.6.1的.
2.已经使用BeanUtils的事例
*构建和java对象模型交互的脚本语言,比如Bean Scripting Framework
*构建web层显示和相似用途的模板语言处理器,如jsp或者Velocity
*构建适用于jsp和xsp环境的自定义标签库,如Jakarta Taglibs,Struts,Cocoon
*处理基于xml的配置资源文件,如Ant创建脚本,应用程序部署文件和Tomcat的xml配置文件
3.API简介
BeanUtils 的 Java API 主要的 package 总共四个
org.apache.commons.beanutils
这个是BeanUtils最基本的包,提供了处理getter和setter方法属性的类
org.apache.commons.beanutils.converters
Converter接口的标准实现,在启动的时候和ConvertUtils一同注册
org.apache.commons.beanutils.locale
组件的本地化处理包
org.apache.commons.beanutils.locale.converters
LocaleConverter接口的标准实现,启动的时候和LocaleConvertUtils 一同注册
4.org.apache.commons.beanutils介绍
这四个包本专题只介绍这一个,其他的使用的时候请自己参考它的文档,文档内容写得很好.
 1.PropertyUtils
 它支持三种类型的属性值-Simple,Indexed,Mapped
 我们先创建一个简单的bean
     public class Employee {
        public Address getAddress(String type);
        public void setAddress(String type, Address address);
        public Employee getSubordinate(int index);
        public void setSubordinate(int index, Employee subordinate);
        public String getFirstName();
        public void setFirstName(String firstName);
        public String getLastName();
        public void setLastName(String lastName);
    }
 *Simple属性访问方法
 PropertyUtils.getSimpleProperty(Object bean, String name)
 PropertyUtils.setSimpleProperty(Object bean, String name, Object value)
 实现代码:
     Employee employee = ...;
    String firstName = (String)
      PropertyUtils.getSimpleProperty(employee, "firstName");
    String lastName = (String)
      PropertyUtils.getSimpleProperty(employee, "lastName");
    ... manipulate the values ...
    PropertyUtils.setSimpleProperty(employee, "firstName", firstName);
    PropertyUtils.setSimpleProperty(employee, "lastName", lastName);
 *Indexed属性访问方法
 PropertyUtils.getIndexedProperty(Object bean, String name)
 PropertyUtils.getIndexedProperty(Object bean, String name, int index)
 PropertyUtils.setIndexedProperty(Object bean, String name, Object value)
 PropertyUtils.setIndexedProperty(Object bean, String name, int index, Object value)
 实现代码:
 Employee employee = ...;
    int index = ...;
    String name = "subordinate[" + index + "]";
    Employee subordinate = (Employee)
    PropertyUtils.getIndexedProperty(employee, name);//根据value取得属性

    Employee employee = ...;
    int index = ...;
    Employee subordinate = (Employee)
    PropertyUtils.getIndexedProperty(employee, "subordinate", index);//根据索引
 值取的属性值
 *Mapped属性访问方法
 PropertyUtils.getMappedProperty(Object bean, String name)
 PropertyUtils.getMappedProperty(Object bean, String name, String key)
 PropertyUtils.setMappedProperty(Object bean, String name, Object value)
 PropertyUtils.setMappedProperty(Object bean, String name, String key, Object value)
 实现代码:
 Employee employee = ...;
    Address address = ...;
    PropertyUtils.setMappedProperty(employee, "address(home)", address);//根据数组
 //内的值来去的相应的属性值
    Employee employee = ...;
    Address address = ...;
    PropertyUtils.setMappedProperty(employee, "address", "home", address);
 *Nested属性访问方法//Nested的意思是参数中包含组件
 PropertyUtils.getNestedProperty(Object bean, String name)
 PropertyUtils.setNestedProperty(Object bean, String name, Object value)
 实现代码:
 String city = (String) PropertyUtils.getNestedProperty(employee,
 "address(home).city");
 2.BeanUtils.DynaBean and BeanUtils.DynaClass 接口介绍
 DynaBean必须有一个bean来实现这个接口,DynaClass必有一个bean的属性集来实现
 *BasicDynaBean and BasicDynaClass - 基本的 Dynamic 类型
 基本的API:
 BasicDynaClass(java.lang.String name, java.lang.Class dynaBeanClass, DynaProperty[] properties)
 BasicDynaBean(DynaClass dynaClass)
 我们线定义一下基本的代码:
 //定义动态属性集
 DynaProperty[] props = new DynaProperty[]{
    new DynaProperty("address", java.util.Map.class),
    new DynaProperty("subordinate", mypackage.Employee[].class),
    new DynaProperty("firstName", String.class),
    new DynaProperty("lastName",  String.class)
      };
 //创建动态类来设定动态属性值
    BasicDynaClass dynaClass = new BasicDynaClass("employee", null, props);
 DynaBean employee = dynaClass.newInstance();
    employee.set("address", new HashMap());
    employee.set("subordinate", new mypackage.Employee[0]);
    employee.set("firstName", "Fred");
    employee.set("lastName", "Flintstone");
 *ResultSetDynaClass (Wraps ResultSet in DynaBeans) - 使用 ResultSet 的
 Dynamic JavaBean
 API:
 ResultSetDynaClass(java.sql.ResultSet resultSet)
 ResultSetDynaClass(java.sql.ResultSet resultSet, boolean lowerCase)
 Connection conn = ...;
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery
    ("select account_id, name from customers");
    Iterator rows = (new ResultSetDynaClass(rs)).iterator();
    while (rows.hasNext()) {
 //利用动态bean进行输出
    DynaBean row = (DynaBean) rows.next();
    System.out.println("Account number is " +
                       row.get("account_id") +
                       " and name is " + row.get("name"));
    }
    rs.close();
    stmt.close();
 *RowSetDynaClass (Disconnected ResultSet as DynaBeans) - 使用 RowSet 的 Dynamic
 JavaBean
 API:
 RowSetDynaClass(java.sql.ResultSet resultSet)
 RowSetDynaClass(java.sql.ResultSet resultSet, boolean lowerCase)
 
    Connection conn = ...;  // 从缓冲池取得连接
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT ...");
    RowSetDynaClass rsdc = new RowSetDynaClass(rs);
    rs.close();
    stmt.close();
    ...;                    //关闭连接返回缓冲池
    List rows = rsdc.getRows();
    ...;                   // 处理得到的行
 2.BeanUtils.ConvertUtils 介绍
 这个包主要用来转换从request传递过来的函数
 主要函数:
 ConvertUtils().convert(java.lang.Object value)
 ConvertUtils().convert(java.lang.String[] values, java.lang.Class clazz)
 ConvertUtils().convert(java.lang.String value, java.lang.Class clazz)
 实现例子:
    HttpServletRequest request = ...;
    MyBean bean = ...;
    HashMap map = new HashMap();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      map.put(name, request.getParameterValues(name));
    }
    BeanUtils.populate(bean, map);//用ConvertUtils进行转换
 目前支持的转换类型:
 sjava.lang.BigDecimal
 java.lang.BigInteger
 boolean and java.lang.Boolean
 byte and java.lang.Byte
 char and java.lang.Character
 java.lang.Class
 double and java.lang.Double
 float and java.lang.Float
 int and java.lang.Integer
 long and java.lang.Long
 short and java.lang.Short
 java.lang.String
 java.sql.Date
 java.sql.Time
 java.sql.Timestamp
5.参考资料或文章:
*http://jakarta.apache.org/commons/beanutils/api/index.html
*http://jakarta.apache.org/commons/beanutils/index.html
*http://apache.linuxforum.net/dist/jakarta/commons/beanutils/binaries/commons-beanutils-1.6.1.zip
本文使用源代码均来自apache

Posted on December 4, 2006 9:47 PM | | Comments (0) | TrackBacks (0)

一、概述
第一次看到BeanUtils包,是在Struts项目中,作为Struts一个工具来使用的,
估计功能越弄越强,就移到Common项目中了吧。

BeanUtils一共有四个package:
org.apache.commons.beanutils
org.apache.commons.beanutils.converters
org.apache.commons.beanutils.locale
org.apache.commons.beanutils.locale.converters
后三个包主要是用于数据的转换,围绕着一个Converter接口,该接口只有一个方法:
java.lang.Object convert(java.lang.Class type, java.lang.Object value) ,
用于将一个value转换成另一个类型为type的Object。在一些自动化的应用中应该会有用。
这里不作评论,以后有兴趣了,或者觉得有用了,再行研究。
这里只讲第一个包。

Continue reading "Jakarta-Common-BeanUtils研究心得[转载]"
Posted on December 4, 2006 9:45 PM | | Comments (0) | TrackBacks (0)

一、概述
第一次看到BeanUtils包,是在Struts项目中,作为Struts一个工具来使用的,
估计功能越弄越强,就移到Common项目中了吧。

BeanUtils一共有四个package:
org.apache.commons.beanutils
org.apache.commons.beanutils.converters
org.apache.commons.beanutils.locale
org.apache.commons.beanutils.locale.converters
后三个包主要是用于数据的转换,围绕着一个Converter接口,该接口只有一个方法:
java.lang.Object convert(java.lang.Class type, java.lang.Object value) ,
用于将一个value转换成另一个类型为type的Object。在一些自动化的应用中应该会有用。
这里不作评论,以后有兴趣了,或者觉得有用了,再行研究。
这里只讲第一个包。

二、测试用的Bean
在开始所有的测试之前,我写了一个简单的Bean,以便于测试,代码如下:
package test.jakarta.commons.beanutils;

/**
 * @author SonyMusic
 *
 */
public class Month {
 private int value;
 private String name;
 private int[] days={11,22,33,44,55};

 public Month(int v, String n){
   value=v;
   name=n;
 }
 
 /**
  * Returns the name.
  * @return String
  */
 public String getName() {
   return name;
 }

 /**
  * Returns the value.
  * @return int
  */
 public int getValue() {
   return value;
 }

 /**
  * Sets the name.
  * @param name The name to set
  */
 public void setName(String name) {
   this.name = name;
 }

 /**
  * Sets the value.
  * @param value The value to set
  */
 public void setValue(int value) {
   this.value = value;
 }

 /**
  * @see java.lang.Object#toString()
  */
 public String toString() {
   return value+"("+name+")";
 }

 public int[] getDays() {
   return days;
 }

 public void setDays(int[] is) {
   days = is;
 }

}

三、BeanUtils
这是一个主要应用于Bean的Util(呵呵,这个解释很绝吧),以下是其中几个方法的例子

//static java.util.Map describe(java.lang.Object bean)
//这个方法返回一个Object中所有的可读属性,并将属性名/属性值放入一个Map中,另外还有
//一个名为class的属性,属性值是Object的类名,事实上class是java.lang.Object的一个属性
 Month month=new Month(1, "Jan");
 
 try {
   Map map=BeanUtils.describe(month);
   Set keySet=map.keySet();
   for (Iterator iter = keySet.iterator(); iter.hasNext();) {
     Object element = (Object) iter.next();
     System.out.println("KeyClass:"+element.getClass().getName());
     System.out.println("ValueClass:"+map.get(element).getClass().getName());
     System.out.print(element+"\t");
     System.out.print(map.get(element));
     System.out.println();
   }
 } catch (IllegalAccessException e) {
   e.printStackTrace();
 } catch (InvocationTargetException e) {
   e.printStackTrace();
 } catch (NoSuchMethodException e) {
   e.printStackTrace();
 }
输出为:
KeyClass:java.lang.String
ValueClass:java.lang.String
value  1
KeyClass:java.lang.String
ValueClass:java.lang.String
class  class test.jakarta.commons.beanutils.Month
KeyClass:java.lang.String
ValueClass:java.lang.String
name  Jan
注意到所有Map中的key/value都是String,而不管object中实际的值是多少。
与此对应的还有static void populate(java.lang.Object bean, java.util.Map properties)
用于将刚才describe出的Map再装配成一个对象。


再看这样一段代码
曹晓钢也许还记得,为了取一个不确定对象的property,着实花了不少时间,
难度不大,但要做到100%的正确,仍然需要付出很大的精力。
//static java.lang.String getProperty(java.lang.Object bean, java.lang.String name)
 Month month=new Month(1, "Jan");
 
 try {
   System.out.println(BeanUtils.getProperty(month,"value"));
 } catch (Exception e) {
   e.printStackTrace();
 }
//输出是:1

与getProperty类似的还有getIndexedProperty, getMappedProperty,
以getIndexedProperty为例:
 Month month=new Month(1, "Jan");
 
 try {
   System.out.println(BeanUtils.getIndexedProperty(month,"days",1));
   System.out.println(BeanUtils.getIndexedProperty(month,"days[1]"));
 } catch (Exception e) {
   e.printStackTrace();
 }
这两个调用是相同的。


BeanUtils中还有一个方法:
static void copyProperties(java.lang.Object dest, java.lang.Object orig)
它真是太有用,还记得struts中满天飞的都是copyProperties,我甚至怀疑整个BeanUtils最初
是不是因为这个方法的需求才写出来的。
它将对象orig中的属性复制到dest中去。


四、PropertyUtils
这个类和BeanUtils类很多的方法在参数上都是相同的,但返回值不同。
BeanUtils着重于"Bean",返回值通常是String,而PropertyUtils着重于属性,
它的返回值通常是Object。


五、ConstructorUtils
这个类中的方法主要分成两种,一种是得到构造方法,一种是创建对象。
事实上多数时候得到构造方法的目的就是创建对象,这里只介绍一下创建对象。
//static java.lang.Object ConstructorUtils.invokeConstructor
//(java.lang.Class klass, java.lang.Object[] args)
//根据一个java.lang.Class以及相应的构造方法的参数,创建一个对象。
 Object obj=ConstructorUtils.invokeConstructor(Month.class, {new Integer(1), "Jan"});
 Month month=(Month)obj;
 try {
   System.out.println(BeanUtils.getProperty(month,"value"));
 } catch (Exception e) {
   e.printStackTrace();
 }
输出证明,构造方法的调用是成功的。
如果需要强制指定构造方法的参数类型,可以这样调用:
   Object[] args={new Integer(1), "Jan"};
   Class[] argsType={int.class, String.class};
   Object obj;
   obj = ConstructorUtils.invokeExactConstructor(Month.class, args, argsType);
   Month month=(Month)obj;
   System.out.println(BeanUtils.getProperty(month,"value"));
argsType指定了参数的类型。

Posted on December 4, 2006 9:43 PM | | Comments (0) | TrackBacks (0)

用了rome 0,8的jar包,代码大部分来自于rome-samples-0.7 。其中加入了一个设置代理的代码,因为本机的环境需要设置代理才行,呵呵,等以后加强功能的时候这个设置还是挺有用的东西

对了,放个rome的链接Rome's Home,可以直接去下载

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

import java.net.*;
import java.util.Properties;


/**
 * @author dozhan
 *
 */


public class Writer {
 
    public static void main(String[] args){
        System.out.println("Start...");
        String str ="http://blog.csdn.net/zdsdiablo/Rss.aspx";
        Properties prop = System.getProperties();
        prop.put("http.proxyHost","192.168.0.1");    //这里填写代理的ip
        prop.put("http.proxyPort","8080");

        boolean ok = false;
        try {         

            URL feedUrl = new URL(str);

            SyndFeedInput input = new SyndFeedInput();

            SyndFeed feed = input.build(new XmlReader(feedUrl));

            System.out.println(feed);

            ok = true;
        }
        catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("ERROR: "+ex.getMessage());
        }


        if (!ok) {
            System.out.println();
            System.out.println("FeedReader reads and prints any RSS/Atom feed type.");
            System.out.println("The first parameter must be the URL of the feed to read.");
            System.out.println();
        }
       
    }
}

 

Start...
SyndFeedImpl.contributors=null
SyndFeedImpl.title=十分钟年华老去
SyndFeedImpl.categories=[]
SyndFeedImpl.link=http://blog.csdn.net/zdsdiablo/
SyndFeedImpl.publishedDate=null
SyndFeedImpl.entries[0].updatedDate=null
SyndFeedImpl.entries[0].contributors=null
SyndFeedImpl.entries[0].title=Java API文档中文版
SyndFeedImpl.entries[0].categories=[]
SyndFeedImpl.entries[0].link=http://blog.csdn.net/zdsdiablo/archive/2006/06/09/782902.aspx
SyndFeedImpl.entries[0].publishedDate=Fri Jun 09 22:35:00 GMT+08:00 2006
SyndFeedImpl.entries[0].authors=null

Posted on November 29, 2006 12:10 PM | | Comments (0) | TrackBacks (0)

下面是在 blog-mover 中实现的一个类,直接贴源码吧(代码中可能存在的Bug,对您造成的误解,我不负责哟,要查看全部源码请访问 http://code.google.com/p/blog-mover),关于 Rome 的更多信息参见 http://rome.dev.java.net. Rome 可是出自 Sun 之手。有着这样的 package name:com.sun.syndication。



/**
 * Created on 2006-9-10 上午02:32:57
 */
package com.redv.blogmover.feed;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;

import com.redv.blogmover.Attachment;
import com.redv.blogmover.BlogMoverException;
import com.redv.blogmover.Comment;
import com.redv.blogmover.WebLog;
import com.redv.blogmover.impl.AbstractBlogWriter;
import com.redv.blogmover.web.DownloadFileServlet;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

/**
 * 使用 <a href="https://rome.dev.java.net/">Rome</a> 将日志导出成下列格式:RSS 0.90, RSS
 * 0.91 Netscape, RSS 0.91 Userland, RSS 0.92, RSS 0.93, RSS 0.94, RSS 1.0, RSS
 * 2.0, Atom 0.3, and Atom 1.0。
 *
 * @author <a href="mailto:zhoushuqun@gmail.com">Shutra Zhou</a>
 *
 */
public class RomeWriter extends AbstractBlogWriter {
    private final Pattern pattern = DownloadFileServlet.TEMP_FILE_NAME_PATTERN;

    private final String encoding = "UTF-8";

    private SyndFeed feed;

    private List<SyndEntry> entries;

    private File outputFile;

    private String feedType;

    private String title;

    private String link;

    private String description;

    private String language;

    private String copyright;

    private String author;

    /**
     * @return the outputFile
     */
    public File getOutputFile() {
        return outputFile;
    }

    /**
     * @param outputFile
     *            the outputFile to set
     */
    public void setOutputFile(File outputFile) {
        this.outputFile = outputFile;
    }

    /**
     *
     * @param filePath
     *            the outputFile's name to set
     */
    public void setFilename(String filename) throws BlogMoverException {
        if (!pattern.matcher(filename).matches()) {
            throw new BlogMoverException("Parameter filename is not matched "
                    + this.pattern.pattern() + ".");
        }

        File tmpdir = new File(SystemUtils.JAVA_IO_TMPDIR);
        this.outputFile = new File(tmpdir, filename);
    }

    /**
     * @param author
     *            the author to set
     */
    public void setAuthor(String author) {
        this.author = author;
    }

    /**
     * @param copyright
     *            the copyright to set
     */
    public void setCopyright(String copyright) {
        this.copyright = copyright;
    }

    /**
     * @param description
     *            the description to set
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * @param feedType
     *            the feedType to set
     */
    public void setFeedType(String feedType) {
        this.feedType = feedType;
    }

    /**
     * @param language
     *            the language to set
     */
    public void setLanguage(String language) {
        this.language = StringUtils.replace(language, "_", "-");
    }

    /**
     * @param link
     *            the link to set
     */
    public void setLink(String link) {
        this.link = link;
    }

    /**
     * @param title
     *            the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.redv.blogmover.impl.AbstractBlogWriter#begin()
     */
    @Override
    protected void begin() throws BlogMoverException {
        this.feed = new SyndFeedImpl();
        this.feed.setEncoding(this.encoding);
        this.feed.setFeedType(this.feedType);
        this.feed.setTitle(this.title);
        this.feed.setLink(this.link);
        this.feed.setDescription(this.description);
        this.feed.setLanguage(this.language);
        this.feed.setCopyright(this.copyright);
        this.feed.setAuthor(this.author);
        this.entries = new ArrayList<SyndEntry>();
        this.feed.setEntries(this.entries);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.redv.blogmover.impl.AbstractBlogWriter#end()
     */
    @Override
    protected void end() throws BlogMoverException {
        SyndFeedOutput output = new SyndFeedOutput();
        OutputStream outputStream = null;
        Writer writer = null;
        try {
            outputStream = new FileOutputStream(this.outputFile);
            writer = new OutputStreamWriter(outputStream, this.encoding);
            output.output(feed, writer);
        } catch (IOException e) {
            throw new BlogMoverException(e);
        } catch (FeedException e) {
            throw new BlogMoverException(e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    log.warn(e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.warn(e);
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see com.redv.blogmover.impl.AbstractBlogWriter#writeAttachment(com.redv.blogmover.Attachment)
     */
    @Override
    protected String writeAttachment(Attachment att) {
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.redv.blogmover.impl.AbstractBlogWriter#writeBlog(com.redv.blogmover.WebLog,
     *      java.util.Map)
     */
    @Override
    protected void writeBlog(WebLog webLog, Map<Attachment, String> attachments)
            throws BlogMoverException {
        // 注意:格式 RSS 0.90, RSS 0.91 Netscape, RSS 0.91 Userland 的日志数量只能在1~15之间。
        if ((this.feedType.equals("rss_0.9")
                || this.feedType.equals("rss_0.91N") || this.feedType
                .equals("rss_0.91U"))
                && this.entries.size() >= 15) {
            return;
        }
        SyndEntry entry = new SyndEntryImpl();
        entry.setAuthor(this.author);
        entry.setTitle(webLog.getTitle());
        entry.setLink(webLog.getUrl());
        entry.setPublishedDate(webLog.getPublishedDate());
        entry.setUri(webLog.getUrl());

        if (webLog.getExcerpt() != null) {
            SyndContent description = new SyndContentImpl();
            description.setType("text/html");
            description.setValue(webLog.getExcerpt());
            entry.setDescription(description);
        } else if (this.feedType.equals("rss_2.0")) {
            SyndContent description = new SyndContentImpl();
            description.setType("text/html");
            description.setValue("");
            entry.setDescription(description);
        } else {
            // Do nothing.
        }

        List<SyndContent> contents = new ArrayList<SyndContent>();
        SyndContentImpl sc = new SyndContentImpl();
        sc.setType("text/html");
        sc.setValue(webLog.getBody());
        contents.add(sc);
        entry.setContents(contents);

        this.entries.add(entry);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.redv.blogmover.impl.AbstractBlogWriter#writeComment(com.redv.blogmover.Comment)
     */
    @Override
    protected void writeComment(Comment comment) throws BlogMoverException {

    }

    public static void main(String[] args) throws IOException, FeedException {
        SyndFeedImpl feed = new SyndFeedImpl();
        feed.setFeedType("rss_0.90");
        feed.setTitle("site title");
        feed.setLink("http://shutra.xpert.cn");
        feed.setDescription("site description");
        feed.setLanguage("zh-CN");
        feed.setCopyright("copyright");
        feed.setAuthor("author");

        List<SyndEntry> entries = new ArrayList<SyndEntry>();
        feed.setEntries(entries);
        for (int i = 0; i < 2; i++) {
            SyndEntry entry = new SyndEntryImpl();
            entry.setAuthor("author");
            entry.setTitle("title");
            entry.setLink("http://xpert.cn/" + i);

            List contents = new ArrayList();
            entry.setContents(contents);
            entries.add(entry);
        }

        SyndFeedOutput output = new SyndFeedOutput();
        List l = feed.getSupportedFeedTypes();
        for (Object s : l) {
            feed.setFeedType(s.toString());
            try {
                output.output(feed, new File("C:\\tmp\\t_" + s + ".xml"));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

by Shutra

Posted on November 29, 2006 12:05 PM | | Comments (0) | TrackBacks (0)
上一页 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 下一页
相关内容
广告计划
最新评论
[评论] 鸿雁 : 默默地为他们祈祷吧
[评论] lym328 : 客源CRM非常不错-----如有需要可以了解
[评论] kevinwu : 作用肯定是有的,Google会首先搜索站
[评论] ss : 其实还真的感觉不到sitemap的作用~
[评论] kevinwu : 谢谢你的关注 :-)
[评论] h51h : 贵博客写得非常的好,界面简洁但内
[评论] snguo : 这里很好 来这里支持下呢?
[评论] redondo : 感谢你分享知识! 这篇文章我转载到
[评论] kevinwu : 就是这本;看来我买的贵了点 - 8折;我
[评论] 安妮 : 《Flex3.0 RIA开发详解:基于ActionScript3.0