﻿<?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-honzeland-文章分类-JAVA</title><link>http://www.blogjava.net/honzeland/category/17080.html</link><description /><language>zh-cn</language><lastBuildDate>Fri, 12 Oct 2007 09:04:40 GMT</lastBuildDate><pubDate>Fri, 12 Oct 2007 09:04:40 GMT</pubDate><ttl>60</ttl><item><title>如何使用Log4j？</title><link>http://www.blogjava.net/honzeland/articles/133434.html</link><dc:creator>honzeland</dc:creator><author>honzeland</author><pubDate>Mon, 30 Jul 2007 13:13:00 GMT</pubDate><guid>http://www.blogjava.net/honzeland/articles/133434.html</guid><wfw:comment>http://www.blogjava.net/honzeland/comments/133434.html</wfw:comment><comments>http://www.blogjava.net/honzeland/articles/133434.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/honzeland/comments/commentRss/133434.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/honzeland/services/trackbacks/133434.html</trackback:ping><description><![CDATA[From：http://www.blogjava.net/rickhunter/articles/28133.html<br />
<br />
<font size="2">
<strong>1、 Log4j是什么？<br />
</strong>&nbsp; Log4j可以帮助调试（有时候debug是发挥不了作 用的）和分析，要下载和了解更详细的内容，还是访问其官方网站吧：</font>
<a href="http://jakarta.apache.org/log4j">
<font size="2">http://jakarta.apache.org/log4j</font>
</a>
<font size="2">。<br />
<br />
<strong>2、Log4j的概念</strong><br />
&nbsp;&nbsp;<!--startfragment --> Log4j中有三个主要的组件，它们分别是</font>
<font size="2">Logger、Appender和Layout，L<!--startfragment -->og4j
允许开发人员定义多个Logger，每个Logger拥有自己的名字，Logger之间通过名字来表明隶属关系。有一个Logger称为Root，它永远
存在，且不能通过名字检索或引用，可以通过Logger.getRootLogger()方法获得，其它Logger通过
Logger.getLogger(String name)方法。<br />
&nbsp;&nbsp; Appender则是用来指明将所有的log信息存放到什么地方，Log4j中支持多种appender，如<!--startfragment --></font>
<font size="3">
</font>
<font size="2">console、files、GUI components、NT Event Loggers等，一个Logger可以拥有多个Appender，也就是你既可以将Log信息输出到屏幕，同时存储到一个文件中。<br />
&nbsp;&nbsp; Layout的作用是控制Log信息的输出方式，也就是格式化输出的信息。<br />
&nbsp;&nbsp;
Log4j中将要输出的Log信息定义了5种级别，依次为DEBUG、INFO、WARN、ERROR和FATAL，当输出时，只有级别高过配置中规定的
级别的信息才能真正的输出，这样就很方便的来配置不同情况下要输出的内容，而不需要更改代码，这点实在是方便啊。<br />
<br />
<strong>3、Log4j的配置文件</strong><br />
&nbsp;
虽然可以不用配置文件，而在程序中实现配置，但这种方法在如今的系统开发中显然是不可取的，能采用配置文件的地方一定一定要用配置文件。Log4j支持两
种格式的配置文件：XML格式和Java的property格式，本人更喜欢后者，首先看一个简单的例子吧，如下：<br />
<br />
</font>
<font color="#614db3">
<font size="2">&nbsp; log4j.rootLogger=debug, <strong>stdout, R</strong><br />
&nbsp; log4j.appender.<strong>stdout</strong>=org.apache.log4j.ConsoleAppender<br />
&nbsp; log4j.appender.stdout.layout=org.apache.log4j.PatternLayout<br />
<br />
&nbsp; # Pattern to output the caller's file name and line number.<br />
&nbsp; log4j.appender.stdout.layout.ConversionPattern=%5p [%t] <strong>(%F:%L)</strong> - %m%n<br />
<br />
&nbsp; log4j.appender.<strong>R</strong>=org.apache.log4j.RollingFileAppender<br />
&nbsp; log4j.appender.R.File=example.log<br />
&nbsp; log4j.appender.R.MaxFileSize=</font>
<font size="2">
<strong>100KB<br />
</strong>
<br />
&nbsp; # Keep one backup file<br />
&nbsp; log4j.appender.R.MaxBackupIndex=1<br />
<br />
&nbsp; log4j.appender.R.layout=org.apache.log4j.PatternLayout<br />
&nbsp; log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
<br />
</font>
<font color="#000000">
<font size="2">&nbsp; 首先，是设置root，格式为<!--startfragment --> log4j.rootLogger=[level],appenderName,&nbsp;...，其中level就是设置需要输出信息的级别，后面是appender的输出的目的地，<!--startfragment -->appenderName就是指定日志信息输出到哪个地方。您可以同时指定多个输出目的地。</font>
<font size="2">配置日志信息输出目的地Appender，其语法为<br />
</font>
<font size="2">&nbsp; log4j.appender.appenderName = fully.qualified.name.of.appender.class<br />
&nbsp; log4j.appender.appenderName.option1 = value1<br />
&nbsp; ...<br />
&nbsp; log4j.appender.appenderName.option = valueN</font>
<br />
<font size="2">Log4j提供的appender有以下几种：<br />
&nbsp; org.apache.log4j.ConsoleAppender（控制台）<br />
&nbsp; org.apache.log4j.FileAppender（文件）<br />
&nbsp; org.apache.log4j.DailyRollingFileAppender（每天产生一个日志文件）<br />
&nbsp; org.apache.log4j.RollingFileAppender（文件大小到达指定尺寸的时候产生新文件）<br />
&nbsp; org.apache.log4j.WriterAppender（将日志信息以流格式发送到任意指定的地方）<br />
</font>
</font>
</font>
<font color="#614db3">
<font color="#000000">
<font size="2">配置日志信息的格式（布局），其语法为：<br />
</font>
<font size="2">&nbsp; log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class<br />
&nbsp; log4j.appender.appenderName.layout.option1 = value1<br />
&nbsp; ....<br />
&nbsp; log4j.appender.appenderName.layout.option = valueN</font>
<br />
<font size="2">Log4j提供的layout有以下几种：<br />
&nbsp; org.apache.log4j.HTMLLayout（以HTML表格形式布局），<br />
&nbsp; org.apache.log4j.PatternLayout（可以灵活地指定布局模式），<br />
&nbsp; org.apache.log4j.SimpleLayout（包含日志信息的级别和信息字符串），<br />
&nbsp; org.apache.log4j.TTCCLayout（包含日志产生的时间、线程、类别等等信息） <br />
<br />
</font>
</font>
</font>
<font color="#000000">
<span style="font-size: 10.5pt;">
<font size="2">
<span lang="EN-US">Log4J采用类似C语言中的printf函数的打印格式格式化日志信息，打印参数如下： %m 输出代码中指定的消息<o:p></o:p></span>
</font>
</span>
</font>
<p>
<font color="#000000">
<span style="font-size: 10.5pt;">
<font size="2">　　</font>
<span lang="EN-US">
<font size="2">%p 输出优先级，即DEBUG，INFO，WARN，ERROR，FATAL <br />
%r 输出自应用启动到输出该log信息耗费的毫秒数 <br />
%c 输出所属的类目，通常就是所在类的全名 <br />
%t 输出产生该日志事件的线程名 <br />
%n 输出一个回车换行符，Windows平台为&#8220;\r\n&#8221;，Unix平台为&#8220;\n&#8221; <br />
%d 输出日志时间点的日期或时间，默认格式为ISO8601，也可以在其后指定格式，比如：%d{yyy MMM dd HH:mm:ss,SSS}，输出类似：</font>
</span>
</span>
<st1:chsdate isrocdate="False" islunardate="False" day="18" month="10" year="2002">
<span style="font-size: 10.5pt;" lang="EN-US">
<font size="2">2002年10月18日</font>
</span>
</st1:chsdate>
<span style="font-size: 10.5pt;" lang="EN-US">
<font size="2"> 22：10：28，921 <br />
%l 输出日志事件的发生位置，包括类目名、发生的线程，以及在代码中的行数。举例：Testlog4.main(TestLog4.java:10)</font>
</span>
</font>
</p>
<br />
<font color="#614db3">
<font color="#000000">
<font size="2">
<br />
<strong>4、Log4j在程序中的使用</strong>
</font>
</font>
</font>
<font color="#614db3">
<font color="#000000">
<br />
</font>
<font color="#a0a0a0">
<font color="#090909" size="2">&nbsp;
要在自己的程序中使用Log4j，首先需要将commons-logging.jar和logging-log4j-1.2.9.jar导入到构建路径
中。然后再将log4j.properties放到src根目录下。这样就可以在程序中使用log4j了。在类中使用log4j，</font>
</font>
</font>
<font color="#614db3">
<font color="#a0a0a0">
<font color="#090909" size="2">首先声明一个静态变量</font>
</font>
</font>
<font color="#614db3">
<font color="#a0a0a0">
<font color="#090909" size="2">Logger
logger=Logger.getLog("classname")；现在就可以使用了，用法如下：logger.debug("debug
message")或者logger.info("info message")，看下面一个小例子：</font>
</font>
</font>
<font color="#614db3">
<font color="#a0a0a0">
<br />
</font>
<br />
<font size="2">&nbsp; import com.foo.Bar;<br />
&nbsp; import org.apache.log4j.Logger;<br />
&nbsp;&nbsp;import org.apache.log4j.PropertyConfigurator;<br />
&nbsp;&nbsp;public class MyApp {<br />
&nbsp; &nbsp; static Logger logger = Logger.getLogger(MyApp.class.getName());<br />
&nbsp;&nbsp; &nbsp;public static void main(String[] args) {<br />
&nbsp;&nbsp;&nbsp; &nbsp; // BasicConfigurator replaced with PropertyConfigurator.<br />
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;PropertyConfigurator.configure(args[0]);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; logger.info("Entering application.");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Bar bar = new Bar();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bar.doIt();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; logger.info("Exiting application.");<br />
&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;}<br />
<br />
<br />
<br />
</font></font>
<div class="postTitle">
zz: http://www.blogjava.net/apple0668/archive/2007/10/11/152150.html<br />
<a id="viewpost1_TitleUrl" class="postTitle2" href="../../apple0668/archive/2007/10/11/152150.html">Log4配置</a><br />
</div>
<p>一、常用输出格式</p>
<p>%c&nbsp;&nbsp; 列出logger名字空间的全称，如加上{&lt;层数&gt;}表示出从最内层算起的指定层数的名字空间<br />
%X&nbsp; 按MDC（Mapped Diagnostic Context,线程映射表）输出日志。通常用于多个客户端连接同一台服务器，方便服务器区分是那个客户端访问留下来的日志。<br />
%p&nbsp; 日志信息级别<br />
%d&nbsp;&nbsp; %d{&lt;日期格式&gt;}:日志信息产生时间,使用ISO8601定义的日期格式<br />
%C&nbsp;&nbsp; 日志信息所在地（全限类名）<br />
%m&nbsp;&nbsp; 产生的日志具体信息<br />
%n&nbsp;&nbsp;&nbsp; 输出日志信息换行<br />
%F　显示调用logger的源文件名<br />
%l&nbsp;&nbsp;&nbsp;&nbsp; 输出日志事件的发生位置，包括类目名、发生的线程，以及在代码中的行数<br />
%L&nbsp;&nbsp;&nbsp; 显示调用logger的代码行<br />
%M&nbsp;&nbsp; 显示调用logger的方法名<br />
%r&nbsp;&nbsp;&nbsp;&nbsp; 显示从程序启动时到记录该条日志时已经经过的毫秒数<br />
%t&nbsp;&nbsp;&nbsp;&nbsp; 输出产生该日志事件的线程名<br />
%%　显示一个<br />
二、log4j.properties<br />
</p>
<p>#控制包中日志输出级别<br />
log4j.logger.org.apache.struts = debug</p>
<p># 应用于控制台<br />
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender<br />
log4j.appender.Threshold=DEBUG<br />
log4j.appender.CONSOLE.Target=System.out<br />
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout<br />
log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %-4r [%t] %-5p %c %x - %m%n<br />
#log4j.appender.CONSOLE.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD]
n%c[CATEGORY]%n%m[MESSAGE]%n%n</p>
<p>#应用于文件<br />
log4j.appender.FILE=org.apache.log4j.FileAppender<br />
log4j.appender.FILE.File=file.log<br />
log4j.appender.FILE.Append=false<br />
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout<br />
log4j.appender.FILE.layout.ConversionPattern=[framework] %d - %-4r [%t] %-5p %c %x - %m%n<br />
# Use this layout for LogFactor 5 analysis</p>
<p># 应用于文件回滚<br />
log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender<br />
log4j.appender.ROLLING_FILE.Threshold=ERROR<br />
log4j.appender.ROLLING_FILE.File=rolling.log<br />
log4j.appender.ROLLING_FILE.Append=true<br />
log4j.appender.ROLLING_FILE.MaxFileSize=100KB<br />
log4j.appender.ROLLING_FILE.MaxBackupIndex=10<br />
log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout<br />
log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %-4r [%t] %-5p %c %x - %m%n</p>
<p><br />
#应用于socket<br />
log4j.appender.SOCKET=org.apache.log4j.net.SocketAppender<br />
log4j.appender.SOCKET.RemoteHost=localhost<br />
log4j.appender.SOCKET.Port=5001<br />
log4j.appender.SOCKET.LocationInfo=true<br />
# Set up for Log Facter 5<br />
log4j.appender.SOCKET.layout=org.apache.log4j.PatternLayout<br />
log4j.appender.SOCET.layout.ConversionPattern=[start]%d{DATE}[DATE]%n%p[PRIORITY]%n%x[NDC]%n%t[THREAD]%n%c[CATEGORY]%n%m[MESSAGE]%n%n</p>
<p><br />
# Log Factor 5 Appender<br />
log4j.appender.LF5_APPENDER=org.apache.log4j.lf5.LF5Appender<br />
log4j.appender.LF5_APPENDER.MaxNumberOfRecords=2000</p>
<p># 发送日志给邮件<br />
log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender<br />
log4j.appender.MAIL.Threshold=FATAL<br />
log4j.appender.MAIL.BufferSize=10<br />
log4j.appender.MAIL.From=web@www.wuset.com<br />
log4j.appender.MAIL.SMTPHost=www.wusetu.com<br />
log4j.appender.MAIL.Subject=Log4J Message<br />
log4j.appender.MAIL.To=web@www.wusetu.com<br />
log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout<br />
log4j.appender.MAIL.layout.ConversionPattern=[framework] %d - %-4r [%t] %-5p %c %x - %m%n</p>
<p># 用于数据库<br />
log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender<br />
log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/test<br />
log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver<br />
log4j.appender.DATABASE.user=root<br />
log4j.appender.DATABASE.password=<br />
log4j.appender.DATABASE.sql=INSERT INTO LOG4J (Message) VALUES ('[framework] %d - %-4r [%t] %-5p %c %x - %m%n')<br />
log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout<br />
log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %-4r [%t] %-5p %c %x - %m%n</p>
<p>#每日回滚日志文件<br />
log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender<br />
log4j.appender.A1.File=SampleMessages.log4j<br />
log4j.appender.A1.DatePattern=yyyyMMdd-HH'.log4j'<br />
log4j.appender.A1.layout=org.apache.log4j.xml.XMLLayout</p>
<p>#自定义Appender<br />
log4j.appender.im = net.cybercorlin.util.logger.appender.IMAppender<br />
log4j.appender.im.host = mail.cybercorlin.net<br />
log4j.appender.im.username = username<br />
log4j.appender.im.password = password<br />
log4j.appender.im.recipient = corlin@cybercorlin.net<br />
log4j.appender.im.layout=org.apache.log4j.PatternLayout<br />
log4j.appender.im.layout.ConversionPattern =[framework] %d - %-4r [%t] %-5p %c %x - %m%n</p>
<br />
<br />
<img src ="http://www.blogjava.net/honzeland/aggbug/133434.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/honzeland/" target="_blank">honzeland</a> 2007-07-30 21:13 <a href="http://www.blogjava.net/honzeland/articles/133434.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Mastering the Java CLASSPATH </title><link>http://www.blogjava.net/honzeland/articles/96954.html</link><dc:creator>honzeland</dc:creator><author>honzeland</author><pubDate>Wed, 31 Jan 2007 06:32:00 GMT</pubDate><guid>http://www.blogjava.net/honzeland/articles/96954.html</guid><wfw:comment>http://www.blogjava.net/honzeland/comments/96954.html</wfw:comment><comments>http://www.blogjava.net/honzeland/articles/96954.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/honzeland/comments/commentRss/96954.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/honzeland/services/trackbacks/96954.html</trackback:ping><description><![CDATA[
		<h2>
				<font color="#ff1493">from </font>
				<a href="http://www.kevinboone.com/classpath.html">
						<font color="#ff1493">http://www.kevinboone.com/classpath.html</font>
				</a>
		</h2>
		<h2>The significance of the class search path</h2>An understanding of the class search path is important for all Java developers. However, the widespread use of integrated development tools has concealed the technicalities for so long that there is a widespread lack of comprehension, even among experienced developers. The problem is particularly acute with development of distributed applications, as the system which will run the application is likely to be configured rather differently from the one on which development takes place. 
<p>This article describes in detail how the Java compiler and the JVM use the class search path to locate classes when they are referenced by other Java code. It does this with reference to a very simple example, which uses two classes in the same package. We will see how various operations to compile these two classes succeed and fail, depending on the class path setting. </p><p>To make things absolutely clear, we will use only simple command-line tools to carry out the compile operations. Interactive development tools have their own ways of manipulating the class path, which vary from product to product. </p><p>There is no fundamental difference between the way that the Java compiler searches for classes, and the way that the JVM does it at run time. However, the compiler has the ability to compile classes from source code, where the JVM does not. In the examples below we will use the compiler, but similar issues apply at run time. </p><h2>The example</h2>This example has two trivial classes: <code>com.web_tomorrow.CPTest1</code> and <code>com.web_tomorrow.CPTest2</code>, which are listed below. <pre>package com.web_tomorrow;
public class CPTest1
{
public static void main(String[] args)
  {
  System.out.println ("Run CPTest1.main()");
  }
}

package com.web_tomorrow;
public class CPTest2
{
public static void main(String[] args)
  {
  System.out.println ("Run CPTest2.main()");
  CPTest1 cpt1 = new CPTest1();
  }
}
</pre>One of the most fundamental rules of Java code organization is that `package name = directory name'. We will begin by setting up a directory structure that matches the package assignment of these two classes. The classes are in a package <code>com.web_tomorrow</code>, so we must create the directory <code>com/web_tomorrow</code> to contain the source code. <pre>[root]
  com
    web_tomorrow
      CPTest1.java
      CPTest2.java
</pre>In this document I will use the notation `[root]' to mean `whatever directory contains the structure described above', that is, the root of the directory layout. This will vary, of course, according to how you install the files. 
<h2>Basic principles</h2>Let's try to compile <code>CPTest1.java</code> on its own using the command-line <code>javac</code> program. To disable the class search path completely (so any existing setting does not interfere with the example), we can run <code>javac</code> with the option `<code>-classpath ""</code>'. 
<p>As a first attempt, let's change directory to the location of <code>CPTest1.java</code>, and try to compile it by specifying its name on the <code>javac</code> command line. </p><pre>cd [root]/com/web_tomorrow
javac -classpath "" CPTest1.java
</pre>This operation succeeds, because the compiler is able to find <code>CPTest1.java</code> (it is in the working directory), and because <code>CPTest1</code> does not reference any other classes. The output file, <code>CPTest1.class</code> ends up in the same directory as <code>CPTest1.java</code> because, again, you haven't given the compiler information to do anything else. So far so good. Now let's try the same thing with <code>CPTest2</code>. Still in the `web_tomorrow' directory, execute this command: <pre>javac -classpath "" CPTest2.java
</pre>This operation should fail, even though the directory is the same as the previous step, and <code>CPTest1</code> and <code>CPTest2</code> are in the same package. The error message will be something like this: <pre>PTest2.java:7: cannot resolve symbol
symbol  : class CPTest1  
location: class com.web_tomorrow.CPTest2
  CPTest1 cpt1 = new CPTest1();
  ^
</pre>The difference between this case and the previous, successful, one is that <code>CPTest2</code> contains a reference to <code>CPTest1</code>: <pre>  CPTest1 cpt1 = new CPTest1();
</pre>What is going on here? When the compiler encounters the reference to <code>CP1Test</code> here, it assumes that this is a class in the same package as <code>CP2Test</code> that is is currently compiling. This is a correct assumption. So the compiler needs to find <code>com.web_tomorrow.CP1Test</code>. But it has nowhere to look, as we have explicitly set the class search path to "" (i.e., nothing). 
<p>You might think this problem can be resolved by telling the compiler to look in the current directory. The standard symbol for `current directory' is a single period (.) in both Unix and Windows systems. So try something like this: </p><pre>javac -classpath "." CPTest2.java
</pre>This fails in exactly the same way as the previous example. The problem now is that although <code>CPTest1.java</code> is in the current directory, the class that it implements is not just <code>CPTest1</code>, but <code>com.web_tomorrow.CPTest1</code>. The compiler will look for a directory <code>com/web_tomorrow</code><i>below</i> the current directory. So, <font color="#ff0000">overall, it is looking for a Java source or class file in the directory <code>[home]/com/web_tomorrow/com/web_tomorrow</code> which, of course, does not exist.</font><p>To make this compile operation work, we need to make the class search path reference not the directory containing <code>CPTest1</code>, but a directory root from which <code>CPTest1</code> can be located by the compiler following the standard Java `package name = directory name' rule. This should work, although it's rather ugly: </p><pre>javac -classpath "../.." CPTest2.java
</pre>Before seeing how we can make this less ugly, consider this example (still in the same directory): <pre>javac -classpath "" CPTest1.java CPTest2.java
</pre>This also works, even though the class path is empty. This is because the Java compiler will look for references between any source code explicitly listed on the command line. If there are many classes, all in the same directory, we can simplify this to: <pre>javac -classpath "" *.java 
</pre>The `*.java' expands to a list of all the .java files in the current directory. This explains why compiling many files in one operation often succeeds where attempts to compile a single file fails. 
<p>A more convenient way to compile <code>CPTest2</code> on its own is like this: </p><pre>cd [root]
javac -classpath "." com/web_tomorrow/CPTest2.java
</pre>In this example we specify the full path to <code>CPTest2.java</code>, but include `.' in the <code>-classpath</code> option. Again, we aren't telling the compiler to look for files in the current directory, we are telling it to <i>begin a class search</i> from the current directory. Because the class we are looking for is <code>com.web_tomorrow.CPTest1</code>, the compiler will search in <code>./com/web_tomorrow</code> (that is, the directory <code>com/web_tomorrow</code> below the current directory). This is exactly where <code>CPTest1.java</code> is located. 
<p>In fact, even though I only specified <code>CPTest2</code> on the command line, this practice does in fact lead to the compilation of <code>CPTest1</code> as well. The compiler finds the <code>.java</code> file in the right place, but it can't tell whether this Java source really implements the right class, so it has to compile it. But note that if we do this: </p><pre>cd [root]
javac -classpath "." com/web_tomorrow/CPTest1.java
</pre>it does not cause a compilation of <code>CPTest2.java</code>, because the compiler does not need to know anything about <code>CPTest2</code> to compile <code>CPTest1</code>. 
<h2>.class files separate from .java files</h2>The examples described so far, when successful, place the output <code>.class</code> files alongside the <code>.java</code> files from which they were generated. This is a simple scheme, and very widely used. However, many developers like to keep the source tree free of generated files, and must therefore tell the Java compiler to maintain separate directories for <code>.class</code> files. Let's see what impact this has on the class search path. 
<p>To begin we will need to delete any <code>.class</code> files lurking around after the previous examples. We will also contain a new directory <code>classes</code> to contain the generated <code>.class</code> files. The procedure at the command line would be something like this: </p><pre>cd [root]
rm com/web_tomorrow/*.class
mkdir classes
</pre>Don't forget to swap the `/' characters for '\' if you are using a Windows system. The directory structure now looks like this. <pre>[root]
  com
    web_tomorrow
      CPTest1.java
      CPTest2.java
  classes
</pre>Let's compile <code>CPTest1.java</code>, specifying <code>classes</code> as the destination directory (using the <code>-d</code> option): <pre>cd [root]
javac -d classes -classpath "" com/web_tomorrow/CPTest1.java 
</pre>This should succeed, but you should notice that the <code>.class</code> files have not been placed into the <code>classes</code> directory at all. Instead, we have a new directory structure like this: <pre>[root]
  com
    web_tomorrow
      CPTest1.java
      CPTest2.java
  classes
    com
      web_tomorrow
        CPTest1.class
</pre>What has happened is that the compiler has created a directory structure to match the package structure. It has done this to be helpful, as we shall see. When we come to compile <code>CPTest2.java</code> we have two choices. First, we can compile it as described above, allowing the compiler to compile <code>CPTest1</code> as part of the process. Alternatively, we can compile it and use the <code>-classpath</code> option to refer to the compiler to the <code>.class</code> file generated in the previous step. This method is superior, as we don't have to repeat the compilation of <code>CPTest1</code>. <pre>cd [root]
javac -d classes -classpath classes com/web_tomorrow/CPTest2.java 
</pre>By doing this, we end up with this directory structure. <pre>[root]
  com
    web_tomorrow
      CPTest1.java
      CPTest2.java
  classes
    com
      web_tomorrow
      CPTest1.class
      CPTest2.class
</pre>Of course we could have compiled both <code>.java</code> files in the same command, and got the same result. 
<h2>JARs on the classpath</h2>The java compiler and run-time can search for classes not only in separate files, but also in `JAR' archives. A JAR file can maintain its own directory structure, and Java follows exactly the same rules as for searching in ordinary directories. Specifically, `directory name = package name'. <font color="#ff0000">Because a JAR is itself a directory, to include a JAR file in the class search path, the path must reference the JAR itself, not merely the directory that contains the JAR</font>. This is a <i>very</i> common error. Suppose I have a JAR <code>myclasses.jar</code> in directory <code>/myclasses</code>. To have the Java compiler look for classes in this jar, we need to specify: <pre>javac -classpath /myclasses/myclasses.jar ...
</pre>and not merely the directory <code>myclasses</code>. 
<h2>Multiple class search directories</h2>In the examples above, we have told <code>javac</code> to search in only one directory at a time. In practice, your class search path will contain numerous directories and JAR archives. The <code>-classpath</code> option to <code>javac</code> and <code>java</code> allows multiple entries to be specified, but notice that the syntax is slightly different for Unix and Windows systems. 
<p>On Unix, we would do this: </p><pre>javac -classpath dir1:dir2:dir3 ...
</pre>whereas on Windows we have: <pre>javac -classpath dir1;dir2;dir3 ...
</pre>The reason for the difference is that Windows uses the colon (:) character as part of a filename, so it can't be used as a filename separator. Naturally the directory separator character is different as well: forward slash (/) for Unix and backslash (\) for Windows. 
<h2>System classpath</h2>Rather than specifying class search path on the <code>javac</code> command line, we can make use of a `system' class path. This is the class path that will be used by both the Java compiler and the JVM in the absence of specific instructions to the contrary. In both Unix and Windows systems, this is done by setting an environment variable. For example, in Linux with the <code>bash</code> shell: <pre>CLASSPATH=/myclasses/myclasses.jar;export CLASSPATH 
</pre>and in Windows: <pre>set CLASSPATH=c:\myclasses\myclasses.jar
</pre>This procedure is fine for short-term changes to the system CLASSPATH, but if you want these changes to be persistent you will need to arrange this yourself. Details vary from system to system. On a Linux system, for example, I would put the commands in the file <code>.bashrc</code> in my home directory. On Windows 2000/NT there is a `Control Panel' page for this. 
<p>Setting the system CLASSPATH is a useful procedure if you have JARs full of classes that you use all the time. For example, if I am developing Enterprise JavaBean (EJB) applications using Sun's J2EE `Reference Implementation', all the EJB-related classes are in a JAR called `<code>j2ee.jar</code>' that comes with the distribution. I want this JAR on the class search path all the time. In addition, most people want to ensure that the current directory is on the search path, whatever the current directory happens to be. So in my <code>.bashrc</code> file I have this line: </p><pre>CLASSPATH=/usr/j2ee/j2ee.jar:.;export CLASSPATH 
</pre>where the `.' indicates `current directory'. 
<p><font color="#ff0000">It is easy to overlook that the <code>-classpath</code> option on the command line <i>replaces</i> the default, system class path; it does not add to it.</font> So what should I do if I want to set the class path to include the default system classpath <i>plus</i> some other entries? I could simply use the <code>-classpath</code> option and list the default entries in addition to my extras. However, a better way is to reference the CLASSPATH environment variable. The syntax for this is different -- of course -- on Windows and Unix systems. On Unix: </p><pre>javac -classpath $CLASSPATH:dir1:dir2 ...
</pre>where <code>$CLASSPATH</code> expands to the current setting of the CLASSPATH environment variable. On Windows: <pre>javac -classpath %CLASSPATH%;dir1:dir2 ...
</pre>Finally, please note that if directories in your class search <font color="#ff0000">path have spaces in their names, you may have to use double-quotes on the command line to prevent the CLASSPATH being split up</font>. For example: <pre>javac -classpath "%CLASSPATH%";dir1:dir2 ...<br /><br /><br />//<br />//the article ended! the following is got from Sun Microsystem Document.
<br /><br /><br /><br /><br /><br /><br /><h1>Setting the class path</h1><h2>Synopsis</h2><blockquote>The class path is the path that the Java runtime environment searches for classes and other resource files. The class search path (more commonly known by the shorter name, "class path") can be set using either the <code>-classpath</code> option when calling a JDK tool (the preferred method) or by setting the <code>CLASSPATH</code> environment variable. The <code>-classpath</code> option is preferred because you can set it individually for each application without affecting other applications and without other applications modifying its value. <p><!-- DON'T USE CODE TAG HERE, BECAUSE ITALIC DOES NOT DISPLAY INSIDE CODE --><code>C:&gt;</code><i>sdkTool</i><code><b>-classpath</b></code><i>classpath1</i><code><b>;</b></code><i>classpath2</i>...</p><p>-or-</p><p><code>C:&gt; <b>set CLASSPATH=</b></code><i>classpath1</i><code><b>;</b></code><i>classpath2</i>...</p><p>where:</p><dl><dt><i>sdkTool</i></dt><dd>A command-line tool, such as <code>java</code>, <code>javac</code>, <code>javadoc</code>, or <code>apt</code>. For a listing, see <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/index.html">JDK Tools</a>.</dd><dt><i>classpath1</i><code><b>;</b></code><i>classpath2</i></dt><dd>Class paths to the .jar, .zip or .class files. Each <i>classpath</i> should end with a filename or directory depending on what you are setting the class path to: <ul><li>For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file.</li><li>For .class files in an unnamed package, the class path ends with the directory that contains the .class files.</li><li>For .class files in a named package, the class path ends with the directory that contains the "root" package (the first package in the full package name).</li></ul><p>Multiple path entries are separated by semi-colons. With the <code>set</code> command, it's important to omit spaces from around the equals sign (=).</p><p>The default class path is the current directory. Setting the <code>CLASSPATH</code> variable or using the <code>-classpath</code> command-line option overrides that default, so if you want to include the current directory in the search path, you must include "<b>.</b>" in the new settings.</p><p>Classpath entries that are neither directories nor archives (.zip or .jar files) nor * are ignored.</p></dd></dl></blockquote><h2>Description</h2><blockquote><p>The class path tells JDK tools and applications where to find third-party and user-defined classes -- that is, classes that are not Java <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/guides/extensions/index.html">extensions</a> or part of the Java platform. The class path needs to find any classes you've compiled with the javac compiler -- its default is the current directory to conveniently enable those classes to be found.</p><p>The JDK, the JVM and other JDK tools find classes by searching the Java platform (bootstrap) classes, any extension classes, and the class path, in that order. (For details on the search strategy, see <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/findingclasses.html">How Classes Are Found</a>.) Class libraries for most applications will want to take advantage of the <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/guides/extensions/index.html">extensions mechanism</a>. You only need to set the class path when you want to load a class that's (a) not in the current directory or in any of its subdirectories, and (b) not in a location specified by the extensions mechanism.</p><p>If you are upgrading from an older version of the JDK, your startup settings may include <code>CLASSPATH</code> settings that are no longer needed. You should remove any settings that are not application-specific, such as <code>classes.zip</code>. Some third-party applications that use the Java Virtual Machine may modify your <code>CLASSPATH</code> environment variable to include the libaries they use. Such settings can remain.</p><p>You can change the class path by using the JDK tools' <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/classpath.html#tooloption">-classpath option</a> when you invoke the JVM or other JDK tools or by using the <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/classpath.html#env%20var"><code>CLASSPATH</code> environment variable</a>. Using the <code>-classpath</code> option is preferred over setting <code>CLASSPATH</code> environment variable because you can set it individually for each application without affecting other applications and without other applications modifying its value.</p><p>Classes can be stored either in directories (folders) or in archive files. The Java platform classes are stored in <code>rt.jar</code>. For more details on archives and information on how the class path works, see <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/classpath.html#Understanding">Understanding the class path and package names</a> near the end of this document.</p><dl><dd><b>Important Note:</b> Some older versions of the JDK sofware included a <code>&lt;</code><i>jdk-dir</i><code>&gt;/classes</code> entry in the default class path. That directory exists for use by the JDK software, and should <i>not</i> be used for application classes. Application classes should be placed in a directory outside of the JDK directory hierarcy. That way, installing a new JDK does not force you to reinstall application classes. For compatibility with older versions, applications that use the <code>&lt;</code><i>jdk-dir</i><code>&gt;/classes</code> directory as a class library will run in the current version, but there is no guarantee that they will run in future versions.</dd></dl></blockquote><h2><a id="tooloption" name="tooloption"></a><b>Using the JDK tools' -classpath option</b></h2><blockquote><p>The JDK tools <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/java.html">java</a>, <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/jdb.html">jdb</a>, <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/javac.html">javac</a>, and <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/javah.html">javah</a> have a <code><b>-classpath</b></code> option which replaces the path or paths specified by the <code>CLASSPATH</code> environment variable while the tool runs. This is the recommended option for changing class path settings, because each application can have the class path it needs without interfering with any other application.</p><p>The runtime tool <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/java.html">java</a> has a <code><b>-cp</b></code> option, as well. This option is an abbreviation for <code><b>-classpath</b></code>.</p><p>For very special cases, both <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/java.html">java</a> and <a href="file:///F:/Java/Documents/jdk-6-doc/technotes/tools/windows/javac.html">javac</a> have options that let you change the path they use to find their own class libraries. The vast majority of users will never to need to use those options, however.</p></blockquote><h2><a name="env_var"></a>Using the CLASSPATH environment variable</h2><blockquote><p>In general, you will want to use the <code>-classpath</code> command-line option, as explained in the previous section. This section shows you how to set the <code>CLASSPATH</code> environment variable if you want to do that, or clear settings left over from a previous installation.</p><h3><b>Setting CLASSPATH</b></h3><p>The <code>CLASSPATH</code> environment variable is modified with the <b>set</b> command. The format is:</p><blockquote><code><b>set CLASSPATH=</b></code><i>path1</i><code><b>;</b></code><i>path2</i> ... </blockquote><p>The paths should begin with the letter specifying the drive, for example, <code>C:\</code>. That way, the classes will still be found if you happen to switch to a different drive. (If the path entries start with backslash (<code>\</code>) and you are on drive <code>D:</code>, for example, then the classes will be expected on <code>D:</code>, rather than<code>C:</code>.)</p><h3><b>Clearing CLASSPATH</b></h3><p>If your <code>CLASSPATH</code> environment variable has been set to a value that is not correct, or if your startup file or script is setting an incorrect path, you can unset <code>CLASSPATH</code> by using:</p><blockquote><code>C:&gt; <b>set CLASSPATH=</b></code></blockquote><p>This command unsets <code>CLASSPATH</code> for the current command prompt window only. You should also delete or modify your startup settings to ensure that you have the right <code>CLASSPATH</code> settings in future sessions.</p><h3><b>Changing Startup Settings</b></h3>If the <code>CLASSPATH</code> variable is set at system startup, the place to look for it depends on your operating system: <table width="90%" summary="How to Check the System Startup CLASSPATH Variable Setting" border="0"><tbody><tr><th align="left">Operating System</th><th align="left">Method</th></tr><tr><td width="22%">Windows 95 and 98</td><td valign="top" width="78%">Examine autoexec.bat for the <b>set</b> command.</td></tr><tr><td valign="top" width="22%" height="44">Other (Windows NT, Windows 2000, ...)</td><td valign="top" width="78%" height="44">The <tt>CLASSPATH</tt> environment variable can be set using the System utility in the Control Panel.</td></tr></tbody></table></blockquote><h2>Understanding class path wildcards</h2><blockquote><p><font color="#ff0000">Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension <code>.jar</code> or <code>.JAR</code>. For example, the class path entry <code>foo/*</code> specifies all JAR files in the directory named <code>foo</code>. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.</font></p><p><font color="#ff0000">A class path entry that contains * will not match class files.</font> To match both classes and JAR files in a single directory <code>foo</code>, use either <code>foo;foo/*</code> or <code>foo/*;foo</code>. The order chosen determines whether the classes and resources in <code>foo</code> are loaded before JAR files in <code>foo</code>, or vice versa.</p><p>Subdirectories are not searched recursively. For example, <code>foo/*</code> looks for JAR files only in <code>foo</code>, not in <code>foo/bar</code>, <code>foo/baz</code>, etc.</p><p>The order in which the JAR files in a directory are enumerated in the expanded class path is not specified and may vary from platform to platform and even from moment to moment on the same machine. A well-constructed application should not depend upon any particular order. If a specific order is required then the JAR files can be enumerated explicitly in the class path.</p><p>Expansion of wildcards is done early, prior to the invocation of a program's <code>main</code> method, rather than late, during the class-loading process itself. Each element of the input class path containing a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory <code>foo</code> contains <code>a.jar</code>, <code>b.jar</code>, and <code>c.jar</code>, then the class path <code>foo/*</code> is expanded into <code>foo/a.jar;foo/b.jar;foo/c.jar</code>, and that string would be the value of the system property <code>java.class.path</code>.</p><p>The <code>CLASSPATH</code> environment variable is not treated any differently from the <code>-classpath</code> (or <code>-cp</code>) command-line option. That is, wildcards are honored in all these cases. However, class path wildcards are not honored in the <code>Class-Path</code> jar-manifest header.</p></blockquote><h2><a id="Understanding" name="Understanding"></a>Understanding the class path and package names</h2><blockquote><p>Java classes are organized into packages which are mapped to directories in the file system. But, unlike the file system, whenever you specify a package name, you specify the <i>whole</i> package name -- never part of it. For example, the package name for <code>java.awt.Button</code> is <i>always</i> specified as <code>java.awt</code>.</p><p>For example, suppose you want the Java runtime to find a class named <code>Cool.class</code> in the package <code>utility.myapp</code>. If the path to that directory is <code>C:\java\MyClasses\utility\myapp</code>, you would set the class path so that it contains <code>C:\java\MyClasses</code>.</p><p>To run that app, you could use the following JVM command:</p><p><code>C:&gt; <b>java -classpath C:\java\MyClasses utility.myapp.Cool</b></code></p><p>When the app runs, the JVM uses the class path settings to find any other classes defined in the <code>utility.myapp</code> package that are used by the <code>Cool</code> class.</p><p>Note that the entire package name is specified in the command. It is not possible, for example, to set the class path so it contains <code>C:\java\MyClasses\utility</code> and use the command <code>java myapp.Cool</code>. The class would not be found.</p><p>(You may be wondering what defines the package name for a class. The answer is that the package name is part of the class and cannot be modified, except by recompiling the class.)</p><blockquote><p><b>Note:</b> An interesting consequence of the package specification mechanism is that files which are part of the same package may actually exist in different directories. The package name will be the same for each class, but the path to each file may start from a different directory in the class path.</p></blockquote><h3>Folders and archive files</h3><p>When classes are stored in a directory (folder), like <code>c:\java\MyClasses\utility\myapp</code>, then the class path entry points to the directory that contains the first element of the package name. (in this case, <code>C:\java\MyClasses</code>, since the package name is <code>utility.myapp</code>.)</p><p>But when classes are stored in an archive file (a .zip or .jar file) the class path entry is the path to and including the .zip or .jar file. For example, to use a class library that is in a .jar file, the command would look something like this:</p><code>C:&gt; <b>java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool</b></code><h3>Multiple specifications</h3><p>To find class files in the directory <code>C:\java\MyClasses</code> as well as classes in <code>C:\java\OtherClasses</code>, you would set the class path to:</p><code>C:&gt; <b>java -classpath C:\java\MyClasses;C:\java\OtherClasses</b> ...</code><p>Note that the two paths are separated by a semicolon.</p><h3>Specification order</h3><p>The order in which you specify multiple class path entries is important. The Java interpreter will look for classes in the directories in the order they appear in the class path variable. In the example above, the Java interpreter will first look for a needed class in the directory <code>C:\java\MyClasses</code>. Only if it doesn't find a class with the proper name in that directory will the interpreter look in the <code>C:\java\OtherClasses</code> directory.</p></blockquote><hr noshade="" size="3" /><table width="100%" summary="layout" border="0"><tbody><tr valign="top"><td><p><font size="-2"><a href="file:///F:/Java/Documents/jdk-6-doc/legal/SMICopyright.html">Copyright</a> © 2004-2006 <a href="http://www.sun.com/">Sun Microsystems, Inc.</a> All Rights Reserved.</font></p></td><td align="right"><img height="30" alt="Sun" src="file:///F:/Java/Documents/jdk-6-doc/images/sunlogo64x30.gif" width="64" border="0" /><br /><font size="+1"><i>Java Software</i></font></td></tr></tbody></table><br /><br /><br /></pre><img src ="http://www.blogjava.net/honzeland/aggbug/96954.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/honzeland/" target="_blank">honzeland</a> 2007-01-31 14:32 <a href="http://www.blogjava.net/honzeland/articles/96954.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java/J2EE中文问题终极解决之道 </title><link>http://www.blogjava.net/honzeland/articles/82284.html</link><dc:creator>honzeland</dc:creator><author>honzeland</author><pubDate>Mon, 20 Nov 2006 07:31:00 GMT</pubDate><guid>http://www.blogjava.net/honzeland/articles/82284.html</guid><wfw:comment>http://www.blogjava.net/honzeland/comments/82284.html</wfw:comment><comments>http://www.blogjava.net/honzeland/articles/82284.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/honzeland/comments/commentRss/82284.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/honzeland/services/trackbacks/82284.html</trackback:ping><description><![CDATA[
		<h3 align="center">
				<a href="http://www.jdon.com/aboutme.htm">板桥里人</a> http://www.jdon.com 2005/06/29</h3>
		<p>　　Java中文问题一直困扰着很多初学者，如果了解了Java系统的中文问题原理，我们就可以对中文问题能够采取根本的解决之道。</p>
		<p>　　最古老的解决方案是使用String的字节码转换，这种方案问题是不方便，我们需要破坏对象封装性，进行字节码转换。</p>
		<p>　　还有一种方式是对J2EE容器进行编码设置，如果J2EE应用系统脱离该容器，则会发生乱码，而且指定容器配置不符合J2EE应用和容器分离的原则。</p>
		<p>　　在Java内部运算中，涉及到的所有字符串都会被转化为UTF-8编码来进行运算。那么，在被Java转化之前，字符串是什么样的字符集？ Java总是根据操作系统的默认编码字符集来决定字符串的初始编码，而且Java系统的输入和输出的都是采取操作系统的默认编码。</p>
		<p>　　因此，如果能统一Java系统的输入、输出和操作系统3者的编码字符集合，将能够使Java系统正确处理和显示汉字。这是处理Java系统汉字的一个原则，但是在实际项目中，能够正确抓住和控制住Java系统的输入和输出部分是比较难的。J2EE中，由于涉及到外部浏览器和数据库等，所以中文问题乱码显得非常突出。</p>
		<p>　　J2EE应用程序是运行在J2EE容器中。在这个系统中，输入途径有很多种：一种是通过页面表单打包成请求（request）发往服务器的；第二种是通过数据库读入；还有第3种输入比较复杂，JSP在第一次运行时总是被编译成Servlet，JSP中常常包含中文字符，那么编译使用javac时，Java将根据默认的操作系统编码作为初始编码。除非特别指定，如在Jbuilder/eclipse中可以指定默认的字符集。</p>
		<p>　　输出途径也有几种：第一种是JSP页面的输出。由于JSP页面已经被编译成Servlet，那么在输出时，也将根据操作系统的默认编码来选择输出编码，除非指定输出编码方式；还有输出途径是数据库，将字符串输出到数据库。</p>
		<p>　　由此看来，一个J2EE系统的输入输出是非常复杂，而且是动态变化的，而Java是跨平台运行的，在实际编译和运行中，都可能涉及到不同的操作系统，如果任由Java自由根据操作系统来决定输入输出的编码字符集，这将不可控制地出现乱码。</p>
		<p>　　正是由于Java的跨平台特性，使得字符集问题必须由具体系统来统一解决，所以在一个Java应用系统中，<strong>解决中文乱码的根本办法是明确指定整个应用系统统一字符集。</strong></p>
		<p>　　指定统一字符集时，到底是指定ISO8859_1 、GBK还是UTF-8呢？ </p>
		<p>　　（1）如统一指定为ISO8859_1，因为目前大多数软件都是西方人编制的，他们默认的字符集就是ISO8859_1，包括操作系统Linux和数据库MySQL等。这样，如果指定Jive统一编码为ISO8859_1，那么就有下面3个环节必须把握：</p>
		<p>　　开发和编译代码时指定字符集为ISO8859_1。</p>
		<p>　　运行操作系统的默认编码必须是ISO8859_1，如Linux。</p>
		<p>　　在JSP头部声明：&lt;%@ page contentType="text/html;charset=ISO8859_1" %&gt;。</p>
		<p>　　（2）如果统一指定为GBK中文字符集，上述3个环节同样需要做到，不同的是只能运行在默认编码为GBK的操作系统，如中文Windows。</p>
		<p>　　统一编码为ISO8859_1和GBK虽然带来编制代码的方便，但是各自只能在相应的操作系统上运行。但是也破坏了Java跨平台运行的优越性，只在一定范围内行得通。例如，为了使得GBK编码在linux上运行，设置Linux编码为GBK。</p>
		<p>　　那么有没有一种除了应用系统以外不需要进行任何附加设置的中文编码根本解决方案呢？</p>
		<p>　　将Java/J2EE系统的统一编码定义为UTF-8。UTF-8编码是一种兼容所有语言的编码方式，惟一比较麻烦的就是要找到应用系统的所有出入口，然后使用UTF-8去“结扎”它。</p>
		<p>　　一个J2EE应用系统需要做下列几步工作：</p>
		<ol>
				<li>开发和编译代码时指定字符集为UTF-8。JBuilder和Eclipse都可以在项目属性中设置。 
</li>
				<li>使用过滤器，如果所有请求都经过一个Servlet控制分配器，那么使用Servlet的filter执行语句，将所有来自浏览器的请求（request）转换为UTF-8，因为浏览器发过来的请求包根据浏览器所在的操作系统编码，可能是各种形式编码。关键一句：<br />request.setCharacterEncoding("UTF-8")。<br />网上有此filter的源码，<a href="http://sourceforge.net/projects/jdon/" target="_blank">Jdon框架源码</a>中com.jdon.util.SetCharacterEncodingFilter<br />需要配置web.xml 激活该Filter。 
</li>
				<li>在JSP头部声明：&lt;%@ page contentType="text/html;charset= UTF-8" %&gt;。 
</li>
				<li>在Jsp的html代码中，声明UTF-8:<br />&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; 
</li>
				<li>设定数据库连接方式是UTF-8。例如连接MYSQL时配置URL如下：<br />jdbc:mysql://localhost:3306/test?useUnicode=true&amp;amp;characterEncoding=UTF-8<br />注意，上述写法是JBoss的mysql-ds.xml写法，多亏网友提示，在tomcat中&amp;amp;要写成&amp;即可。一般其他数据库都可以通过管理设置设定UTF-8 
</li>
				<li>其他和外界交互时能够设定编码时就设定UTF-8，例如读取文件，操作XML等。 </li>
		</ol>　　　　 笔者以前在Jsp/Servlet时就采取这个原则，后来使用Struts、Tapestry、EJB、Hibernate、Jdon等框架时，从未被乱码困扰过，可以说适合各种架构。希望本方案供更多初学者分享，减少Java/J2EE的第一个拦路虎，也避免因为采取一些临时解决方案，导致中文问题一直出现在新的技术架构中。 <img src ="http://www.blogjava.net/honzeland/aggbug/82284.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/honzeland/" target="_blank">honzeland</a> 2006-11-20 15:31 <a href="http://www.blogjava.net/honzeland/articles/82284.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>String和StringBuffer之概览 </title><link>http://www.blogjava.net/honzeland/articles/80328.html</link><dc:creator>honzeland</dc:creator><author>honzeland</author><pubDate>Fri, 10 Nov 2006 02:44:00 GMT</pubDate><guid>http://www.blogjava.net/honzeland/articles/80328.html</guid><wfw:comment>http://www.blogjava.net/honzeland/comments/80328.html</wfw:comment><comments>http://www.blogjava.net/honzeland/articles/80328.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/honzeland/comments/commentRss/80328.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/honzeland/services/trackbacks/80328.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: String												和				StringBuffer												之概览																		　　非可变对象一旦创建之后就不能再被改变，可变对象则可以在创建之后被改变。				String												对象是非可变对象，				StringBuffer										...&nbsp;&nbsp;<a href='http://www.blogjava.net/honzeland/articles/80328.html'>阅读全文</a><img src ="http://www.blogjava.net/honzeland/aggbug/80328.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/honzeland/" target="_blank">honzeland</a> 2006-11-10 10:44 <a href="http://www.blogjava.net/honzeland/articles/80328.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>