﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-永远的船长-随笔分类-J2EE</title><link>http://www.blogjava.net/buaacaptain/category/11576.html</link><description>只有偏执狂才能生存</description><language>zh-cn</language><lastBuildDate>Wed, 28 Feb 2007 11:12:27 GMT</lastBuildDate><pubDate>Wed, 28 Feb 2007 11:12:27 GMT</pubDate><ttl>60</ttl><item><title>一步一步教你远程调用EJB</title><link>http://www.blogjava.net/buaacaptain/archive/2006/09/09/68706.html</link><dc:creator>船长</dc:creator><author>船长</author><pubDate>Sat, 09 Sep 2006 05:48:00 GMT</pubDate><guid>http://www.blogjava.net/buaacaptain/archive/2006/09/09/68706.html</guid><wfw:comment>http://www.blogjava.net/buaacaptain/comments/68706.html</wfw:comment><comments>http://www.blogjava.net/buaacaptain/archive/2006/09/09/68706.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/buaacaptain/comments/commentRss/68706.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/buaacaptain/services/trackbacks/68706.html</trackback:ping><description><![CDATA[
		<span id="ArticleContent1_ArticleContent1_lblContent"> 
<p>前期准备：弄清楚weblogic（或jboss）、tomcat、JBluder（或eclipse＋MyEclipse）的使用方法，能写一个简单的基于struts框架的web工程，然后准备两台联网的电脑（局域网也可以），如果没有条件，也可以在同一台电脑上分别安装两个web服务器（例如：weblogic和tomcat）来代替，本文将采用后一种方法，采用weblogic作EJB容器，tomcat作web容器，用struts工程来调用EJB</p><p>准备好了吗？让我们开始下一步</p><p>第一步：写一个简单的EJB。写EJB最好用的还是JBuilder，毕竟够傻瓜化。当然作为专业人士，eclipse搭配MyEclipse是最佳选择，不过作为初学者，建议采用JBuilder。以下是本文测试所用到的EJB。</p><p>remote接口：</p><p>package testhello;</p><p>import javax.ejb.EJBObject;</p><p>public interface SayHello extends EJBObject {<br />    public String sayHello(String name) throws java.rmi.RemoteException;<br />}<br /></p><p>home接口：</p><p>package testhello;</p><p>import javax.ejb.EJBHome;<br />import javax.ejb.CreateException;<br />import java.rmi.RemoteException;</p><p>public interface SayHelloHome extends EJBHome {<br />    public SayHello create() throws CreateException, RemoteException;<br />}<br /></p><p>bean类：</p><p>package testhello;</p><p>import javax.ejb.SessionBean;<br />import javax.ejb.SessionContext;<br />import javax.ejb.CreateException;</p><p>public class SayHelloBean implements SessionBean {<br />    SessionContext sessionContext;<br />    public void ejbCreate() throws CreateException {<br />    }</p><p>    public void ejbRemove() {<br />    }</p><p>    public void ejbActivate() {<br />    }</p><p>    public void ejbPassivate() {<br />    }</p><p><br />    public void setSessionContext(SessionContext sessionContext) {<br />        this.sessionContext = sessionContext;<br />    }</p><p>    public String  sayHello(String name) {<br />        return "Hello "+name;<br />    }<br />}<br /></p><p>如果你是采用上面两种工具来写的话，配置文件就不必考虑了</p><p>第二步：利用JBuilder或eclipse将这个EJB工程编译并打包，会得到一个jar(如果你的工程名叫testhello，那么这个jar文件就是testhello.jar)文件。如果你的EJB容器（weblogic或JBoss）是在本机上，那么在JBuilder或eclipse中就可以直接鼠标右击EJB工程，来部署EJB。如果需要部署到远程服务器上，只需要通过EJB容器的控制台将testhello.jar上传到远程端，然后在EJB Modler里面按提示部署好EJB。最后，别忘了在JNDI Tree里面察看你的EJB工程的JNDI名，本例的JNDI名叫SayHello</p><p>第三步：将remote接口和home接口打包成jar文件，copy到你要远程调用EJB的struts工程下的lib目录（例如：helloapp -&gt;WEB-INF -&gt;lib）</p><p>第四步：将weblogic的weblogic.jar（在weblogic的安装目录－&gt;weblogic81－&gt;server－&gt;lib文件夹中）copy到tomcat安装目录下的－&gt;shared－&gt;lib文件夹中，其实这里我们需要用到的只是weblogic.jar里的几个class文件而已，不过对于初学者而言，先不必去深究到底只需要那几个class。</p><p>第五步：编写一个简单的struts工程（其实这些都可以用工具生成），一下是调用EJB的HelloAction的源代码(特别要注意的是，记得要将之前第三步生成的jar包导入编辑器中，否则下面的代码编译通不过。如果你不知道导入jar包，就把那个jar包多copy一份到你的jdk安装目录 -&gt; jre-&gt; lib-&gt; ext文件夹下)</p><p>package logging.actions;<br />import logging.Constants;</p><p>import java.util.*;<br />import javax.servlet.ServletException;<br />import javax.servlet.RequestDispatcher;<br />import javax.servlet.http.HttpSession;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;<br />import javax.naming.Context;<br />import javax.naming.InitialContext;<br />import javax.naming.NamingException;<br />import javax.rmi.PortableRemoteObject;</p><p>import org.apache.struts.action.Action;<br />import org.apache.struts.action.ActionForm;<br />import org.apache.struts.action.ActionForward;<br />import org.apache.struts.action.ActionMapping;<br />import org.apache.struts.action.ActionMessage;<br />import org.apache.struts.action.ActionMessages;<br />import org.apache.struts.util.MessageResources;<br />import org.apache.struts.validator.DynaValidatorForm;</p><p>public final class HelloAction extends Action{<br /> <br /> public ActionForward execute(ActionMapping mapping,<br />         ActionForm form,<br />         HttpServletRequest request,<br />         HttpServletResponse response)<br /> throws Exception{</p><p>        InitialContext ctx=this.getInitialContext();</p><p>  //查找JNDI名为SayHello的EJB组件<br />        Object obj=ctx.lookup("SayHello");</p><p><br />  //获得远程EJB组件的home接口的引用<br />        testhello.SayHelloHome home=(testhello.SayHelloHome)PortableRemoteObject.narrow(obj,testhello.SayHelloHome.class);</p><p><br />  //获得远程EJB组件的remote接口的引用<br />        testhello.SayHello hello=home.create();<br />        <br />        String name="飘然随风";<br />        String sayString=hello.sayHello(name);<br />        <br />        request.setAttribute("userName",name);<br />        request.setAttribute("passWord",sayString);<br />        request.removeAttribute(mapping.getAttribute());<br />       <br />  return mapping.findForward("loginSuccess");<br /> }<br /> </p><p>/*以下方法是作用是：通过传递环境属性选择JNDI驱动和服务器的网络位置，<br />  并连接到连接到JNDI树。<br />  这是采用weblogic做EJB容器时，远程调用EJB的固定初始化模式，初学者可以死记下来<br />*/<br /> private  InitialContext getInitialContext() throws Exception {<br />  //EJB容器的地址<br />     String url = "t3://image:7001";<br />     String user = null;<br />     String password = null;<br />     Properties properties;<br />  <br />        properties = new Properties();<br />        properties.put(Context.INITIAL_CONTEXT_FACTORY,<br />                       "weblogic.jndi.WLInitialContextFactory");<br />        properties.put(Context.PROVIDER_URL, url);<br />        if (user != null) {<br />            properties.put(Context.SECURITY_PRINCIPAL, user);<br />            properties.put(Context.SECURITY_CREDENTIALS,<br />                           password == null ? "" : password);<br />        }<br />        return new javax.naming.InitialContext(properties);<br /> }<br />}</p><p>第六步：如果你严格按照上面的步骤做了，那么剩下的就是同时启动weblogic和tomcat来测试了。</p></span>
<img src ="http://www.blogjava.net/buaacaptain/aggbug/68706.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/buaacaptain/" target="_blank">船长</a> 2006-09-09 13:48 <a href="http://www.blogjava.net/buaacaptain/archive/2006/09/09/68706.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>深入 Lucene 索引机制</title><link>http://www.blogjava.net/buaacaptain/archive/2006/08/01/61256.html</link><dc:creator>船长</dc:creator><author>船长</author><pubDate>Tue, 01 Aug 2006 15:12:00 GMT</pubDate><guid>http://www.blogjava.net/buaacaptain/archive/2006/08/01/61256.html</guid><wfw:comment>http://www.blogjava.net/buaacaptain/comments/61256.html</wfw:comment><comments>http://www.blogjava.net/buaacaptain/archive/2006/08/01/61256.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/buaacaptain/comments/commentRss/61256.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/buaacaptain/services/trackbacks/61256.html</trackback:ping><description><![CDATA[
		<blockquote>
				<p>Lucene 是一个基于 Java 的全文检索工具包，你可以利用它来为你的应用程序加入索引和检索功能。Lucene 目前是著名的 Apache Jakarta 家族中的一个开源项目，下面我们即将学习 Lucene 的索引机制以及它的索引文件的结构。</p>
				<p>在这篇文章中，我们首先演示如何使用 Lucene 来索引文档，接着讨论如何提高索引的性能。最后我们来分析 Lucene 的索引文件结构。需要记住的是，Lucene 不是一个完整的应用程序，而是一个信息检索包，它方便你为你的应用程序添加索引和搜索功能。</p>
		</blockquote>
		<!--START RESERVED FOR FUTURE USE INCLUDE FILES-->
		<!-- include java script once we verify teams wants to use this and it will work on dbcs and cyrillic characters -->
		<!--END RESERVED FOR FUTURE USE INCLUDE FILES-->
		<p>
				<a name="N10047">
						<span class="atitle">
								<font face="Arial" size="4">架构概览</font>
						</span>
				</a>
		</p>
		<p>图一显示了 Lucene 的索引机制的架构。Lucene 使用各种解析器对各种不同类型的文档进行解析。比如对于 HTML 文档，HTML 解析器会做一些预处理的工作，比如过滤文档中的 HTML 标签等等。HTML 解析器的输出的是文本内容，接着 Lucene 的分词器(Analyzer)从文本内容中提取出索引项以及相关信息，比如索引项的出现频率。接着 Lucene 的分词器把这些信息写到索引文件中。</p>
		<br />
		<a name="N10052">
				<b>图一：Lucene 索引机制架构</b>
		</a>
		<br />
		<img height="345" alt="图一：Lucene 索引机制架构" src="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/images/image002.jpg" width="438" border="0" />
		<br />
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N10062">
						<span class="atitle">
								<font face="Arial" size="4">用Lucene索引文档</font>
						</span>
				</a>
		</p>
		<p>接下来我将一步一步的来演示如何利用 Lucene 为你的文档创建索引。只要你能将要索引的文件转化成文本格式，Lucene 就能为你的文档建立索引。比如，如果你想为 HTML 文档或者 PDF 文档建立索引，那么首先你就需要从这些文档中提取出文本信息，然后把文本信息交给 Lucene 建立索引。我们接下来的例子用来演示如何利用 Lucene 为后缀名为 txt 的文件建立索引。</p>
		<p>1． 准备文本文件</p>
		<p>首先把一些以 txt 为后缀名的文本文件放到一个目录中，比如在 Windows 平台上，你可以放到 C:\\files_to_index 下面。</p>
		<p>2． 创建索引</p>
		<p>清单1是为我们所准备的文档创建索引的代码。</p>
		<br />
		<a name="N10077">
				<b>清单1：用 Lucene 索引你的文档</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">package lucene.index;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;

/**
 * This class demonstrates the process of creating an index with Lucene 
 * for text files in a directory.
 */
public class TextFileIndexer {
 public static void main(String[] args) throws Exception{
   //fileDir is the directory that contains the text files to be indexed
   File   fileDir  = new File("C:\\files_to_index ");

   //indexDir is the directory that hosts Lucene's index files
   File   indexDir = new File("C:\\luceneIndex");
   Analyzer luceneAnalyzer = new StandardAnalyzer();
   IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,true);
   File[] textFiles  = fileDir.listFiles();
   long startTime = new Date().getTime();

   //Add documents to the index
   for(int i = 0; i &lt; textFiles.length; i++){
     if(textFiles[i].isFile() &gt;&gt; textFiles[i].getName().endsWith(".txt")){
       System.out.println("File " + textFiles[i].getCanonicalPath() 
              + " is being indexed");
       Reader textReader = new FileReader(textFiles[i]);
       Document document = new Document();
       document.add(Field.Text("content",textReader));
       document.add(Field.Text("path",textFiles[i].getPath()));
       indexWriter.addDocument(document);
     }
   }

   indexWriter.optimize();
   indexWriter.close();
   long endTime = new Date().getTime();

   System.out.println("It took " + (endTime - startTime) 
              + " milliseconds to create an index for the files in the directory "
              + fileDir.getPath());
  }
}
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>正如清单1所示，你可以利用 Lucene 非常方便的为文档创建索引。接下来我们分析一下清单1中的比较关键的代码，我们先从下面的一条语句开始看起。</p>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">Analyzer luceneAnalyzer = new StandardAnalyzer();
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>这条语句创建了类 StandardAnalyzer 的一个实例，这个类是用来从文本中提取出索引项的。它只是抽象类 Analyzer 的其中一个实现。Analyzer 也有一些其它的子类，比如 SimpleAnalyzer 等。</p>
		<p>我们接着看另外一条语句：</p>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,true);
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>这条语句创建了类 IndexWriter 的一个实例，该类也是 Lucene 索引机制里面的一个关键类。这个类能创建一个新的索引或者打开一个已存在的索引并为该所引添加文档。我们注意到该类的构造函数接受三个参数，第一个参数指定了存储索引文件的路径。第二个参数指定了在索引过程中使用什么样的分词器。最后一个参数是个布尔变量，如果值为真，那么就表示要创建一个新的索引，如果值为假，就表示打开一个已经存在的索引。</p>
		<p>接下来的代码演示了如何添加一个文档到索引文件中。</p>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">Document document = new Document();
