To laugh often and much;
To win the respect of intelligent people and the affection of children;
To earn the appreciation of honest critics and endure the betrayal of false friends;
To appreciate beauty;
To find the best in others;
To leave the world a bit better, whether by a healthy child, a garden patch or a redeemed social condition;
To know even one life has breathed easier because you have lived;
This is to have succeeded.
知識(shí)在于積累和實(shí)踐,-正所謂"厚積薄發(fā)",我想應(yīng)該是這個(gè)道理吧!
舊的知識(shí)需要時(shí)刻溫習(xí),就像英語(yǔ),你不看,不接觸,遲早有一天會(huì)把它忘得干干凈凈
從今天開始,每天進(jìn)步一點(diǎn)點(diǎn),畢竟"學(xué)習(xí)"是一輩子的事情,馬虎不得!呵呵~~~
The furthest distance in the world
Is not between life and death
But when I stand in front of you
Yet you don’t know that
I love you
The furthest distance in the world
Is not when i stand in font of you
Yet you can’t see my love
But when undoubtedly knowing the love from both
Yet cannot
Be togehter
The furthest distance in the world
Is not being apart while being in love
But when plainly can not resist the yearning
Yet pretending
You have never been in my heart
The furthest distance in the world
Is not
But using one’s indifferent heart
To dig an uncrossable river
For the one who loves you
世界上最遙遠(yuǎn)的距離,不是生與死
而是我就站在你的面前,你卻不知道我愛(ài)你
世界上最遙遠(yuǎn)的距離,不是我站在你面前,你卻不知道我愛(ài)你
而是明明知道彼此相愛(ài),卻不能在一起
世界上最遙遠(yuǎn)的距離,不是明明知道彼此相愛(ài),卻不能在一起
而是明明無(wú)法抵擋這股想念,卻還得故意裝作絲毫沒(méi)有把你放在心里
世界上最遙遠(yuǎn)的距離,不是明明無(wú)法抵擋這股想念,卻還得故意裝作絲毫沒(méi)有把你放在心里,而是用自己冷漠的心對(duì)愛(ài)你的人掘了一條無(wú)法跨越的溝渠
1.Compliment three people every day.每天贊美三個(gè)人。
2.Watch a sunrise.看日出。
3.Be the first to say "hello".先向別人打招呼。
4.Live beneath your means.靠自己的力量生活。
5.Treat everyone as your want to be treated.像自己希望得到的善待一樣善待他人。
6.Never give up on anybody;Miracles happen.不要放棄任何人;奇跡總會(huì)發(fā)生。
7.Remember someone's name.記住別人的名字。
8 .Pray not for things,but for wisdom and courage.不要乞求得到什么東西,但可以乞求智慧和勇氣。
9.Be tough-minded,but tender hearted.意志要堅(jiān)強(qiáng),但心地要善良。
10.Be kinder than you have to be.仁慈,再仁慈一點(diǎn)。
11.Don't forget that a person's greatest emotional need is to feel appreciated.不
要忘記一個(gè)人最偉大的情感需要是得到別人的欣賞。
12.Keep your promises.履行你的諾言。
13.Show cheerfulness even when you don’t feel it.即使沒(méi)有快樂(lè)的感覺(jué),也要努力表現(xiàn)出來(lái)。
14.Remember that overnight success usually takes 15 years.切記所謂的“一夜成名”通常需要付出“15年的努力”。
15.Leave everything better than you found it.讓一切變的更加美好。
16.Remember that winners do what losers don't want to do.切記勝利者通常會(huì)做失敗者不想做的事情。
17.When you arrive at your job in the morning,let the first thing you say brighten everyone's day.早上到辦公室時(shí),先說(shuō)一件能讓每個(gè)人在一天中感到愉快的事。
18.Don't rain on other people's parades.看到別人的輝煌時(shí),不要抱怨。
19.Don't waste an opportunity to tell someone you love them.抓住一切機(jī)會(huì)對(duì)別人說(shuō)“我愛(ài)你”。
20.Keep some things to yourself and don't promote have by hurting people you love.自己承受一些事情,不要讓所愛(ài)的人受傷害。
為什么說(shuō)亂碼是中國(guó)程序員無(wú)法避免的話題呢?這個(gè)首先要從編碼機(jī)制上說(shuō)起,大家都是中文和英文的編碼格式不是一樣,解碼也是不一樣的!如果中國(guó)的程序員不會(huì)遇到亂碼,那么只有使用漢語(yǔ)編程。漢語(yǔ)編程是怎么回事我也不大清楚,應(yīng)該是前年吧,我一朋友給我介紹漢語(yǔ)編程,怎么不錯(cuò)不錯(cuò)?當(dāng)時(shí)因?yàn)閷W(xué)習(xí)忙沒(méi)去關(guān)注這個(gè),等我閑了,那個(gè)朋友不弄這個(gè),問(wèn)他他也不說(shuō)不大清楚,最后自己對(duì)這個(gè)學(xué)習(xí)也不了了之了。
今天我寫這個(gè)不是講解中英文之間的差距,解碼等,我是將我在這幾年工作遇到各種各樣的亂碼的解決方法,總結(jié)一樣,也希望大家能把自己暈倒解決亂碼的方法都說(shuō)出來(lái),咱們弄一個(gè)解決亂碼的“葵花寶典”。
對(duì)于Java由于默認(rèn)的編碼方式是 UNICODE,所以用中文也易出問(wèn)題,常見的解決是
String s2 = new String(s1.getBytes(“ISO-8859-1”),”GBK”);
1、utf8解決JSP中文亂碼問(wèn)題
一般說(shuō)來(lái)在每個(gè)頁(yè)面的開始處,加入:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
%>
charset=UTF-8 的作用是指定JSP向客戶端輸出的編碼方式為“UTF-8”
pageEncoding="UTF-8" 為了讓JSP引擎能正確地解碼含有中文字符的JSP頁(yè)面,這在LINUX中很有效
request.setCharacterEncoding("UTF-8"); 是對(duì)請(qǐng)求進(jìn)行了中文編碼
有時(shí),這樣仍不能解決問(wèn)題,還需要這樣處理一下:
String msg = request.getParameter("message");
String str=new String(msg.getBytes("ISO-8859-1"),"UTF-8");
out.println(st);
2、Tomcat 5.5 中文亂碼
只要把%TOMCAT安裝目錄%/ webapps\servlets-examples\WEB-INF\classes\filters\SetCharacterEncodingFilter.class文件拷到你的webapp目錄/filters下,如果沒(méi)有filters目錄,就創(chuàng)建一個(gè)。
2)在你的web.xml里加入如下幾行:
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3)完成.
2 get方式的解決辦法
1) 打開tomcat的server.xml文件,找到區(qū)塊,加入如下一行:
URIEncoding=”GBK”
完整的應(yīng)如下:
<Connector
port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true"
URIEncoding="GBK"
/>
2)重啟tomcat,一切OK。
3、xmlHttpRequest中文問(wèn)題
頁(yè)面jsp用的GBK編碼
<%@ page contentType="text/html; charset=GBK"%>
javascript部分
function addFracasReport() {
var url="controler?actionId=0_06_03_01&actionFlag=0010";
var urlmsg="&reportId="+fracasReport1.textReportId.value; //故障報(bào)告表編號(hào)
var xmlHttp=Common.createXMLHttpRequest();
xmlHttp.onreadystatechange = Common.getReadyStateHandler(xmlHttp, eval("turnAnalyPage"));
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader( " Content-Type " , " application/x-www-form-urlencoded);
xmlHttp.send(urlmsg);
}
后臺(tái)java中獲得的reportId是亂碼,不知道該怎么轉(zhuǎn),主要是不知道xmlHttp.send(urlmsg); 以后是什么編碼?在后面用java來(lái)轉(zhuǎn),試了幾種,都沒(méi)有成功,其中有:
public static String UTF_8ToGBK(String str) {
try {
return new String(str.getBytes("UTF-8"), "GBK");
} catch (Exception ex) {
return null;
}
}
public static String UTF8ToGBK(String str) {
try {
return new String(str.getBytes("UTF-16BE"), "GBK");
} catch (Exception ex) {
return null;
}
}
public static String GBK(String str) {
try {
return new String(str.getBytes("GBK"),"GBK");
} catch (Exception ex) {
return null;
}
}
public static String getStr(String str) {
try {
String temp_p = str;
String temp = new String(temp_p.getBytes("ISO8859_1"), "GBK");
temp = sqlStrchop(temp);
return temp;
} catch (Exception e) {
return null;
}
}
4、JDBC ODBC Bridge的Bug及其解決方法
在編寫一數(shù)據(jù)庫(kù)管理程序時(shí),發(fā)現(xiàn)JDBC-ODBC Bridge存在不易發(fā)現(xiàn)的Bug。在向數(shù)據(jù)表插入數(shù)據(jù)時(shí),如果為英文字符,存儲(chǔ)內(nèi)容完全正確,如果存入中文字符,部分?jǐn)?shù)據(jù)庫(kù)只能存儲(chǔ)前七八個(gè)中文字符,其他內(nèi)容被截去,導(dǎo)致存儲(chǔ)內(nèi)容的不完整(有些數(shù)據(jù)庫(kù)不存在這個(gè)問(wèn)題,如Sybase SQL Anywhere 5.0。JDBC-ODBC Bridge還存在無(wú)法建表的Bug)。
對(duì)于廣大需要存儲(chǔ)中文信息的Java程序員來(lái)說(shuō),這可是一個(gè)不好的消息。要么改用其他語(yǔ)言編程,要么選擇其他價(jià)格昂貴的數(shù)據(jù)庫(kù)產(chǎn)品。“一次編寫,到處運(yùn)行”的目標(biāo),也大打折扣。能不能采用變通的方法,將中文信息進(jìn)行處理后再存儲(chǔ)來(lái)解決這個(gè)問(wèn)題呢?答案是肯定的。
解決問(wèn)題的具體思路、方法
Java采用Unicode碼編碼方式,中英文字符均采用16bit存儲(chǔ)。既然存儲(chǔ)英文信息是正確的,根據(jù)一定規(guī)則,將中文信息轉(zhuǎn)換成英文信息后存儲(chǔ),自然不會(huì)出現(xiàn)截尾現(xiàn)象。讀取信息時(shí)再進(jìn)行逆向操作,將英文信息還原成中文信息即可。由GB2312編碼規(guī)則可知,漢字一般為二個(gè)高位為1的ASCII碼,在轉(zhuǎn)換時(shí)將一個(gè)漢字的二個(gè)高位1去掉,還原時(shí)再將二個(gè)高位1加上。為了處理含有英文字符的中文字串,對(duì)英文字符則需要加上一個(gè)Byte 0標(biāo)記。以下提供的兩個(gè)公用靜態(tài)方法,可加入任何一個(gè)類中使用。
將中英文字串轉(zhuǎn)換成純英文字串
public static String toTureAsciiStr(String str){
StringBuffer sb = new StringBuffer();
byte[] bt = str.getBytes();
for(int i =0 ; i〈bt.length; i++){
if(bt[i]〈0){
//是漢字去高位1
sb.append((char)(bt[i]&&0x7f));
}else{//是英文字符 補(bǔ)0作記錄
sb.append((char)0);
sb.append((char)bt[i]);
}
}
return sb.toString();
}
將經(jīng)轉(zhuǎn)換的字串還原
public static String unToTrueAsciiStr(String str){
byte[] bt = str.getBytes();
int i,l=0,length = bt.length,j=0;
for(i = 0; i〈length; i++){
if(bt[i] == 0){
l++;
}
}
byte []bt2 = new byte[length-l];
for(i =0 ; i〈length; i++){
if(bt[i] == 0){
i++;
bt2[j] = bt[i];
}else{
bt2[j] = (byte)(bt[i]|0x80);
}
j++;
}
String tt = new String(bt2);
return tt;
}
上例在實(shí)際編程中效果很好,只是存儲(chǔ)的中文信息需要經(jīng)過(guò)同樣處理,才能被其他系統(tǒng)使用。而且如果中文字串出現(xiàn)英文字符,實(shí)際上增加了額外的存儲(chǔ)空間。
5、Solaris下Servlet編程的中文問(wèn)題及解決辦法
在使用Java開發(fā)Internet上的一個(gè)應(yīng)用系統(tǒng)時(shí),發(fā)現(xiàn)在Windows下調(diào)試完全正常的Servlet,上傳到Solaris 服務(wù)器上,運(yùn)行卻出現(xiàn)故障——返回的網(wǎng)頁(yè)不能顯示中文,應(yīng)為中文的信息全為亂碼;用中文信息做關(guān)鍵字,不能正確檢索數(shù)據(jù)庫(kù)。后來(lái)采用加入檢查代碼等方法探知故障原因如下:
顯示亂碼主要是因?yàn)橥ㄟ^(guò)類 HttpServletResponse提供的方法setContentType 無(wú)法改變返回給客戶的數(shù)據(jù)的編碼方式,正確的編碼方式應(yīng)為GB2312或者GBK,而事實(shí)上為缺省的ISO8859-1。無(wú)法檢索中文信息則是因?yàn)椋蛻籼峤坏闹形男畔⒔?jīng)瀏覽器編碼到達(dá)服務(wù)器后,Servlet無(wú)法將其正確解碼。
舉例說(shuō)明顯示亂碼解決方法
Servlet 一般通常做法如下:
public class ZldTestServlet extends HttpServlet {
public void doGet (HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
//在使用 Writer向?yàn)g覽器返回?cái)?shù)據(jù)前,設(shè)置 content-type header ,在這里設(shè)置相應(yīng)的字符集gb2312
response.setContentType("text/html; charset=gb2312");
PrintWriter out = response.getWriter(); //*
// 正式返回?cái)?shù)據(jù)
out.println("〈html〉〈head〉〈title〉Servlet test〈/title〉〈/head〉" );
out.println("這是一個(gè)測(cè)試頁(yè)!");
out.println("〈/body〉〈/html〉");
out.close();
}
...
}
解決頁(yè)面顯示亂碼問(wèn)題,需將*處代碼換成如下內(nèi)容:
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(),"gb2312"));
Solaris中文信息檢索問(wèn)題的解決
瀏覽器利用表單向服務(wù)器提交信息時(shí),一般采用x-www-form-urlencoded 的MIME格式對(duì)數(shù)據(jù)進(jìn)行編碼。如果使用get方法,參數(shù)名稱和參數(shù)值經(jīng)編碼后附加在URL后,在Java中稱作查詢串(query string)。
在Servlet程序中,如果采用ServletRequest的方法getParameter取得參數(shù)值,在Solaris環(huán)境下,對(duì)漢字卻不能正確解碼。因而無(wú)法正確檢索數(shù)據(jù)庫(kù)。
在Java 1.2的包——java.net中提供了URLEncode和URLDecode類。類URLEncode提供了按x-www-form-urlencoded格式對(duì)給定串進(jìn)行轉(zhuǎn)換的方法。類URLEncode則提供了逆方法。
6、Common Mail亂碼問(wèn)題
common mail是一個(gè)小而方便的mail包,他實(shí)現(xiàn)了對(duì)Java Mail的封裝,使用起來(lái)十分的方便,但是我在使用他的時(shí)候發(fā)現(xiàn),使用純文本的內(nèi)容發(fā)送,結(jié)果是亂碼,代碼如下:
public class TestCommonMail {
public static void main(String[] args) throws EmailException, MessagingException {
SimpleEmail email = new SimpleEmail();
email.setCharset("GB2312");
email.setHostName("smtp.163.com");
email.setSubject("test");
email.addTo("test@163.com");
email.setFrom("test@163.com");
email.setMsg("我的測(cè)試");
email.setAuthentication("test", "test");
email.send();
}
}
分析了一下commons mail的源碼找到了原因。源碼如下:
public class SimpleEmail extends Email
{
public Email setMsg(String msg) throws EmailException, MessagingException
{
if (EmailUtils.isEmpty(msg))
{
throw new EmailException("Invalid message supplied");
}
setContent(msg, TEXT_PLAIN);
return this;
}
}
Email代碼片段
public void setContent(Object aObject, String aContentType)
{
this.content = aObject;
if (EmailUtils.isEmpty(aContentType))
{
this.contentType = null;
}
else
{
// set the content type
this.contentType = aContentType;
// set the charset if the input was properly formed
String strMarker = "; charset=";
int charsetPos = aContentType.toLowerCase().indexOf(strMarker);
if (charsetPos != -1)
{
// find the next space (after the marker)
charsetPos += strMarker.length();
int intCharsetEnd =
aContentType.toLowerCase().indexOf(" ", charsetPos);
if (intCharsetEnd != -1)
{
this.charset =
aContentType.substring(charsetPos, intCharsetEnd);
}
else
{
this.charset = aContentType.substring(charsetPos);
}
}
}
}
email.send(); 的send方法將調(diào)用
public void buildMimeMessage() throws EmailException
{
try
{
this.getMailSession();
this.message = new MimeMessage(this.session);
if (EmailUtils.isNotEmpty(this.subject))
{
if (EmailUtils.isNotEmpty(this.charset))
{
this.message.setSubject(this.subject, this.charset);
}
else
{
this.message.setSubject(this.subject);
}
}
// ========================================================
// Start of replacement code
if (this.content != null)
{
this.message.setContent(this.content, this.contentType);
}
// end of replacement code
// ========================================================
else if (this.emailBody != null)
{
this.message.setContent(this.emailBody);
}
else
{
this.message.setContent("", Email.TEXT_PLAIN);
}
if (this.fromAddress != null)
{
this.message.setFrom(this.fromAddress);
}
else
{
throw new EmailException("Sender address required");
}
if (this.toList.size() + this.ccList.size() + this.bccList.size() == 0)
{
throw new EmailException(
"At least one receiver address required");
}
if (this.toList.size() > 0)
{
this.message.setRecipients(
Message.RecipientType.TO,
this.toInternetAddressArray(this.toList));
}
if (this.ccList.size() > 0)
{
this.message.setRecipients(
Message.RecipientType.CC,
this.toInternetAddressArray(this.ccList));
}
if (this.bccList.size() > 0)
{
this.message.setRecipients(
Message.RecipientType.BCC,
this.toInternetAddressArray(this.bccList));
}
if (this.replyList.size() > 0)
{
this.message.setReplyTo(
this.toInternetAddressArray(this.replyList));
}
if (this.headers.size() > 0)
{
Iterator iterHeaderKeys = this.headers.keySet().iterator();
while (iterHeaderKeys.hasNext())
{
String name = (String) iterHeaderKeys.next();
String value = (String) headers.get(name);
this.message.addHeader(name, value);
}
}
if (this.message.getSentDate() == null)
{
this.message.setSentDate(getSentDate());
}
if (this.popBeforeSmtp)
{
Store store = session.getStore("pop3");
store.connect(this.popHost, this.popUsername, this.popPassword);
}
}
catch (MessagingException me)
{
throw new EmailException(me);
}
}
由代碼可以知道純文本方式最終調(diào)用了Java Mail的
message.setContent(this.content, this.contentType);
content是內(nèi)容
contentType是類型,如text/plain,
(我們可以試試直接用Java mail發(fā)郵件,設(shè)置文本內(nèi)容不使用setText方法,也使用setContent("測(cè)試", "text/plain")方式,你可以看到內(nèi)容也是亂碼)
關(guān)鍵就在于text/plain,我們改成text/plain; charset=gb2312,ok亂碼解決了。在commons mail我們看SimpleEmail 類中setMsg方法調(diào)用的就是 setContent(msg, TEXT_PLAIN); 我們只需要將Email類中的常量TEXT_PLAIN修改一下加入 charset=你的字符集 ,重新打包jar,這樣就可以了
7、toad的字符集的設(shè)置與oracle的安裝
oracle數(shù)據(jù)庫(kù)服務(wù)器的安裝一般是中文字符集,有時(shí)安裝在不同的平臺(tái)下,設(shè)置為ISO編碼,toad是oracle開發(fā)的最好工具,不是我說(shuō)的,可是中文環(huán)境下安裝的toad,打開英文字符的oracle時(shí),中文全是亂碼。必須進(jìn)行設(shè)置
環(huán)境變量---〉系統(tǒng)變量
加
NLS_lANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK
或
NLS_lANG=AMERICAN_AMERICA.WE8ISO8859P1
AMERICAN_AMERICA.WE8MSWIN1252
或者
打開注冊(cè)表,點(diǎn)擊HKEY_LOCAL_MATHINE
再點(diǎn)擊Software,再點(diǎn)擊ORACLE
在點(diǎn)擊HOME(ORACLE所在目錄)
在注冊(cè)表的右半面有NLS_LANG,
雙擊它,將你想要的覆蓋掉原來(lái)的就可以了
最好記下舊的,以便可以改回來(lái)。
connect sys/chang_on_install
update props$
set value$='ZHS16CGB231280'
where name='NLS_CHARACTERSET';
commit;
這樣就OK了
8、如何解決GWT(google web toolkit)中文的問(wèn)題
GWT 中文亂碼解決方法
1.把你要顯示的中文“測(cè)試字符串”輸入到一個(gè)文件,如:1.txt
2.進(jìn)入命令行,進(jìn)入1.txt所在的目錄,敲入以下命令:native2ascii.exe 1.txt 2.txt 回車。這樣就生成了另外一個(gè)文件2.txt。
3.2.txt的內(nèi)容如下:\u6d4b\u8bd5\u5b57\u7b26\u4e32
4.然后用上面的編碼,在gwt中使用,就可以了.
9、xmlHttp得到的網(wǎng)頁(yè)怎么是亂碼?
(1)在服務(wù)器端使用WebRequest而不是xmlHttp
(2) 將
StreamReader sr = new StreamReader(stream);
對(duì)于簡(jiǎn)體中文改成:
StreamReader sr = new StreamReader(stream , Encoding.Default );
對(duì)于utf-8改成:
StreamReader sr = new StreamReader(stream , Encoding.UTF8 );
當(dāng)然,Encoding枚舉還有很多其他的成員,對(duì)于不同的編碼content-type可以有選擇的應(yīng)用
(3)后來(lái)我發(fā)現(xiàn)無(wú)論是content-type是gb2312還是utf-8,用
StreamReader sr = new StreamReader(stream , Encoding.Default );
都可以返回正常的漢字,所以統(tǒng)一的改成Encoding.Default
--------------------------------------------------------------------------------
最后,在服務(wù)器端從一個(gè)url獲得網(wǎng)頁(yè)的源代碼的代碼如下:
/// <summary>
/// post一個(gè)指定的url,獲得網(wǎng)頁(yè)的源代碼(用WebRequest實(shí)現(xiàn))
/// </summary>
/// <param name="url"></param>
/// <returns>
/// 如果請(qǐng)求失敗,返回null
/// 如果請(qǐng)求成功,返回網(wǎng)頁(yè)的源代碼
/// </returns>
public static string GetContentFromUrl2( string url )
{
//變量定義
string respstr;
WebRequest myWebRequest=WebRequest.Create(url);
// myWebRequest.PreAuthenticate=true;
// NetworkCredential networkCredential=new NetworkCredential( username , password , domain );
// myWebRequest.Credentials=networkCredential;
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse=myWebRequest.GetResponse();
System.IO.Stream stream = myWebResponse.GetResponseStream();
StreamReader sr = new StreamReader(stream , Encoding.Default );
//以字符串形式讀取數(shù)據(jù)流
respstr = sr.ReadToEnd();
sr.Close();
return respstr;
}
來(lái)源:soddabao-BlogJava
前言
ant是java開發(fā)者工具箱的重要一環(huán),junit,xdoclet等都與它緊密關(guān)聯(lián),程序員可能習(xí)慣了IDE提供的自動(dòng)構(gòu)建,甚至部署的功能,從而忽略了ant本身,其實(shí),主流的IDE通常是內(nèi)置ant任務(wù)來(lái)完成這些工作的,熟悉ant內(nèi)在的機(jī)理,可以閱讀或簡(jiǎn)單修改build.xml無(wú)疑可以幫助你更靈活地集成、管理應(yīng)用項(xiàng)目,如果需要學(xué)習(xí)maven這種開源項(xiàng)目管理解決方案,也是要以理解ant為基礎(chǔ)的喲。另外,使用ant的過(guò)程實(shí)際上對(duì)構(gòu)建進(jìn)行了文檔化,它是無(wú)關(guān)于IDE的,想象一下,你的同事中可能三分之一在用JbuilderX,三分之一用eclipse,還有一些是別的。
本人使用eclipse3.0.1,以前的構(gòu)建和發(fā)布工作都由myeclipse插件作了,趁周末實(shí)踐了一下手動(dòng)構(gòu)建,記此備忘。
實(shí)踐
準(zhǔn)備工作:這是我的個(gè)人習(xí)慣,把所有公用的類庫(kù)jar置于一個(gè)固定目錄,分好類,不要丟在一個(gè)文件夾下,如jakarta-commons、hibernate、spring、struts等,這些是源碼構(gòu)建時(shí)需要用到的,在部署時(shí)可能有一些不用再打進(jìn)去了,比如servlet.jar。如果你們有自己的framework,也一并放在這里。然后,打開eclipse,進(jìn)入Windows->Preferences->Java->User Libraries,增加一個(gè)自己的庫(kù),比如說(shuō)mylib,把剛才那些公共的jar全部添入,這樣有個(gè)好處,在eclipse項(xiàng)目中,不用再看到煩人的長(zhǎng)長(zhǎng)的jar列表了,比較整潔。
下來(lái)正式進(jìn)行:
1.新建一個(gè)Java Project,此時(shí)就不要再選你的j2ee插件內(nèi)置的一些選項(xiàng)了,至簡(jiǎn)即可。
2.在root下建幾個(gè)文件夾,我們?cè)诰W(wǎng)上下載的開源項(xiàng)目中經(jīng)常可以看到這些,比如:
src - 源碼
classes - 編譯
web - jsp等
lib - 庫(kù),這里可以簡(jiǎn)單地把mylib下的東東copy過(guò)來(lái),便于將來(lái)發(fā)布源碼。
dlist - 輸出的jar或war
當(dāng)然,我們要建一個(gè)build.xml,eclipse中會(huì)出現(xiàn)一個(gè)螞蟻的小圖標(biāo),一般這個(gè)文件建立后,下一個(gè)項(xiàng)目簡(jiǎn)單的copy過(guò)去,稍加改動(dòng)就可以了。
3.打開項(xiàng)目的屬性頁(yè),在Java Build Path的庫(kù)選項(xiàng)中,加入我們自定義的公共庫(kù)mylib.至于Builders方式就不用改了,使用默認(rèn)的Java Builer即可,我只是項(xiàng)目部署時(shí)使用ant,平常的排錯(cuò)工作就交給IDE吧。
4.重中之重,寫你的build.xml,網(wǎng)上文章很海,我這里就不再?嗦了,基本上就分那幾個(gè)任務(wù):
4.1 先要聲明一些路徑變量,如
<property name="war.dir" value="dlist" />
也可以將其寫至properties文件中,在這里引用;
4.2 聲明編譯的類路徑,如下:
<path id="master-classpath">
<fileset dir="${lib.root}/struts">
<include name="struts-menu-2.3.jar" />
<include name="struts.jar" />
</fileset>
<fileset dir="${lib.root}/jakarta-commons">
<include name="commons-*.jar" />
</fileset>
<fileset dir="${lib.root}/ibatis2.0.9">
<include name="ibatis-*.jar" />
</fileset>
<fileset dir="${lib.root}/jdbcdriver">
<include name="jtds-0.9-rc2.jar" />
</fileset>s
......
</path>
4.3 清空輸出目錄,如web,dlist等。
4.4 編譯構(gòu)建:
<target name="build" description="Compile main source tree java files into class files, generate jar files">
<mkdir dir="${build.dir}" />
<javac destdir="${build.dir}" source="1.3" target="1.3" debug="true" deprecation="false" optimize="false" failonerror="true">
<src path="${src.dir}" />
<classpath refid="master-classpath" />
</javac>
<copy todir="${build.dir}" preservelastmodified="true">
<fileset dir="${src.dir}">
<include name="**/*.xml" />
<include name="**/*.properties" />
</fileset>
</copy>
<!-- ============================================= -->
<!-- 據(jù)測(cè)試,資源文件不能被打到j(luò)ar文件中,其余均可 -->
<!-- ============================================= -->
<copy todir="${webclasses.dir}/conf" preservelastmodified="true">
<fileset dir="${src.dir}/conf">
<include name="springResources*.properties" />
</fileset>
</copy>
<mkdir dir="${weblib.dir}" />
<jar jarfile="${weblib.dir}/${name}.jar" compress="true">
<fileset dir="${build.dir}">
<include name="**" />
</fileset>
</jar>
<copy todir="${weblib.dir}" preservelastmodified="true">
<fileset dir="${lib.root}">
<include name="log4j-1.2.8.jar" />
</fileset>
<fileset dir="${lib.root}/struts">
<include name="struts-menu-2.3.jar" />
<include name="struts.jar" />
</fileset>
<fileset dir="${lib.root}/jakarta-commons">
<include name="commons-*.jar" />
</fileset>
<fileset dir="${lib.root}/spring-1.1.3">
<include name="spring.jar" />
<include name="aopalliance.jar" />
</fileset>
......
</copy>
</target>
<!-- ============================================= -->
<!-- Compile main Java sources and copy libraries -->
<!-- ============================================= -->
<target name="warfile" description="Build the web application archive">
<mkdir dir="${dist.dir}" />
<war warfile="${dist.dir}/${name}.war" basedir="${war.dir}" webxml="${war.dir}/WEB-INF/web.xml">
<include name="*" />
<include name="WEB-INF/*.*" />
<exclude name="WEB-INF/web.xml" />
<include name="WEB-INF/classes/*.*" />
<include name="WEB-INF/lib/**" />
<exclude name="**/.*" />
</war>
</target>
4.5 打成war
<target name="warfile" description="Build the web application archive">
<mkdir dir="${dist.dir}" />
<war warfile="${dist.dir}/${name}.war" basedir="${war.dir}" webxml="${war.dir}/WEB-INF/web.xml">
<include name="*" />
<include name="WEB-INF/*.*" />
<exclude name="WEB-INF/web.xml" />
<include name="WEB-INF/classes/*.*" />
<include name="WEB-INF/lib/**" />
<exclude name="**/.*" />
</war>
</target>
4.6 把幾個(gè)任務(wù)串起來(lái),弄一個(gè)default target
<target name="all">
<antcall target="clean" />
<antcall target="build" />
<antcall target="warfile" />
</target>
打完收功。在實(shí)踐中發(fā)現(xiàn),一些配置文件,如struts-config.xml ibatis和spring的xml都可以打進(jìn)jar文件,spring資源文件好象不行,得單獨(dú)copy至WEB-INFclasses下,另外,你的web文件夾下,事先得放好web.xml,以及一些tld文件喲!