document.add(Field.Text("content",textReader));
document.add(Field.Text("path",textFiles[i].getPath()));
indexWriter.addDocument(document);
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>首先第一行创建了类 Document 的一个实例，它由一个或者多个的域(Field)组成。你可以把这个类想象成代表了一个实际的文档，比如一个 HTML 页面，一个 PDF 文档，或者一个文本文件。而类 Document 中的域一般就是实际文档的一些属性。比如对于一个 HTML 页面，它的域可能包括标题，内容，URL 等。我们可以用不同类型的 Field 来控制文档的哪些内容应该索引，哪些内容应该存储。如果想获取更多的关于 Lucene 的域的信息，可以参考 Lucene 的帮助文档。代码的第二行和第三行为文档添加了两个域，每个域包含两个属性，分别是域的名字和域的内容。在我们的例子中两个域的名字分别是"content"和"path"。分别存储了我们需要索引的文本文件的内容和路径。最后一行把准备好的文档添加到了索引当中。</p>
		<p>当我们把文档添加到索引中后，不要忘记关闭索引，这样才保证 Lucene 把添加的文档写回到硬盘上。下面的一句代码演示了如何关闭索引。</p>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">indexWriter.close();
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>利用清单1中的代码，你就可以成功的将文本文档添加到索引中去。接下来我们看看对索引进行的另外一种重要的操作，从索引中删除文档。</p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N100BD">
						<span class="atitle">
								<font face="Arial" size="4">从索引中删除文档</font>
						</span>
				</a>
		</p>
		<p>类IndexReader负责从一个已经存在的索引中删除文档，如清单2所示。</p>
		<br />
		<a name="N100C6">
				<b>清单2：从索引中删除文档</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">File   indexDir = new File("C:\\luceneIndex");
IndexReader ir = IndexReader.open(indexDir);
ir.delete(1);
ir.delete(new Term("path","C:\\file_to_index\lucene.txt"));
ir.close();
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>在清单2中，第二行用静态方法 IndexReader.open(indexDir) 初始化了类 IndexReader 的一个实例，这个方法的参数指定了索引的存储路径。类 IndexReader 提供了两种方法去删除一个文档，如程序中的第三行和第四行所示。第三行利用文档的编号来删除文档。每个文档都有一个系统自动生成的编号。第四行删除了路径为"C:\\file_to_index\lucene.txt"的文档。你可以通过指定文件路径来方便的删除一个文档。值得注意的是虽然利用上述代码删除文档使得该文档不能被检索到，但是并没有物理上删除该文档。Lucene 只是通过一个后缀名为 .delete 的文件来标记哪些文档已经被删除。既然没有物理上删除，我们可以方便的把这些标记为删除的文档恢复过来，如清单 3 所示，首先打开一个索引，然后调用方法 ir.undeleteAll() 来完成恢复工作。</p>
		<br />
		<a name="N100D3">
				<b>清单3：恢复已删除文档</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">File   indexDir = new File("C:\\luceneIndex");
IndexReader ir = IndexReader.open(indexDir);
ir.undeleteAll();
ir.close();
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>你现在也许想知道如何物理上删除索引中的文档，方法也非常简单。清单 4 演示了这个过程。</p>
		<br />
		<a name="N100E0">
				<b>清单4：如何物理上删除文档</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">File   indexDir = new File("C:\\luceneIndex");
Analyzer luceneAnalyzer = new StandardAnalyzer();
IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,false);
indexWriter.optimize();
indexWriter.close();
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>在清单 4 中，第三行创建了类 IndexWriter 的一个实例，并且打开了一个已经存在的索引。第 4 行对索引进行清理，清理过程中将把所有标记为删除的文档物理删除。</p>
		<p>Lucene 没有直接提供方法对文档进行更新，如果你需要更新一个文档，那么你首先需要把这个文档从索引中删除，然后把新版本的文档加入到索引中去。</p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N100F0">
						<span class="atitle">
								<font face="Arial" size="4">提高索引性能</font>
						</span>
				</a>
		</p>
		<p>利用 Lucene，在创建索引的工程中你可以充分利用机器的硬件资源来提高索引的效率。当你需要索引大量的文件时，你会注意到索引过程的瓶颈是在往磁盘上写索引文件的过程中。为了解决这个问题, Lucene 在内存中持有一块缓冲区。但我们如何控制 Lucene 的缓冲区呢？幸运的是，Lucene 的类 IndexWriter 提供了三个参数用来调整缓冲区的大小以及往磁盘上写索引文件的频率。</p>
		<p>1．合并因子（mergeFactor）</p>
		<p>这个参数决定了在 Lucene 的一个索引块中可以存放多少文档以及把磁盘上的索引块合并成一个大的索引块的频率。比如，如果合并因子的值是 10，那么当内存中的文档数达到 10 的时候所有的文档都必须写到磁盘上的一个新的索引块中。并且，如果磁盘上的索引块的隔数达到 10 的话，这 10 个索引块会被合并成一个新的索引块。这个参数的默认值是 10，如果需要索引的文档数非常多的话这个值将是非常不合适的。对批处理的索引来讲，为这个参数赋一个比较大的值会得到比较好的索引效果。</p>
		<p>2．最小合并文档数</p>
		<p>这个参数也会影响索引的性能。它决定了内存中的文档数至少达到多少才能将它们写回磁盘。这个参数的默认值是10，如果你有足够的内存，那么将这个值尽量设的比较大一些将会显著的提高索引性能。</p>
		<p>3．最大合并文档数</p>
		<p>这个参数决定了一个索引块中的最大的文档数。它的默认值是 Integer.MAX_VALUE，将这个参数设置为比较大的值可以提高索引效率和检索速度，由于该参数的默认值是整型的最大值，所以我们一般不需要改动这个参数。</p>
		<p>清单 5 列出了这个三个参数用法，清单 5 和清单 1 非常相似，除了清单 5 中会设置刚才提到的三个参数。</p>
		<br />
		<a name="N1010E">
				<b>清单5：提高索引性能</b>
		</a>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">/**
 * This class demonstrates how to improve the indexing performance 
 * by adjusting the parameters provided by IndexWriter.
 */
public class AdvancedTextFileIndexer  {
  public static void main(String[] args) throws Exception{
    //fileDir is the directory that contains the text files to be indexed
    File   fileDir  = new File("C:\\files_to_index");

    //indexDir is the directory that hosts Lucene's index files
    File   indexDir = new File("C:\\luceneIndex");
    Analyzer luceneAnalyzer = new StandardAnalyzer();
    File[] textFiles  = fileDir.listFiles();
    long startTime = new Date().getTime();

    int mergeFactor = 10;
    int minMergeDocs = 10;
    int maxMergeDocs = Integer.MAX_VALUE;
    IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,true);        
    indexWriter.mergeFactor = mergeFactor;
    indexWriter.minMergeDocs = minMergeDocs;
    indexWriter.maxMergeDocs = maxMergeDocs;

    //Add documents to the index
    for(int i = 0; i &lt; textFiles.length; i++){
      if(textFiles[i].isFile() &gt;&gt; textFiles[i].getName().endsWith(".txt")){
        Reader textReader = new FileReader(textFiles[i]);
        Document document = new Document();
        document.add(Field.Text("content",textReader));
        document.add(Field.Keyword("path",textFiles[i].getPath()));
        indexWriter.addDocument(document);
      }
    }

    indexWriter.optimize();
    indexWriter.close();
    long endTime = new Date().getTime();

    System.out.println("MergeFactor: " + indexWriter.mergeFactor);
    System.out.println("MinMergeDocs: " + indexWriter.minMergeDocs);
    System.out.println("MaxMergeDocs: " + indexWriter.maxMergeDocs);
    System.out.println("Document number: " + textFiles.length);
    System.out.println("Time consumed: " + (endTime - startTime) + " milliseconds");
  }
}
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>通过这个例子，我们注意到在调整缓冲区的大小以及写磁盘的频率上面 Lucene 给我们提供了非常大的灵活性。现在我们来看一下代码中的关键语句。如下的代码首先创建了类 IndexWriter 的一个实例，然后对它的三个参数进行赋值。</p>
		<br />
		<table cellspacing="0" cellpadding="5" width="100%" bgcolor="#eeeeee" border="1">
				<tbody>
						<tr>
								<td>
										<code>
												<pre class="section">int mergeFactor = 10;
int minMergeDocs = 10;
int maxMergeDocs = Integer.MAX_VALUE;
IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,true);        
indexWriter.mergeFactor = mergeFactor;
indexWriter.minMergeDocs = minMergeDocs;
indexWriter.maxMergeDocs = maxMergeDocs;
</pre>
										</code>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<p>下面我们来看一下这三个参数取不同的值对索引时间的影响，注意参数值的不同和索引之间的关系。我们为这个实验准备了 10000 个测试文档。表 1 显示了测试结果。</p>
		<br />
		<a name="N10129">
				<b>表1：测试结果</b>
		</a>
		<br />
		<img height="199" alt="表1：测试结果" src="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/images/table1.gif" width="502" border="0" />
		<br />
		<p>通过表 1，你可以清楚地看到三个参数对索引时间的影响。在实践中，你会经常的改变合并因子和最小合并文档数的值来提高索引性能。只要你有足够大的内存，你可以为合并因子和最小合并文档数这两个参数赋尽量大的值以提高索引效率，另外我们一般无需更改最大合并文档数这个参数的值，因为系统已经默认将它设置成了最大。</p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N1013C">
						<span class="atitle">
								<font face="Arial" size="4">Lucene 索引文件结构分析</font>
						</span>
				</a>
		</p>
		<p>在分析 Lucene 的索引文件结构之前，我们先要理解反向索引（Inverted index）这个概念，反向索引是一种以索引项为中心来组织文档的方式，每个索引项指向一个文档序列，这个序列中的文档都包含该索引项。相反，在正向索引中，文档占据了中心的位置，每个文档指向了一个它所包含的索引项的序列。你可以利用反向索引轻松的找到那些文档包含了特定的索引项。Lucene正是使用了反向索引作为其基本的索引结构。</p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N10145">
						<span class="atitle">
								<font face="Arial" size="4">索引文件的逻辑视图</font>
						</span>
				</a>
		</p>
		<p>在Lucene 中有索引块的概念，每个索引块包含了一定数目的文档。我们能够对单独的索引块进行检索。图 2 显示了 Lucene 索引结构的逻辑视图。索引块的个数由索引的文档的总数以及每个索引块所能包含的最大文档数来决定。</p>
		<br />
		<a name="N10150">
				<b>图2：索引文件的逻辑视图</b>
		</a>
		<br />
		<img height="415" alt="图2：索引文件的逻辑视图" src="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/images/image004.jpg" width="467" border="0" />
		<br />
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N10160">
						<span class="atitle">
								<font face="Arial" size="4">Lucene 中的关键索引文件</font>
						</span>
				</a>
		</p>
		<p>下面的部分将会分析Lucene中的主要的索引文件，可能分析有些索引文件的时候没有包含文件的所有的字段，但不会影响到对索引文件的理解。</p>
		<p>1．索引块文件</p>
		<p>这个文件包含了索引中的索引块信息，这个文件包含了每个索引块的名字以及大小等信息。表 2 显示了这个文件的结构信息。</p>
		<br />
		<a name="N10171">
				<b>表2：索引块文件结构</b>
		</a>
		<br />
		<img height="198" alt="表2：索引块文件结构" src="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/images/table2.gif" width="568" border="0" />
		<br />
		<p>2．域信息文件</p>
		<p>我们知道，索引中的文档由一个或者多个域组成，这个文件包含了每个索引块中的域的信息。表 3 显示了这个文件的结构。</p>
		<br />
		<a name="N10189">
				<b>表3：域信息文件结构</b>
		</a>
		<br />
		<img height="179" alt="表3：域信息文件结构" src="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/images/table3.gif" width="567" border="0" />
		<br />
		<p>3．索引项信息文件</p>
		<p>这是索引文件里面最核心的一个文件，它存储了所有的索引项的值以及相关信息，并且以索引项来排序。表 4 显示了这个文件的结构。</p>
		<br />
		<a name="N101A1">
				<b>表4：索引项信息文件结构</b>
		</a>
		<br />
		<img height="252" alt="表4：索引项信息文件结构" src="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/images/table4.gif" width="568" border="0" />
		<br />
		<p>4．频率文件</p>
		<p>这个文件包含了包含索引项的文档的列表，以及索引项在每个文档中出现的频率信息。如果Lucene在索引项信息文件中发现有索引项和搜索词相匹配。那么 Lucene 就会在频率文件中找有哪些文件包含了该索引项。表5显示了这个文件的一个大致的结构，并没有包含这个文件的所有字段。</p>
		<br />
		<a name="N101B9">
				<b>表5：频率文件的结构</b>
		</a>
		<br />
		<img height="124" alt="表5：频率文件的结构" src="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/images/table5.gif" width="567" border="0" />
		<br />
		<p>5．位置文件</p>
		<p>这个文件包含了索引项在每个文档中出现的位置信息，你可以利用这些信息来参与对索引结果的排序。表 6 显示了这个文件的结构</p>
		<br />
		<a name="N101D1">
				<b>表6：位置文件的结构</b>
		</a>
		<br />
		<img height="69" alt="表6：位置文件的结构" src="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/images/table6.gif" width="568" border="0" />
		<br />
		<p>到目前为止我们介绍了 Lucene 中的主要的索引文件结构，希望能对你理解 Lucene 的物理的存储结构有所帮助。</p>
		<br />
		<table cellspacing="0" cellpadding="0" width="100%" border="0">
				<tbody>
						<tr>
								<td>
										<img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" />
										<br />
										<img height="6" alt="" src="http://www.ibm.com/i/c.gif" width="8" border="0" />
								</td>
						</tr>
				</tbody>
		</table>
		<table class="no-print" cellspacing="0" cellpadding="0" align="right">
				<tbody>
						<tr align="right">
								<td>
										<img height="4" alt="" src="http://www.ibm.com/i/c.gif" width="100%" />
										<br />
										<table cellspacing="0" cellpadding="0" border="0">
												<tbody>
														<tr>
																<td valign="center">
																		<img height="16" alt="" src="http://www.ibm.com/i/v14/icons/u_bold.gif" width="16" border="0" />
																		<br />
																</td>
																<td valign="top" align="right">
																		<a class="fbox" href="http://www-128.ibm.com/developerworks/cn/java/wa-lucene/index.html#main">
																				<b>
																						<font color="#996699">回页首</font>
																				</b>
																		</a>
																</td>
														</tr>
												</tbody>
										</table>
								</td>
						</tr>
				</tbody>
		</table>
		<br />
		<br />
		<p>
				<a name="N101E4">
						<span class="atitle">
								<font face="Arial" size="4">总结</font>
						</span>
				</a>
		</p>
		<p>目前已经有非常多的知名的组织正在使用 Lucene，比如，Lucene 为 Eclipse 的帮助系统，麻省理工学院的 OpenCourseWare 提供了搜索功能。通过阅读这篇文章，希望你能对 Lucene 的索引机制有所了解，并且你会发现利用 Lucene 创建索引是非常简单的事情。</p>
<img src ="http://www.blogjava.net/buaacaptain/aggbug/61256.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/buaacaptain/" target="_blank">船长</a> 2006-08-01 23:12 <a href="http://www.blogjava.net/buaacaptain/archive/2006/08/01/61256.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>string和stringbuffer</title><link>http://www.blogjava.net/buaacaptain/archive/2006/07/13/58031.html</link><dc:creator>船长</dc:creator><author>船长</author><pubDate>Thu, 13 Jul 2006 09:47:00 GMT</pubDate><guid>http://www.blogjava.net/buaacaptain/archive/2006/07/13/58031.html</guid><wfw:comment>http://www.blogjava.net/buaacaptain/comments/58031.html</wfw:comment><comments>http://www.blogjava.net/buaacaptain/archive/2006/07/13/58031.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/buaacaptain/comments/commentRss/58031.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/buaacaptain/services/trackbacks/58031.html</trackback:ping><description><![CDATA[String和StringBuffer之概览<br />　　非可变对象一旦创建之后就不能再被改变，可变对象则可以在创建之后被改变。String对象是非可变对象，StringBuffer对象则是可变对象。为获得更佳的性能你需要根据实际情况小心谨慎地选择到底使用这两者中的某一个。下面的话题会作详细的阐述。（注意：这个章节假设读者已经具备Java的String和StringBuffer的相关基础知识。）<br /> <br />创建字符串的较佳途径<br />你可以按照以下方式创建字符串对象：<br />1. String s1 = "hello"; <br />    String s2 = "hello"; <br />2. String s3 = new String("hello");<br />    String s4 = new String("hello");<br /> <br />上面哪种方式会带来更好的性能呢？下面的代码片断用来测量二者之间的区别。<br /><br />StringTest1.java<br />package com.performance.string;<br />/** This class shows the time taken for creation of<br /> *  String literals and String objects.<br /> */<br />public class StringTest1 {<br />public static void main(String[] args){<br />    // create String literals<br />    long startTime = System.currentTimeMillis();<br />    for(int i=0;i&lt;50000;i++){<br />    String s1 = "hello";<br />    String s2 = "hello";<br />    }<br />    long endTime = System.currentTimeMillis();<br />    System.out.println("Time taken for creation of String literals : "<br />                  + (endTime - startTime) + " milli seconds" );<br />    // create String objects using 'new' keyword       <br />    long startTime1 = System.currentTimeMillis();<br />    for(int i=0;i&lt;50000;i++){<br />    String s3 = new String("hello");<br />    String s4 = new String("hello");<br />    }<br />    long endTime1 = System.currentTimeMillis();<br />    System.out.println("Time taken for creation of String objects : "<br />                  + (endTime1 - startTime1)+" milli seconds");<br />    }<br />}<br />这段代码的输出：<br />Time taken for creation of String literals : 0 milli seconds<br />Time taken for creation of String objects : 170 milli seconds<br /> <br />JVM是怎样处理字符串的呢？<br />　　Java虚拟机会维护一个内部的滞留字符串对象的列表（唯一字符串的池）来避免在堆内存中产生重复的String对象。当JVM从class文件里加载字符串字面量并执行的时候，它会先检查一下当前的字符串是否已经存在于滞留字符串列表，如果已经存在，那就不会再创建一个新的String对象而是将引用指向已经存在的String对象，JVM会在内部为字符串字面量作这种检查，但并不会为通过new关键字创建的String对象作这种检查。当然你可以明确地使用String.intern()方法强制JVM为通过 new关键字创建的String对象作这样的检查。这样可以强制JVM检查内部列表而使用已有的String对象。<br />　　所以结论是，JVM会内在地为字符串字面量维护一些唯一的String对象，程序员不需要为字符串字面量而发愁，但是可能会被一些通过 new关键字创建的String对象而困扰，不过他们可以使用intern()方法来避免在堆内存上创建重复的String对象来改善Java的运行性能。下一小节会向大家展示更多的信息。<br /> <br />下图展示了未使用intern()方法来创建字符串的情况。<br /> <br />string_creating_without_intern() method<br />　　你可以自己使用==操作符和String.equals()方法来编码测试上面提到的区别。==操作符会返回true如果一些引用指向一个相同的对象但不会判断String对象的内容是否相同；String.equals()方法会返回true如果被操作的String对象的内容相同。对于上面的代码会有s1==s2，因为s1和s2两个引用指向同一个对象，对于上面的代码，s3.equals(s4)会返回true因为两个对象的内容都一样为”hello”。你可以从上图看出这种机制。在这里有三个独立的包含了相同的内容（”hello”）的对象，实际上我们不需要这么三个独立的对象—— 因为要运行它们的话既浪费时间又浪费内存。<br /> <br />　　那么怎样才能确保String对象不会重复呢？下一个话题会涵盖对于内建String机制的兴趣。<br /> <br />滞留字符串的优化作用<br />　　同一个字符串对象被重复地创建是不必要的，String.intern ()方法可以避免这种情况。下图说明了String.intern()方法是如何工作的，String.intern()方法检查字符串对象的存在性，如果需要的字符串对象已经存在，那么它会将引用指向已经存在的字符串对象而不是重新创建一个。下图描绘了使用了intern()方法的字符串字面量和字符串对象的创建情况。<br /> <br />string_creating_with_intern() method<br />下面的例程帮助大家了解String.intern()方法的重要性。<br />StringTest2.java<br /> <br />package com.performance.string;<br />// This class shows the use of intern() method to improve performance<br />public class StringTest2 {<br />public static void main(String[] args){<br />    // create String references like s1,s2,s3...so on..<br />    String variables[] = new String[50000];<br />    for( int i=0;i&lt;variables.length;i++){<br />        variables[i] = "s"+i;<br />    }<br />    // create String literals<br />    long startTime0 = System.currentTimeMillis();<br />    for(int i=0;i&lt;variables.length;i++){<br />        variables[i] = "hello";<br />    }<br />    long endTime0 = System.currentTimeMillis();<br />    System.out.println("Time taken for creation of String literals : "<br />                         + (endTime0 - startTime0) + " milli seconds" );<br />    // create String objects using 'new' keyword       <br />    long startTime1 = System.currentTimeMillis();<br />    for(int i=0;i&lt;variables.length;i++){<br />        variables[i] = new String("hello");<br />    }<br />    long endTime1 = System.currentTimeMillis();<br />    System.out.println("Time taken for creation of String objects with 'new' key word : "<br />                        + (endTime1 - startTime1)+" milli seconds");<br />    // intern String objects with intern() method   <br />    long startTime2 = System.currentTimeMillis();<br />    for(int i=0;i&lt;variables.length;i++){<br />        variables[i] = new String("hello");<br />        variables[i] = variables[i].intern();<br />    }<br />    long endTime2 = System.currentTimeMillis();<br />    System.out.println("Time taken for creation of String objects with intern(): "<br />                        + (endTime2 - startTime2)+" milli seconds");<br />    }<br />}<br />这是上面那段代码的输出结果：<br />Time taken for creation of String literals : 0 milli seconds<br />Time taken for creation of String objects with 'new' key word : 160 milli seconds<br />Time taken for creation of String objects with intern(): 60 milli seconds<br /> <br />连接字符串时候的优化技巧<br />　　你可以使用+操作符或者String.concat()或者StringBuffer.append()等办法来连接多个字符串，那一种办法具有最佳的性能呢？<br />　　如何作出选择取决于两种情景，第一种情景是需要连接的字符串是在编译期决定的还是在运行期决定的，第二种情景是你使用的是 StringBuffer还是String。通常程序员会认为StringBuffer.append()方法会优于+操作符或 String.concat()方法，但是在一些特定的情况下这个假想是不成立的。<br /> <br />1) 第一种情景：编译期决定相对于运行期决定<br />请看下面的StringTest3.java代码和输出结果。<br /><br />package com.performance.string;<br />/** This class shows the time taken by string concatenation at compile time and run time.*/<br />public class StringTest3 {<br />  public static void main(String[] args){<br />    //Test the String Concatination<br />    long startTime = System.currentTimeMillis();<br />    for(int i=0;i&lt;5000;i++){<br />    String result = "This is"+ "testing the"+ "difference"+ "between"+<br />            "String"+ "and"+ "StringBuffer";<br />    }<br />    long endTime = System.currentTimeMillis();<br />    System.out.println("Time taken for string concatenation using + operator : "<br />         + (endTime - startTime)+ " milli seconds");<br />    //Test the StringBuffer Concatination<br />    long startTime1 = System.currentTimeMillis();<br />    for(int i=0;i&lt;5000;i++){<br />    StringBuffer result = new StringBuffer();<br />         result.append("This is");<br />        result.append("testing the");<br />        result.append("difference");<br />        result.append("between");<br />       result.append("String");<br />       result.append("and");<br />       result.append("StringBuffer");<br />     }<br />    long endTime1 = System.currentTimeMillis();<br />    System.out.println("Time taken for String concatenation using StringBuffer : "<br />           + (endTime1 - startTime1)+ " milli seconds");<br />  }<br />}<br />这是上面的代码的输出结果：<br />Time taken for String concatenation using + operator : 0 milli seconds<br />Time taken for String concatenation using StringBuffer : 50 milli seconds<br />很有趣地，+操作符居然比StringBuffer.append()方法要快，为什么呢？<br /> <br />　　这里编译器的优化起了关键作用，编译器像下面举例的那样简单地在编译期连接多个字符串。它使用编译期决定取代运行期决定，在你使用new关键字来创建String对象的时候也是如此。<br /> <br />编译前：<br />String result = "This is"+"testing the"+"difference"+"between"+"String"+"and"+"StringBuffer";<br />编译后：<br />String result = "This is testing the difference between String and StringBuffer";<br /><br />这里String对象在编译期就决定了而StringBuffer对象是在运行期决定的。运行期决定需要额外的开销当字符串的值无法预先知道的时候，编译期决定作用于字符串的值可以预先知道的时候，下面是一个例子。<br /> <br />编译前：<br />public String getString(String str1,String str2) {<br />    return str1+str2;<br />}<br />编译后：<br />return new StringBuffer().append(str1).append(str2).toString();<br />运行期决定需要更多的时间来运行。<br /> <br />2) 第二种情景：使用StringBuffer取代String<br />看看下面的代码你会发现与情景一相反的结果——连接多个字符串的时候StringBuffer要比String快。<br />StringTest4.java<br /> <br />package com.performance.string;<br />/** This class shows the time taken by string concatenation<br />using + operator and StringBuffer  */<br />public class StringTest4 {<br /> public static void main(String[] args){<br />    //Test the String Concatenation using + operator<br />    long startTime = System.currentTimeMillis();<br />    String result = "hello";<br />    for(int i=0;i&lt;1500;i++){<br />        result += "hello";<br />    }<br />    long endTime = System.currentTimeMillis();<br />    System.out.println("Time taken for string concatenation using + operator : "<br />                  + (endTime - startTime)+ " milli seconds");<br />    //Test the String Concatenation using StringBuffer<br />    long startTime1 = System.currentTimeMillis();<br />    StringBuffer result1 = new StringBuffer("hello");<br />    for(int i=0;i&lt;1500;i++){<br />        result1.append("hello");<br />    }<br />    long endTime1 = System.currentTimeMillis();<br />    System.out.println("Time taken for string concatenation using StringBuffer :  "<br />                  + (endTime1 - startTime1)+ " milli seconds");<br />    }<br />}<br />这是上面的代码的输出结果：<br />Time taken for string concatenation using + operator : 280 milli seconds<br />Time taken for String concatenation using StringBuffer : 0 milli seconds<br />看得出StringBuffer.append()方法要比+操作符要快得多，为什么呢？<br /><br />　　原因是两者都是在运行期决定字符串对象，但是+操作符使用不同于StringBuffer.append()的规则通过String和StringBuffer来完成字符串连接操作。（译注：什么样的规则呢？）<br /> <br />借助StringBuffer的初始化过程的优化技巧<br />　　你可以通过StringBuffer的构造函数来设定它的初始化容量，这样可以明显地提升性能。这里提到的构造函数是StringBuffer(int length)，length参数表示当前的StringBuffer能保持的字符数量。你也可以使用ensureCapacity(int minimumcapacity)方法在StringBuffer对象创建之后设置它的容量。首先我们看看StringBuffer的缺省行为，然后再找出一条更好的提升性能的途径。<br /> <br />StringBuffer的缺省行为：<br />　　StringBuffer在内部维护一个字符数组，当你使用缺省的构造函数来创建StringBuffer对象的时候，因为没有设置初始化字符长度，StringBuffer的容量被初始化为16个字符，也就是说缺省容量就是16个字符。当StringBuffer达到最大容量的时候，它会将自身容量增加到当前的2倍再加2，也就是（2*旧值+2）。<br />　　如果你使用缺省值，初始化之后接着往里面追加字符，在你追加到第16个字符的时候它会将容量增加到34（2*16+2），当追加到34个字符的时候就会将容量增加到70（2*34+2）。无论何事只要StringBuffer到达它的最大容量它就不得不创建一个新的字符数组然后重新将旧字符和新字符都拷贝一遍——这也太昂贵了点。所以总是给StringBuffer设置一个合理的初始化容量值是错不了的，这样会带来立竿见影的性能增益。<br />　　我利用两个StringBuffer重新测试了上面的StringTest4.java代码，一个未使用初始化容量值而另一个使用了。这次我追加了50000个’hello’对象没有使用+操作符。区别是我使用StringBuffer(250000)的构造函数来初始化第二个 StringBuffer了。<br /> <br />输出结果如下：<br />Time taken for String concatenation using StringBuffer with out setting size: 280 milli seconds<br />Time taken for String concatenation using StringBuffer with setting size: 0 milli seconds<br />StringBuffer初始化过程的调整的作用由此可见一斑。所以，使用一个合适的容量值来初始化StringBuffer永远都是一个最佳的建议。<br /> <br />关键点<br />1. 无论何时只要可能的话使用字符串字面量来常见字符串而不是使用new关键字来创建字符串。<br />2. 无论何时当你要使用new关键字来创建很多内容重复的字符串的话，请使用String.intern()方法。<br />3. +操作符会为字符串连接提供最佳的性能——当字符串是在编译期决定的时候。<br />4. 如果字符串在运行期决定，使用一个合适的初期容量值初始化的StringBuffer会为字符串连接提供最佳的性能<br /><br /><a href="http://java.chinaitlab.com/JDK/364481.html">http://java.chinaitlab.com/JDK/364481.html</a><img src ="http://www.blogjava.net/buaacaptain/aggbug/58031.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/buaacaptain/" target="_blank">船长</a> 2006-07-13 17:47 <a href="http://www.blogjava.net/buaacaptain/archive/2006/07/13/58031.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>xml的document和xml字符串间的转换</title><link>http://www.blogjava.net/buaacaptain/archive/2006/07/13/57953.html</link><dc:creator>船长</dc:creator><author>船长</author><pubDate>Thu, 13 Jul 2006 04:52:00 GMT</pubDate><guid>http://www.blogjava.net/buaacaptain/archive/2006/07/13/57953.html</guid><wfw:comment>http://www.blogjava.net/buaacaptain/comments/57953.html</wfw:comment><comments>http://www.blogjava.net/buaacaptain/archive/2006/07/13/57953.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/buaacaptain/comments/commentRss/57953.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/buaacaptain/services/trackbacks/57953.html</trackback:ping><description><![CDATA[
		<table cellspacing="1" cellpadding="4" width="100%" border="0">
				<tbody>
						<tr>
								<td valign="top">
										<div class="subhead">
												<b>XML字符串和XML DOCUMENT的相互转换</b>
										</div>
								</td>
						</tr>
						<tr>
								<td class="content" valign="top">
										<table width="200" align="right" border="0">
												<tbody>
														<tr>
																<td>
																</td>
														</tr>
												</tbody>
										</table>
										<p>
												<font size="2">在做一般的XML数据交换过程中，我更乐意传递XML字符串，而不是格式化的XML Document。这就涉及到XML字符串和Xml Document的转换问题，说白了这是个很简单的问题，本文就各种XML解析器分别列举如下，以方便自己今后查阅。</font>
										</p>
										<p>
												<br />
												<strong>
														<font size="2">一、使用最原始的javax.xml.parsers，标准的jdk api</font>
												</strong>
										</p>
										<p>
												<font size="2">// 字符串转XML<br />String xmlStr = \"......\";<br />StringReader sr = new StringReader(xmlStr); <br />InputSource is = new InputSource(sr); <br />DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); <br />DocumentBuilder builder=factory.newDocumentBuilder(); <br />Document doc = builder.parse(is); </font>
										</p>
										<p>
												<font size="2">//XML转字符串<br />TransformerFactory  tf  =  TransformerFactory.newInstance();<br />Transformer t = tf.newTransformer();<br />t.setOutputProperty(\"encoding\",\"GB23121\");//解决中文问题，试过用GBK不行<br />ByteArrayOutputStream  bos  =  new  ByteArrayOutputStream();<br />t.transform(new DOMSource(doc), new StreamResult(bos));<br />String xmlStr = bos.toString();</font>
										</p>
										<p>
												<font size="2">这里的XML DOCUMENT为org.w3c.dom.Document</font>
										</p>
										<p>
												<strong>
														<font size="2">二、使用dom4j后程序变得更简单</font>
												</strong>
										</p>
										<p>
												<font size="2">// 字符串转XML<br />String xmlStr = \"......\";<br />Document document = DocumentHelper.parseText(xmlStr);</font>
										</p>
										<p>
												<font size="2">// XML转字符串 <br />Document document = ...;<br />String text = document.asXML();</font>
										</p>
										<p>
												<font size="2">这里的XML DOCUMENT为org.dom4j.Document</font>
										</p>
										<p>
												<strong>
														<font size="2">三、使用JDOM</font>
												</strong>
										</p>
										<p>
												<font size="2">JDOM的处理方式和第一种方法处理非常类似</font>
										</p>
										<p>
												<font size="2">//字符串转XML<br />String xmlStr = \".....\";<br />StringReader sr = new StringReader(xmlStr);<br />InputSource is = new InputSource(sr);<br />Document doc = (new SAXBuilder()).build(is);</font>
										</p>
										<p>
												<font size="2">//XML转字符串<br />Format format = Format.getPrettyFormat();<br />format.setEncoding(\"gb2312\");//设置xml文件的字符为gb2312，解决中文问题<br />XMLOutputter xmlout = new XMLOutputter(format);<br />ByteArrayOutputStream bo = new ByteArrayOutputStream();<br />xmlout.output(doc,bo);<br />String xmlStr = bo.toString();</font>
										</p>
										<p>
												<font size="2">这里的XML DOCUMENT为org.jdom.Document</font>
										</p>
										<p>
												<strong>
														<font size="2">四、JAVASCRIPT中的处理</font>
												</strong>
										</p>
										<p>
												<br />
												<font size="2">//字符串转XML<br />var xmlStr = \".....\";<br />var xmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");<br />xmlDoc.async=false;<br />xmlDoc.loadXML(xmlStr);<br />//可以处理这个xmlDoc了<br />var name = xmlDoc.selectSingleNode(\"/person/name\");<br />alert(name.text);</font>
										</p>
										<p>
												<font size="2">//XML转字符串<br />var xmlDoc = ......;<br />var xmlStr = xmlDoc.xml</font>
										</p>
										<p>
												<font size="2">这里的XML DOCUMENT为javascript版的XMLDOM</font>
										</p>
								</td>
						</tr>
				</tbody>
		</table>
<img src ="http://www.blogjava.net/buaacaptain/aggbug/57953.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/buaacaptain/" target="_blank">船长</a> 2006-07-13 12:52 <a href="http://www.blogjava.net/buaacaptain/archive/2006/07/13/57953.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>关于clob字段的一些讨论</title><link>http://www.blogjava.net/buaacaptain/archive/2006/07/11/57616.html</link><dc:creator>船长</dc:creator><author>船长</author><pubDate>Tue, 11 Jul 2006 03:07:00 GMT</pubDate><guid>http://www.blogjava.net/buaacaptain/archive/2006/07/11/57616.html</guid><wfw:comment>http://www.blogjava.net/buaacaptain/comments/57616.html</wfw:comment><comments>http://www.blogjava.net/buaacaptain/archive/2006/07/11/57616.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/buaacaptain/comments/commentRss/57616.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/buaacaptain/services/trackbacks/57616.html</trackback:ping><description><![CDATA[在网上闲逛找到了解决方案：<br />     现在3.x中对blob和clob增加了org.hibernate.lob.SerializableBlob和org.hibernate.lob.SerializableClob类的封装。<br /><br />其次如果你将前面的测试程序放到weblogic的容器中通过weblogic的数据源得到连接的话，你会发现oracle.sql.BLOB blob = (oracle.sql.BLOB)person.getImage();和 oracle.sql.CLOB clob = (oracle.sql.CLOB)person.getArticle();这俩行会出错，原因就是weblogic进行了包装。<br /><br />现在将以上两个问题的综合解决方案用以下代码说明：<br /><br /><br /><br />            for (int i = 0; i &lt; 10; i++) {<br />                LargeObject large = new LargeObject();<br />                large.setId(i + "");<br />                large.setName("林意炜");<br /><br />                // 插入一个小数据数据<br />                large.setImage(Hibernate.createBlob(new byte[1]));<br />                large.setArticle(Hibernate.createClob(" "));<br /><br />                session.save(large);<br />                session.flush();<br /><br />                // 锁定该记录<br />                session.refresh(large, LockMode.UPGRADE);<br /><br />                // 插入图片数据<br />                String fileName = "E:/AAA/" + i + ".jpg";<br />                SerializableBlob sb = (SerializableBlob)large.getImage();<br />                java.sql.Blob wrapBlob = sb.getWrappedBlob();<br />                // 通过非weblogic容器中数据源获得连接的情况<br />                if(wrapBlob instanceof oracle.sql.BLOB){<br />                    oracle.sql.BLOB blob = (oracle.sql.BLOB) wrapBlob;<br />                    OutputStream out = blob.getBinaryOutputStream();<br />                    out.write(getData(fileName));<br />                    out.close();<br />                }<br />                // 使用weblogic的Oracle Thin driver类型连接池，驱动类名：oracle.jdbc.OracleDriver<br />                else if(wrapBlob instanceof weblogic.jdbc.vendor.oracle.OracleThinBlob){<br />                    OracleThinBlob blob = (OracleThinBlob)wrapBlob;<br />                    OutputStream out = blob.getBinaryOutputStream();<br />                    out.write(getData(fileName));<br />                    out.close();<br />                }<br /><br /><br />                // 插入文章数据<br />                fileName = "E:/AAA/" + i + ".java";<br />                SerializableClob cb = (SerializableClob)large.getArticle();<br />                java.sql.Clob wrapClob = cb.getWrappedClob();<br />                // 通过非weblogic容器中数据源获得连接的情况<br />                if(wrapClob instanceof oracle.sql.CLOB){<br />                    oracle.sql.CLOB clob = (oracle.sql.CLOB) wrapClob;<br />                    Writer writer = clob.getCharacterOutputStream();<br />                    String article = new String(getData(fileName));<br />                    writer.write(article);<br />                    writer.close();<br />                }<br />                // 使用weblogic的Oracle Thin driver类型连接池，驱动类名：oracle.jdbc.OracleDriver<br />                else if(wrapClob instanceof weblogic.jdbc.vendor.oracle.OracleThinClob){<br />                    OracleThinClob clob = (OracleThinClob)wrapClob;<br />                    Writer writer = clob.getCharacterOutputStream();<br />                    String article = new String(getData(fileName));<br />                    writer.write(article);<br />                    writer.close();<br />                }<br />            }<br /><br /><br />***************************************************<br /><span class="postbody">采用得是ORACLE9i数据库，Jboss或Weblogic。 <br />JDBC采用ORACLE9i自带的Class12.jar <br />－－－－－－－－－－－－－ <br />数据库结构： <br /></span><table cellspacing="1" cellpadding="3" width="90%" align="center" border="0"><tbody><tr><td><span class="genmed"><b>java代码: </b></span></td></tr><tr><td class="code"><div style="FONT-FAMILY: 'Courier New', Courier, monospace"><br /><br />CREATE TABLE SNCPARAMETERS <br /><span style="COLOR: #000000">(</span><br />  ID     NUMBER<span style="COLOR: #000000">(</span><span style="COLOR: #000000" ?="">19</span><span style="COLOR: #000000">)</span>                             NOT <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">NULL</span>, <br />  SNCID  NUMBER<span style="COLOR: #000000">(</span><span style="COLOR: #000000" ?="">19</span><span style="COLOR: #000000">)</span>, <br />  NAME   VARCHAR2<span style="COLOR: #000000">(</span><span style="COLOR: #000000" ?="">255</span><span style="COLOR: #000000">)</span>, <br />  VALUE  CLOB <br /><span style="COLOR: #000000">)</span><br /></div><br /></td></tr></tbody></table><span class="postbody"><br />－－－－－－－－－－－－－－ <br />BO采用xdoclet建立的： <br /></span><table cellspacing="1" cellpadding="3" width="90%" align="center" border="0"><tbody><tr><td><span class="genmed"><b>java代码: </b></span></td></tr><tr><td class="code"><div style="FONT-FAMILY: 'Courier New', Courier, monospace"><br /><br /><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">class</span> SNCParameters <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">extends</span> BaseObject <br /><span style="COLOR: #000000">{</span><br /><br />    <span style="COLOR: #6666ff">/** <br />     * Returns the id. <br />     * <br />     * @return      long <br />     * @hibernate.id <br />     *          column = "id" <br />     *          type = "long" <br />     *          generator-class = "native" <br />     *          unsaved-value = "null" <br />     */</span><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="COLOR: #aaaadd" ?="">Long</span> getId<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">return</span> id; <br />    <span style="COLOR: #000000">}</span><br /><br />    <span style="COLOR: #6666ff">/** <br />     *    Sets the Id attribute of the SNCParameters object <br />     * <br />     * @param    id  The new Id value <br />     */</span><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">void</span> setId<span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">Long</span> id<span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        this.<span style="COLOR: #000000">id</span> = id; <br />    <span style="COLOR: #000000">}</span><br /><br /><br />    <span style="COLOR: #6666ff">/** <br />     * Returns the name. <br />     * <br />     * @return      String <br />     * <br />     * @hibernate.property <br />     *          column = "name" <br />     *          type = "string" <br />     *          not-null = "true" <br />     *          unique = "false" <br />     */</span><br /><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="COLOR: #aaaadd" ?="">String</span> getName<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">return</span> name; <br />    <span style="COLOR: #000000">}</span><br /><br />    <span style="COLOR: #6666ff">/** <br />     *    Sets the Name attribute of the SNCParameters object <br />     * <br />     * @param    name  The new Name value <br />     */</span><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">void</span> setName<span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">String</span> name<span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        this.<span style="COLOR: #000000">name</span> = name; <br />    <span style="COLOR: #000000">}</span><br /><br />    <span style="COLOR: #6666ff">/** <br />     * Returns the sncId. <br />     * <br />     * @return      Long <br />     * <br />     * @hibernate.property <br />     *          column = "sncId" <br />     *          type = "long" <br />     *          not-null = "true" <br />     *          unique = "false" <br />     */</span><br /><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="COLOR: #aaaadd" ?="">Long</span> getSncId<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">return</span> sncId; <br />    <span style="COLOR: #000000">}</span><br /><br />    <span style="COLOR: #6666ff">/** <br />     *    Sets the SncId attribute of the SNCParameters object <br />     * <br />     * @param    sncId  The new SncId value <br />     */</span><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">void</span> setSncId<span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">Long</span> sncId<span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        this.<span style="COLOR: #000000">sncId</span> = sncId; <br />    <span style="COLOR: #000000">}</span><br /><br />    <span style="COLOR: #6666ff">/** <br />     * Returns the values. <br />     * <br />     * @return      Clob <br />     * <br />     * @hibernate.property <br />     *          column = "value" <br />     *          type = "clob" <br />     *          not-null = "true" <br />     *          unique = "false" <br />     */</span><br /><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="COLOR: #aaaadd" ?="">Clob</span> getValue<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">return</span> value; <br />    <span style="COLOR: #000000">}</span><br /><br />    <span style="COLOR: #6666ff">/** <br />     *    Sets the Values attribute of the SNCParameters object <br />     * <br />     * @param    values  The new Values value <br />     */</span><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">void</span> setValue<span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">Clob</span> value<span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        this.<span style="COLOR: #000000">value</span> = value; <br />    <span style="COLOR: #000000">}</span><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">private</span><span style="COLOR: #aaaadd" ?="">Long</span> id; <br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">private</span><span style="COLOR: #aaaadd" ?="">Long</span> sncId; <br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">private</span><span style="COLOR: #aaaadd" ?="">String</span> name; <br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">private</span><span style="COLOR: #aaaadd" ?="">Clob</span> value; <br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">private</span><span style="COLOR: #aaaadd" ?="">String</span> valueString; <br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="COLOR: #aaaadd" ?="">String</span> getValueString<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">return</span> valueString; <br />    <span style="COLOR: #000000">}</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">void</span> setValueString<span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">String</span>  valueString<span style="COLOR: #000000">)</span><br />    <span style="COLOR: #000000">{</span><br />        this.<span style="COLOR: #000000">valueString</span> = valueString; <br />    <span style="COLOR: #000000">}</span><br /><span style="COLOR: #000000">}</span><br /></div><br /></td></tr></tbody></table><span class="postbody"><br /><br /><span style="FONT-WEIGHT: bold">注：valueString并不映射到数据库的CLOB字段，只是方便需要使用这个BO的人用GET、SET 处理这个巨长的CLOB字段</span><br />－－－－－－－－－－－－ <br />xdocLet生成的XML文件： <br /></span><table cellspacing="1" cellpadding="3" width="90%" align="center" border="0"><tbody><tr><td><span class="genmed"><b>java代码: </b></span></td></tr><tr><td class="code"><div style="FONT-FAMILY: 'Courier New', Courier, monospace"><br /><br />&lt;?xml version="<span style="COLOR: #000000" ?="">1</span>.<span style="COLOR: #000000" ?="">0</span>"?&gt; <br /><br />&lt;!DOCTYPE hibernate-mapping <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">PUBLIC</span><br />    "-<span style="COLOR: #6666ff">//Hibernate/Hibernate Mapping DTD 2.0//EN" </span><br />    "http:<span style="COLOR: #6666ff">//hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"&gt;</span><br /><br />&lt;hibernate-mapping&gt; <br />    &lt;<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">class</span><br />        name="com.<span style="COLOR: #000000">idncn</span>.<span style="COLOR: #000000">mc</span>.<span style="COLOR: #000000">bo</span>.<span style="COLOR: #000000">SNCParameters</span>" <br />        table="SNCParameters" <br />        dynamic-update="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">false</span>" <br />        dynamic-insert="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">false</span>" <br />    &gt; <br /><br />        &lt;id <br />            name="id" <br />            column="id" <br />            type="long" <br />            unsaved-value="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">null</span>" <br />        &gt; <br />            &lt;generator <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">class</span>="native"&gt; <br />            &lt;/generator&gt; <br />        &lt;/id&gt; <br /><br />        &lt;property <br />            name="name" <br />            type="string" <br />            update="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">true</span>" <br />            insert="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">true</span>" <br />            column="name" <br />            not-<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">null</span>="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">true</span>" <br />            unique="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">false</span>" <br />        /&gt; <br /><br />        &lt;property <br />            name="sncId" <br />            type="long" <br />            update="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">true</span>" <br />            insert="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">true</span>" <br />            column="sncId" <br />            not-<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">null</span>="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">true</span>" <br />            unique="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">false</span>" <br />        /&gt; <br /><br />        &lt;property <br />            name="value" <br />            type="clob" <br />            update="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">true</span>" <br />            insert="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">true</span>" <br />            column="value" <br />            not-<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">null</span>="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">true</span>" <br />            unique="<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">false</span>" <br />        /&gt; <br />    &lt;/<span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">class</span>&gt; <br /><br />&lt;/hibernate-mapping&gt; <br /></div><br /></td></tr></tbody></table><span class="postbody"><br />－－－－－－－－－－－－－－－－－－－－ <br />insert的代码： <br /></span><table cellspacing="1" cellpadding="3" width="90%" align="center" border="0"><tbody><tr><td><span class="genmed"><b>java代码: </b></span></td></tr><tr><td class="code"><div style="FONT-FAMILY: 'Courier New', Courier, monospace"><br /><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="COLOR: #aaaadd" ?="">List</span> batchAddSncParameters<span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">List</span> sncParametersList, <span style="COLOR: #aaaadd" ?="">Long</span> sncId<span style="COLOR: #000000">)</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">throws</span> DbAccessException <br />    <span style="COLOR: #000000">{</span><br />        logger.<span style="COLOR: #000000">enterMethod</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />        <span style="COLOR: #aaaadd" ?="">List</span> ret = <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span><span style="COLOR: #aaaadd" ?="">ArrayList</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">try</span><br />        <span style="COLOR: #000000">{</span><br />            sess = getSession<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />            <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">if</span><span style="COLOR: #000000">(</span>sncParametersList != <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">null</span> &amp;&amp; sncParametersList.<span style="COLOR: #000000">size</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span> &gt; <span style="COLOR: #000000" ?="">0</span><span style="COLOR: #000000">)</span><br />            <span style="COLOR: #000000">{</span><br />                <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">for</span><span style="COLOR: #000000">(</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">int</span> i = <span style="COLOR: #000000" ?="">0</span>; i &lt; sncParametersList.<span style="COLOR: #000000">size</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; i++<span style="COLOR: #000000">)</span><br />                <span style="COLOR: #000000">{</span><br />                    SNCParameters cp = <span style="COLOR: #000000">(</span>SNCParameters<span style="COLOR: #000000">)</span> sncParametersList.<span style="COLOR: #000000">get</span><span style="COLOR: #000000">(</span>i<span style="COLOR: #000000">)</span>; <br />                    long newId = -<span style="COLOR: #000000" ?="">1</span>; <br />                    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">if</span><span style="COLOR: #000000">(</span>cp != <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">null</span><span style="COLOR: #000000">)</span><br />                    <span style="COLOR: #000000">{</span><br />                        SNCParameters cpNew = <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span> SNCParameters<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                        cpNew.<span style="COLOR: #000000">setSncId</span><span style="COLOR: #000000">(</span>sncId<span style="COLOR: #000000">)</span>; <br />                        cpNew.<span style="COLOR: #000000">setName</span><span style="COLOR: #000000">(</span>cp.<span style="COLOR: #000000">getName</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />                        cpNew.<span style="COLOR: #000000">setValue</span><span style="COLOR: #000000">(</span>Hibernate.<span style="COLOR: #000000">createClob</span><span style="COLOR: #000000">(</span>" "<span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />                        newId = <span style="COLOR: #000000">(</span><span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">Long</span><span style="COLOR: #000000">)</span> sess.<span style="COLOR: #000000">save</span><span style="COLOR: #000000">(</span>cpNew<span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>.<span style="COLOR: #000000">longValue</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                        sess.<span style="COLOR: #000000">flush</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br /><br />                        sess.<span style="COLOR: #000000">refresh</span><span style="COLOR: #000000">(</span>cpNew, LockMode.<span style="COLOR: #000000">UPGRADE</span><span style="COLOR: #000000">)</span>; <br />                        <span style="COLOR: #aaaadd" ?="">String</span> content = cp.<span style="COLOR: #000000">getValueString</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br /><br />                        <span style="COLOR: #aaaadd" ?="">String</span> appserver = <span style="COLOR: #aaaadd" ?="">System</span>.<span style="COLOR: #000000">getProperty</span><span style="COLOR: #000000">(</span>"appserver", "jboss"<span style="COLOR: #000000">)</span>; <br />                        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">if</span><span style="COLOR: #000000">(</span>!appserver.<span style="COLOR: #000000">equalsIgnoreCase</span><span style="COLOR: #000000">(</span>"jboss"<span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span><br />                        <span style="COLOR: #000000">{</span><br />                            <span style="COLOR: #6666ff">//weblogic</span><br />                            OracleThinClob clob = <span style="COLOR: #000000">(</span>OracleThinClob<span style="COLOR: #000000">)</span> cpNew.<span style="COLOR: #000000">getValue</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                            java.<span style="COLOR: #000000">io</span>.<span style="COLOR: #000000">Writer</span> pw = clob.<span style="COLOR: #000000">getCharacterOutputStream</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                            pw.<span style="COLOR: #000000">write</span><span style="COLOR: #000000">(</span>content<span style="COLOR: #000000">)</span>; <br />                            pw.<span style="COLOR: #000000">flush</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                            pw.<span style="COLOR: #000000">close</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                        <span style="COLOR: #000000">}</span><br />                        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">else</span><br />                        <span style="COLOR: #000000">{</span><br />                            <span style="COLOR: #6666ff">//jboss</span><br />                            oracle.<span style="COLOR: #000000">sql</span>.<span style="COLOR: #000000">CLOB</span> clob = <span style="COLOR: #000000">(</span>oracle.<span style="COLOR: #000000">sql</span>.<span style="COLOR: #000000">CLOB</span><span style="COLOR: #000000">)</span> cpNew.<span style="COLOR: #000000">getValue</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                            java.<span style="COLOR: #000000">io</span>.<span style="COLOR: #000000">Writer</span> pw = clob.<span style="COLOR: #000000">getCharacterOutputStream</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                            pw.<span style="COLOR: #000000">write</span><span style="COLOR: #000000">(</span>content<span style="COLOR: #000000">)</span>; <br />                            pw.<span style="COLOR: #000000">flush</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                            pw.<span style="COLOR: #000000">close</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                        <span style="COLOR: #000000">}</span><br />                        ret.<span style="COLOR: #000000">add</span><span style="COLOR: #000000">(</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span><span style="COLOR: #aaaadd" ?="">Long</span><span style="COLOR: #000000">(</span>newId<span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />                    <span style="COLOR: #000000">}</span><br />                <span style="COLOR: #000000">}</span><br />            <span style="COLOR: #000000">}</span><br />        <span style="COLOR: #000000">}</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">catch</span><span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">Exception</span> e<span style="COLOR: #000000">)</span><br />        <span style="COLOR: #000000">{</span><br />            logger.<span style="COLOR: #000000">error</span><span style="COLOR: #000000">(</span>e<span style="COLOR: #000000">)</span>; <br />            ErrorReason errorReason = <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span> ErrorReason<span style="COLOR: #000000">(</span>ErrorReason.<span style="COLOR: #000000">INSERT_OBJECT_FAILED_REASON</span><span style="COLOR: #000000">)</span>; <br />            throw <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span> DbAccessException<span style="COLOR: #000000">(</span>DbAccessException.<span style="COLOR: #000000">DBA_OPERATE_EXCEPTION</span>, errorReason<span style="COLOR: #000000">)</span>; <br />        <span style="COLOR: #000000">}</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">finally</span><br />        <span style="COLOR: #000000">{</span><br />            closeSession<span style="COLOR: #000000">(</span>sess<span style="COLOR: #000000">)</span>; <br />            logger.<span style="COLOR: #000000">exitMethod</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />        <span style="COLOR: #000000">}</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">return</span> ret; <br />    <span style="COLOR: #000000">}</span><br /></div><br /></td></tr></tbody></table><span class="postbody"><br />－－－－－－－－－－－－－－－－－ <br />注：Weblogic必须使用<span style="FONT-WEIGHT: bold">weblogic.jdbc.vendor.oracle.OracleThinClob</span><br />－－－－－－－－－－－－－－－－－－－－－ <br />读取CLOB字段： <br /></span><table cellspacing="1" cellpadding="3" width="90%" align="center" border="0"><tbody><tr><td><span class="genmed"><b>java代码: </b></span></td></tr><tr><td class="code"><div style="FONT-FAMILY: 'Courier New', Courier, monospace"><br /><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="COLOR: #aaaadd" ?="">List</span> selectSncParametersBySncId<span style="COLOR: #000000">(</span>long sncId<span style="COLOR: #000000">)</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">throws</span> DbAccessException <br />    <span style="COLOR: #000000">{</span><br />        logger.<span style="COLOR: #000000">enterMethod</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />        <span style="COLOR: #aaaadd" ?="">List</span> ret = <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span><span style="COLOR: #aaaadd" ?="">ArrayList</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">try</span><br />        <span style="COLOR: #000000">{</span><br />            sess = getSession<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />            <span style="COLOR: #aaaadd" ?="">String</span> query = "select cp from cp in <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">class</span> com.<span style="COLOR: #000000">idncn</span>.<span style="COLOR: #000000">mc</span>.<span style="COLOR: #000000">bo</span>.<span style="COLOR: #000000">SNCParameters</span> where cp.<span style="COLOR: #000000">sncId</span> = ?"; <br />            logger.<span style="COLOR: #000000">debug</span><span style="COLOR: #000000">(</span>"SQL=" + query<span style="COLOR: #000000">)</span>; <br />            <span style="COLOR: #aaaadd" ?="">List</span> iter = sess.<span style="COLOR: #000000">find</span><span style="COLOR: #000000">(</span>query, <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span><span style="COLOR: #aaaadd" ?="">Long</span><span style="COLOR: #000000">(</span>sncId<span style="COLOR: #000000">)</span>, Hibernate.<span style="COLOR: #000000">LONG</span><span style="COLOR: #000000">)</span>; <br />            <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">for</span><span style="COLOR: #000000">(</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">int</span> i = <span style="COLOR: #000000" ?="">0</span>; i &lt; iter.<span style="COLOR: #000000">size</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; i++<span style="COLOR: #000000">)</span><br />            <span style="COLOR: #000000">{</span><br />                SNCParameters newCp = <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span> SNCParameters<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                SNCParameters cp = <span style="COLOR: #000000">(</span>SNCParameters<span style="COLOR: #000000">)</span><span style="COLOR: #000000">(</span>iter.<span style="COLOR: #000000">get</span><span style="COLOR: #000000">(</span>i<span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />                logger.<span style="COLOR: #000000">debug</span><span style="COLOR: #000000">(</span>"after fetch:" + cp<span style="COLOR: #000000">)</span>; <br />                newCp.<span style="COLOR: #000000">setId</span><span style="COLOR: #000000">(</span>cp.<span style="COLOR: #000000">getId</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />                newCp.<span style="COLOR: #000000">setSncId</span><span style="COLOR: #000000">(</span>cp.<span style="COLOR: #000000">getSncId</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />                newCp.<span style="COLOR: #000000">setName</span><span style="COLOR: #000000">(</span>cp.<span style="COLOR: #000000">getName</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />                java.<span style="COLOR: #000000">sql</span>.<span style="COLOR: #000000">Clob</span> clob = cp.<span style="COLOR: #000000">getValue</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">if</span><span style="COLOR: #000000">(</span>clob != <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">null</span><span style="COLOR: #000000">)</span><br />                <span style="COLOR: #000000">{</span><br />                    logger.<span style="COLOR: #000000">debug</span><span style="COLOR: #000000">(</span>"b===" + clob.<span style="COLOR: #000000">length</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />                    <span style="COLOR: #aaaadd" ?="">String</span> b = clob.<span style="COLOR: #000000">getSubString</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000" ?="">1</span>, <span style="COLOR: #000000">(</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">int</span><span style="COLOR: #000000">)</span> clob.<span style="COLOR: #000000">length</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />                    <span style="COLOR: #6666ff">//logger.debug("b==="+b);</span><br />                    newCp.<span style="COLOR: #000000">setValueString</span><span style="COLOR: #000000">(</span>b<span style="COLOR: #000000">)</span>; <br />                <span style="COLOR: #000000">}</span><br />                ret.<span style="COLOR: #000000">add</span><span style="COLOR: #000000">(</span>newCp<span style="COLOR: #000000">)</span>; <br />            <span style="COLOR: #000000">}</span><br />        <span style="COLOR: #000000">}</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">catch</span><span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">Exception</span> e<span style="COLOR: #000000">)</span><br />        <span style="COLOR: #000000">{</span><br />            logger.<span style="COLOR: #000000">error</span><span style="COLOR: #000000">(</span>e<span style="COLOR: #000000">)</span>; <br />            ErrorReason errorReason = <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span> ErrorReason<span style="COLOR: #000000">(</span>ErrorReason.<span style="COLOR: #000000">SELECT_FAILED_REASON</span><span style="COLOR: #000000">)</span>; <br />            throw <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span> DbAccessException<span style="COLOR: #000000">(</span>DbAccessException.<span style="COLOR: #000000">DBA_OPERATE_EXCEPTION</span>, errorReason<span style="COLOR: #000000">)</span>; <br />        <span style="COLOR: #000000">}</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">finally</span><br />        <span style="COLOR: #000000">{</span><br />            closeSession<span style="COLOR: #000000">(</span>sess<span style="COLOR: #000000">)</span>; <br />            logger.<span style="COLOR: #000000">exitMethod</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />        <span style="COLOR: #000000">}</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">return</span> ret; <br />    <span style="COLOR: #000000">}</span><br /></div><br /></td></tr></tbody></table><span class="postbody"><br />－－－－－－－－－－－－－－－ <br />更新这个字段的代码： <br /></span><table cellspacing="1" cellpadding="3" width="90%" align="center" border="0"><tbody><tr><td><span class="genmed"><b>java代码: </b></span></td></tr><tr><td class="code"><div style="FONT-FAMILY: 'Courier New', Courier, monospace"><br /><br />    <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">public</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">void</span> updateSncParameters<span style="COLOR: #000000">(</span>SNCParameters newParam<span style="COLOR: #000000">)</span><span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">throws</span> DbAccessException <br />    <span style="COLOR: #000000">{</span><br />        logger.<span style="COLOR: #000000">enterMethod</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">try</span><br />        <span style="COLOR: #000000">{</span><br />            sess = getSession<span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br /><br />            <span style="COLOR: #aaaadd" ?="">Long</span> id = newParam.<span style="COLOR: #000000">getId</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />            SNCParameters pp = <span style="COLOR: #000000">(</span>SNCParameters<span style="COLOR: #000000">)</span> sess.<span style="COLOR: #000000">load</span><span style="COLOR: #000000">(</span>SNCParameters.<span style="COLOR: #000000">class</span>, id, net.<span style="COLOR: #000000">sf</span>.<span style="COLOR: #000000">hibernate</span>.<span style="COLOR: #000000">LockMode</span>.<span style="COLOR: #000000">UPGRADE</span><span style="COLOR: #000000">)</span>; <br /><br />            pp.<span style="COLOR: #000000">setSncId</span><span style="COLOR: #000000">(</span>newParam.<span style="COLOR: #000000">getSncId</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />            pp.<span style="COLOR: #000000">setName</span><span style="COLOR: #000000">(</span>newParam.<span style="COLOR: #000000">getName</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br />            pp.<span style="COLOR: #000000">setId</span><span style="COLOR: #000000">(</span>newParam.<span style="COLOR: #000000">getId</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br /><br />            <span style="COLOR: #aaaadd" ?="">String</span> newValue = newParam.<span style="COLOR: #000000">getValueString</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />            logger.<span style="COLOR: #000000">debug</span><span style="COLOR: #000000">(</span>"Update Length =" + newValue.<span style="COLOR: #000000">length</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span>; <br /><br />            <span style="COLOR: #aaaadd" ?="">String</span> appserver = <span style="COLOR: #aaaadd" ?="">System</span>.<span style="COLOR: #000000">getProperty</span><span style="COLOR: #000000">(</span>"appserver", "jboss"<span style="COLOR: #000000">)</span>; <br />            logger.<span style="COLOR: #000000">debug</span><span style="COLOR: #000000">(</span>"appserver: " + appserver<span style="COLOR: #000000">)</span>; <br />            <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">if</span><span style="COLOR: #000000">(</span>!appserver.<span style="COLOR: #000000">equalsIgnoreCase</span><span style="COLOR: #000000">(</span>"jboss"<span style="COLOR: #000000">)</span><span style="COLOR: #000000">)</span><br />            <span style="COLOR: #000000">{</span><br />                <span style="COLOR: #6666ff">//weblogic</span><br />                OracleThinClob clob = <span style="COLOR: #000000">(</span>OracleThinClob<span style="COLOR: #000000">)</span> pp.<span style="COLOR: #000000">getValue</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">if</span><span style="COLOR: #000000">(</span>pp != <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">null</span><span style="COLOR: #000000">)</span><br />                <span style="COLOR: #000000">{</span><br />                    java.<span style="COLOR: #000000">io</span>.<span style="COLOR: #000000">Writer</span> pw = clob.<span style="COLOR: #000000">getCharacterOutputStream</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                    pw.<span style="COLOR: #000000">write</span><span style="COLOR: #000000">(</span>newValue<span style="COLOR: #000000">)</span>; <br />                    pw.<span style="COLOR: #000000">flush</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                    pw.<span style="COLOR: #000000">close</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                <span style="COLOR: #000000">}</span><br />            <span style="COLOR: #000000">}</span><br />            <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">else</span><br />            <span style="COLOR: #000000">{</span><br />                <span style="COLOR: #6666ff">//jboss</span><br />                oracle.<span style="COLOR: #000000">sql</span>.<span style="COLOR: #000000">CLOB</span> clob = <span style="COLOR: #000000">(</span>oracle.<span style="COLOR: #000000">sql</span>.<span style="COLOR: #000000">CLOB</span><span style="COLOR: #000000">)</span> pp.<span style="COLOR: #000000">getValue</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">if</span><span style="COLOR: #000000">(</span>pp != <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">null</span><span style="COLOR: #000000">)</span><br />                <span style="COLOR: #000000">{</span><br />                    java.<span style="COLOR: #000000">io</span>.<span style="COLOR: #000000">Writer</span> pw = clob.<span style="COLOR: #000000">getCharacterOutputStream</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                    pw.<span style="COLOR: #000000">write</span><span style="COLOR: #000000">(</span>newValue<span style="COLOR: #000000">)</span>; <br />                    pw.<span style="COLOR: #000000">flush</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                    pw.<span style="COLOR: #000000">close</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />                <span style="COLOR: #000000">}</span><br />            <span style="COLOR: #000000">}</span><br />        <span style="COLOR: #000000">}</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">catch</span><span style="COLOR: #000000">(</span><span style="COLOR: #aaaadd" ?="">Exception</span> e<span style="COLOR: #000000">)</span><br />        <span style="COLOR: #000000">{</span><br />            logger.<span style="COLOR: #000000">error</span><span style="COLOR: #000000">(</span>e<span style="COLOR: #000000">)</span>; <br />            ErrorReason errorReason = <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span> ErrorReason<span style="COLOR: #000000">(</span>ErrorReason.<span style="COLOR: #000000">UPDATE_OBJECT_FAILED_REASON</span><span style="COLOR: #000000">)</span>; <br />            throw <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">new</span> DbAccessException<span style="COLOR: #000000">(</span>DbAccessException.<span style="COLOR: #000000">DBA_OPERATE_EXCEPTION</span>, errorReason<span style="COLOR: #000000">)</span>; <br />        <span style="COLOR: #000000">}</span><br />        <span style="FONT-WEIGHT: bold; COLOR: #990066" ?="">finally</span><br />        <span style="COLOR: #000000">{</span><br />            closeSession<span style="COLOR: #000000">(</span>sess<span style="COLOR: #000000">)</span>; <br />            logger.<span style="COLOR: #000000">exitMethod</span><span style="COLOR: #000000">(</span><span style="COLOR: #000000">)</span>; <br />        <span style="COLOR: #000000">}</span><br />    <span style="COLOR: #000000">}</span><br /></div></td></tr></tbody></table><br /><br /><img src ="http://www.blogjava.net/buaacaptain/aggbug/57616.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/buaacaptain/" target="_blank">船长</a> 2006-07-11 11:07 <a href="http://www.blogjava.net/buaacaptain/archive/2006/07/11/57616.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>web中下拉列表的几种实现</title><link>http://www.blogjava.net/buaacaptain/archive/2006/07/10/57475.html</link><dc:creator>船长</dc:creator><author>船长</author><pubDate>Mon, 10 Jul 2006 05:52:00 GMT</pubDate><guid>http://www.blogjava.net/buaacaptain/archive/2006/07/10/57475.html</guid><wfw:comment>http://www.blogjava.net/buaacaptain/comments/57475.html</wfw:comment><comments>http://www.blogjava.net/buaacaptain/archive/2006/07/10/57475.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/buaacaptain/comments/commentRss/57475.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/buaacaptain/services/trackbacks/57475.html</trackback:ping><description><![CDATA[总结一下关于web上使用下拉框的情况<br /><br />从数据库中获得数据List，将数据放到Request里面<br />        使用setAttribute（”AList”,AList）<br />A中有2个属性（String id,String value）<br /><br />1.        使用JSTL的forEach方式<br />&lt;select name=”xx” ……..&gt;<br />&lt;c:forEach items="${AList}" var="p" &gt;<br />        &lt;c:choose&gt;<br />                &lt;c:when test="${xxx == p.id}"&gt;<br />                        &lt;option value='&lt;c:out value="${p.id}"/&gt;' selected="selected"&gt;<br />                                        &lt;c:out value="${p.value}"/&gt;<br />                        &lt;/option&gt;<br />                &lt;/c:when&gt;<br />        &lt;c:otherwise&gt;<br />                        &lt;option value='&lt;c:out value="${p.id}"/&gt;'&gt;<br />                                &lt;c:out value="${p.value}"/&gt;<br />                        &lt;/option&gt;<br />                &lt;/c:otherwise&gt;<br />        &lt;/c:choose&gt;        <br />&lt;c:forEach&gt;<br />&lt;/select&gt;<br /><br />2.        使用struts的标签<br />&lt;html:select property=”xxx”&gt;<br />&lt;html:options collection="AList" labelProperty="value" property="id" /&gt;<br />&lt;/html:select&gt;<br /><br />查一下struts的api文档，可以看到select 中选项有3 taglib可以使用。<br />第一种直接使用把所有选项写在中间。<br /><pre class="overflow">&lt;html:option value="0-15"&gt;0-15&lt;/html:option&gt;<br /> &lt;html:option value="15-20" &gt;15-20&lt;/html:option&gt;<br /> &lt;html:option value="20-30" &gt;20-30&lt;/html:option&gt;<br /> &lt;html:option value="20 or above"&gt;30 or above&lt;/html:option&gt;</pre><br /><br />第二种：把选项放在一个Collection中(这里使用List).在实际项目中，更多的是可能数据来源于db,文件等。这种情况用得比较多。<br /><br /><pre class="overflow">&lt;html:options collection="AList" property="value" labelProperty="label"/&gt;<br />把option放在list中的过程在Action中作处理<br />//prepare the age selector list.<br />List ageList =new ArrayList();<br />ageList.add(new LabelValueBean("0-15","0-15"));<br />ageList.add(new LabelValueBean("15-20","15-20"));<br />ageList.add(new LabelValueBean("20-30","20-30"));<br />ageList.add(new LabelValueBean("30 or above","30 or above"));<br />request.setAttribute("AList",AList);</pre><br /><br />这里使用了LabelValueBean，可以不用的，象<br />&lt;html:options collection="AList" labelProperty="value" property="id" /&gt;<br />只要在AList中填入的bean有value和id属性就可以<br /><br />第三种，把此list 作为Form 的一个属性.<br />&lt;html:optionsCollection property="AList" /&gt;<br />在Form 中添加AList 的setter和getter. Form中作如下处理。<br />//the list can be a form property.<br />f.setAgeList(AList);<br /><br />1.        从数据库中获得数据，你应该在Action里面取得数据后，将数据放到Request里面<br />2.        数据取出来后放在一个List或Collection或Map里面，我习惯用List<br />3.        从List或其它的容器中取数据应该用&lt;html:options&gt; 或&lt;html:optionsCollection&gt;<br />4.        &lt;html:options&gt; 和&lt;html:optionsCollection&gt;外层必须用&lt;html:select property=""&gt;，所以这个属性你必须在FormBean里定义<br />5.        由于你要用到这些标签，所以你必须定义FormBean<br />6.        <br />从Action取数据，以List为例<br /><br />List list = xxxxx;//从数据库中取得下拉列表中的数据<br />request.setAttribute("list",list);<br /><br />在页面显示<br /><pre class="overflow">&lt;html:form action="xxxx"&gt;<br />...<br />&lt;html:select property="xxx"&gt;<br />&lt;html:options collection="list" labelProperty="下拉框中显示的内容，一般是name或其它相似属性" property="各选项对应的值，一般是id" /&gt;<br />&lt;/html:select&gt;<br />...<br />&lt;/html:form&gt;</pre><br /><br />补充一点点：<br /><br />因为数据你要从 数据库去取， 所以一般在 action 里调用 DAO ，作为 request 的一个属性传到页面上； 这时一般用 &lt;html:options .../&gt; 标签<br /><br />另外，如果数据不从数据库去取，而是代码固定的，则一般把这种放到 ActionForm 里，作为属性在页面上取，这时一般用 &lt;html:optionsCollection ... /&gt;<br /><img src ="http://www.blogjava.net/buaacaptain/aggbug/57475.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/buaacaptain/" target="_blank">船长</a> 2006-07-10 13:52 <a href="http://www.blogjava.net/buaacaptain/archive/2006/07/10/57475.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>struts标签收集</title><link>http://www.blogjava.net/buaacaptain/archive/2006/07/06/56984.html</link><dc:creator>船长</dc:creator><author>船长</author><pubDate>Thu, 06 Jul 2006 09:10:00 GMT</pubDate><guid>http://www.blogjava.net/buaacaptain/archive/2006/07/06/56984.html</guid><wfw:comment>http://www.blogjava.net/buaacaptain/comments/56984.html</wfw:comment><comments>http://www.blogjava.net/buaacaptain/archive/2006/07/06/56984.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/buaacaptain/comments/commentRss/56984.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/buaacaptain/services/trackbacks/56984.html</trackback:ping><description><![CDATA[
		<strong> </strong>Struts提供了五个标签库，即：HTML、Bean、Logic、Template和Nested。
<div><table style="WIDTH: 959px; HEIGHT: 129px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td align="middle"><p align="center"> 标签库</p></td><td align="middle"><p align="center"> 说明</p></td></tr><tr><td> HTML 标签</td><td> 用来创建能够和Struts 框架和其他相应的HTML 标签交互的HTML 输入表单</td></tr><tr><td> Bean 标签</td><td> 在访问JavaBeans 及其属性，以及定义一个新的bean 时使用</td></tr><tr><td> Logic 标签</td><td> 管理条件产生的输出和对象集产生的循环</td></tr><tr><td> Template 标签</td><td> 随着Tiles框架包的出现，此标记已开始减少使用</td></tr><tr><td> Nested 标签</td><td> 增强对其他的Struts 标签的嵌套使用的能力</td></tr></tbody></table></div><div><strong></strong> </div><div><strong>标签的公共特征</strong></div><div><strong></strong> </div><div>使用固定属性名称的Struts 标签：</div><div><table style="WIDTH: 946px; HEIGHT: 108px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td align="middle"><p align="center"> 属性</p></td><td align="middle"><p align="center"> 说明</p></td></tr><tr><td> id</td><td> 命名自定义标签创建时的脚本变量名。</td></tr><tr><td> name</td><td> 指出关键字值，在该关键字下可以找到一个存在的bean 。如果给出了scope属性，则仅仅在scope中查找。否则，根据标准的顺序在各种scope中查找：(page, request, session, or application)。</td></tr><tr><td> property</td><td> 指出bean 中的某个属性，可以在其中检索值。如果没有标明，则使用对象本身的值。</td></tr><tr><td> scope</td><td> 定义了Bean在哪个范围(page, request, session, or application)中被查找。如果没有标明按顺序查找。脚本变量(见id)将在相同的范围中创建。</td></tr></tbody></table></div><div> </div><div>Struts 标签也支持嵌套引用，例如：<br /><table style="WIDTH: 947px; HEIGHT: 72px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td>Property="foo.bar.baz"<br /><br />这相当于进行下面的调用：<br />getFoo().getBar().getBaz()；<br /><br />或者做为setter：<br />getFoo().getBar().setBaz(value)；</td></tr></tbody></table></div><div><strong></strong> </div><div>虽然Struts 标签的设计原意是为了避免使用scriptlet，scriptlet的表达式还能够提供给所有的Struts 标签使用。但请确保使用完整的表达式:<br /><div><strong><table style="WIDTH: 949px; HEIGHT: 90px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td> 错误：<br /> &lt;html:link href="'&lt;%= "/" + name %&gt;/index.jsp&gt;'&gt;<br /> <br /> 正确：<br /> &lt;html:link href="'&lt;%= "/" + name + "/index.jsp" %&gt;'&gt;    // 表达式必须提供整个属性值</td></tr></tbody></table></strong></div></div><div><strong></strong> </div><div><strong></strong> </div><div><strong>Html 标签库</strong></div><ol><li>&lt;html&gt;标签<br />它有两个属性：locale和xhtml，两者都不是必需的。<br /><div><strong><table style="WIDTH: 905px; HEIGHT: 73px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td> &lt;html:html locale=\"true\"&gt;<br /><br /> 此行代码解析后：<br /> &lt;html lang=\"en\"&gt;</td></tr></tbody></table></strong></div>说明：生成的结果取决于Struts应用程序所位于的服务器的locale。如果你将应用程序部署到一个不同locale的服务器，你不需要改变代码，Locale会自动调整。 
</li><li>&lt;base&gt;标签：表示所包含页面的绝对位置。这个标签只有内嵌在head标签中才有效。<br /><div><strong><table style="WIDTH: 907px; HEIGHT: 73px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td> &lt;html:base/&gt;<br /><br /> 此行代码解析后：<br /> &lt;base href=\"http://www.mymain.com/myStrutsApp/testing.jsp\"&gt;</td></tr></tbody></table></strong></div></li><li><div>&lt;img&gt;标签<br />最重要的属性page：图象文件的路径，前面必须带有一个斜线。<br />其它属性：heignt、width、alt。</div><div><strong><table style="WIDTH: 907px; HEIGHT: 24px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td>  &lt;html:img page=\"/logo.gif\" height=\"50\"  width=\"200\" alt=\"Web Logo\"/&gt;</td></tr></tbody></table></strong></div></li><li>&lt;link&gt;标签<br /><div><strong><table style="WIDTH: 908px; HEIGHT: 40px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td> &lt;html:link page=\"/index.html\"&gt;Click demo&lt;/html:link&gt;<br /><br /> 此行代码解析后：<br />  &lt;a href=\"/index.html\"&gt;Click demo&lt;/a&gt;</td></tr></tbody></table></strong></div></li><li>&lt;errors&gt;标签：通过一个简单的&lt;html:errors/&gt;标签，你就可以在一个JSP页面上显示完全自定义的错误信息。功能超强大！！<br />说明：这个标签在Request对象的属性集合中查找reserved key。如果它找到一个reserved key，它就假设这个key是一个String、或是一个String数组  <br />        （它包含在模块的MessageResources中查找的message keys）、或是类型为org.apache.struts.action.ActionErrors的一个对象。<br />          如果在应用程序资源中存在相应的信息，那么就可以用下面这些可选的message keys：  <br />         · errors.header  or  errors.prefix：相应的信息在错误信息的单独列表前显示。 <br />         · errors.footer or  errors.suffix：相应的信息在错误信息的单独列表后显示。 
</li><li>&lt;form&gt;标签系列<br />使用&lt;form&gt;标签时必须遵循一些规则： 
<ol><li>标签中必须包含一个action属性，它是这个标签中唯一必需的属性。如果不具备该属性则JSP页面会抛出一个异常。之后你必须给这个action属性指定一个有效值。一个有效值是指应用程序的Struts配置文件中元素里的任何一个子元素的访问路径。而且相应的元素中必须有一个name属性，它的值是form bean的名称。<br /><div><strong><table style="WIDTH: 624px; HEIGHT: 265px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td> &lt;html:form action=\"/login\" &gt; <br /><br /> 如果你有上述一个标签 ，那么你的Struts配置文件的元素中必须有一个如下显示为粗体的元素： <br />&lt;action-mappings&gt; <br />     &lt;action path=\"/login\" <br />      type=\"com.javapro.struts.LoginAction\"  <br />      name=\"loginForm\"<br />      scope=\"request\"<br />      input=\"/login.jsp\"&gt;<br />      &lt;forward name=\"success\" path=\"/mainMenu.jsp\"/&gt;<br />    &lt;/action&gt;<br />    .<br />    .<br />    .<br />&lt;/action-mappings&gt;  // 这就是说一个form标签是和form bean相关联的。</td></tr></tbody></table><br /></strong></div></li><li><div>任何包含在&lt;form&gt;中用来接收用户输入的标签（&lt;text&gt;、&lt;password&gt;、&lt;hidden&gt;、&lt;textarea&gt;、&lt;radio&gt;、&lt;checkbox&gt;、&lt;select&gt;）必须在相关的form bean中有一个指定的属性值。比如，如果你有一个属性值被指定为“username”的&lt;text&gt;标签，那么相关的form bean中也必须有一个名为“username”的属性。输入&lt;text&gt;标签中的值会被用于生成form bean的userName属性。</div></li></ol><div><br />&lt;form&gt;标签还有一些不是必须但很有用的“次要”属性。<br />比如，你可以用focus属性来生成JavaScript，它会“定焦”（focus）到该form所包含的一个元素上。使用focus属性时你需要给它指定元素的名称。<br /></div><div><strong><table style="WIDTH: 664px; HEIGHT: 397px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td> &lt;body&gt;<br /> &lt;html:form action=\"/login\" focus=\"password\"&gt;<br /> User Name: &lt;html:text property=\"userName\"/&gt;<br /> &lt;br&gt;Password: &lt;html:text property=\"password\"/&gt;<br /> &lt;br&gt;&lt;html:submit/&gt;<br /> &lt;/html:form&gt;<br /> &lt;/body&gt;<br /><br /> 代码解析后：<br /> &lt;body&gt;<br /> &lt;form name=\"loginForm\" method=\"post\"  action=\"/myStrutsApp/login.do\"&gt;<br /> User Name: &lt;input type=\"text\" name=\"userName\"  value=\"\"&gt;<br /> &lt;br&gt;Password: &lt;input type=\"text\"  name=\"password\" value=\"\"&gt;<br /> &lt;br&gt;&lt;input type=\"submit\"   value=\"Submit\"&gt;<br /> &lt;/form&gt;<br /> &lt;script language=\"JavaScript\"  type=\"text/javascript\"&gt;<br />  &lt;!--<br />  if (document.forms[\"loginForm\"].elements[\"password\"].type != \"hidden\") <br />       document.forms[\"loginForm\"].elements[\"password\"].focus()<br />  // --&gt;<br /> &lt;/script&gt;<br /><br /> &lt;/body&gt;</td></tr></tbody></table></strong></div>有没有看到这个标签库是如何建立JavaScript来定焦到password元素上的? 这也是该库让人着迷的地方之一。你不用担心如何在客户端进行编程，它会帮你自动生成。<br />还可以看到，&lt;form&gt;标签中method属性的缺省值是POST。<br /><br />&lt;text&gt;标签、&lt;hidden&gt;标签、&lt;textarea&gt;标签、&lt;radio&gt;标签、&lt;checkbox&gt;标签、&lt;submit&gt;标签、&lt;reset&gt;标签：<br />都有一个property属性，最后会被转换成HTML中的name属性，当然还有name和value属性。<br /><br />&lt;password&gt;标签<br /><div><strong><table style="WIDTH: 664px; HEIGHT: 24px" bordercolor="#000000" cellspacing="1" cellpadding="1" bgcolor="#ffffcc" border="1"><tbody><tr><td>  &lt;html:password property=\"password\"  redisplay=\"false\"/&gt;</td></tr></tbody></table></strong></div>该标签中的一个很重要的属性是"redisplay"，它用于重新显示以前输入到这个区域中的值。该属性的缺省值为true。然而，为了使password不能被重新显示，你或许希望将该属性的值设为false。<br /><br />&lt;select&gt;标签和&lt;option&gt;标签：  <strong><div><table style="WIDTH: 663px; HEIGHT: 24px" bordercolo