內容 |
|
廠商幫忙安裝好的Solaris 9,預設只能使用/etc/hosts內的設定去找到主機名稱對應的IP,如果要一一設定一些常用的網站的IP,將是個大工程跟苦差事,最簡單的方法還是使用DNS來解析主機名稱,方法很簡單,先自己產生/etc/resolv.conf,再將/etc/nsswitch.conf改為使用dns來解析hosts。
cd /etc
vi resolv.conf
nameserver 168.95.1.1
nameserver 168.95.192.1
cp nsswitch.dns nsswitch.conf
注意:順序很重要!我就遇到先執行cp nsswitch.dns nsswitch.conf再vi resolv.conf而無法正常運作的狀況。
如果遇到上述的問題,可以執行下列的動作還原回來:
rm -rf /etc/resolv.conf
cp /etc/nsswitch.files /etc/nsswitch.conf
|
 |
|
JSPWiki是一個開放原始碼的wiki engine,目前採用 LGPL授權,未來將會轉移到 Apache去,使用Java語言(JSP+Servlet)開發,wiki的精神就是每個人都可以編輯,所以滿適合用於公司內團隊的協同作業上,例如產生軟體開發專案相關的說明文件或是系統安裝、設定、操作的說明文件等,讓小組成員隨時參考。
安裝起來也滿方便的,首先我們先 下載目前stable的2.6.3版,並將其解壓縮後,放到 Tomcat的webapps目錄下,在我的環境上是symbolic link到使用者家目錄下的www目錄。
cd ~/download
wget http://www.ecyrd.com/~jalkanen/JSPWiki/2.6.3/JSPWiki-2.6.3-bin.zip
rm -rf JSPWiki
unzip JSPWiki-2.6.3-bin.zip
cd JSPWiki
mkdir ~/www/wiki
unzip JSPWiki.war -d ~/www/wiki/
mkdir ~/www/data/wikidata
unzip JSPWiki-corepages.zip -d ~/www/data/wikidata
sed -i -e "s/\/p\/web\/www-data\/jspwiki/\/home\/andowson\/www\/data\/wikidata/g" \
-e "s/\/tmp\/jspwiki.log/logs\/jspwiki.log/g" ~/www/wiki/WEB-INF/jspwiki.properties
sudo chmod 664 ~/www/wiki/WEB-INF/jspwiki.properties
sudo chgrp tomcat ~/www/wiki/WEB-INF/jspwiki.properties
sudo chmod 775 ~/www/data/wikidata
sudo chmod 664 ~/www/data/wikidata/*.txt
sudo chgrp -R tomcat ~/www/data/wikidata
接著修改/etc/httpd/conf.d/mod_jk.conf:
JkMount /wiki/* loadbalancer
重新啟動Apache和Tomcat,載入JSPWiki,
利用http://<myhost>/wiki/Install.jsp設定並產生admin的帳號及密碼(亂數產生),請登入後先修改密碼。
再來就可以參考網站上的文件進行編輯了。
|
 |
|
|
 |
|
http://www.opennet.ru/soft/ora_inst/
依 Oracle安裝說明文件:
Apply patch no. 3006854. You can download this patch from OracleMetaLink ( http://metalink.oracle.com). This patch creates the /etc/libcwait.so file and appends the following line to the /etc/ld.so.preload file:
/etc/libcwait.so
如果沒裝的話,執行runInstaller將會遇到類似下面的錯誤訊息:
Error occurred during initialization of VM
Unable to load native library: /tmp/OraInstall2008-01-10_10-23-48PM/jre/lib/i386/libjava.so: symbol __libc_wait, version GLIBC_2.0 not defined in file libc.so.6 with link time reference
安裝完成之後就可以成功執行Oracle Universal Installer了
資料來源:
http://www.itpub.net/viewthread.php?tid=386263
http://www.puschitz.com/InstallingOracle9i.shtml#RunningOracleInstallationOnRHELAS3
|
 |
|
有網友發現JForum 2.1.8版templates/default下的兩個htm檔案內含入(include)的檔名拼錯了,這兩個檔案是pm_review_message.htm和topic_review.htm,原來寫成:
<#include "highligther_js.htm"/>
正確的寫法應該是
<#include "highlighter_js.htm"/>
差別在哪裡不知道您發現了嗎?對了就是th和ht的順序錯了。
參考資料:
http://www.jforum.net/posts/list/4275.page
|
 |
|
The original post only supports URL in the form "www.youtube.com". However, if you change to another form, like "youtube.com" or "tw.youtube.com", it will not work. So, we need to modify the original bb_config.xml as follows:
<!-- YouTube -->
<match name="youtube">
<regex>
(?i)\[youtube\]http\:\/\/(.*?)youtube.com\/watch\?v\=(.*?)\[/youtube\]
</regex>
<replace>
<![CDATA[
<object width="450" height="370">
<param name="movie" value="http://$1youtube.com/v/$2"></param>
<param name="wmode" value="transparent"></param>
<embed src="http://$1youtube.com/v/$2" type="application/x-shockwave-flash" wmode="transparent" width="450" height="370"></embed>
</object>
]]>
</replace>
</match>
Now, the new form of URL works.
See:
http://www.jforum.net/posts/list/4269.page
|
 |
|
大家好,今天是網站成立滿一年的日子,2007年的元旦假期讓我有時間把網站架起來,從2007年1月的月流量182名訪客成長到2007年12月的月流量4608名訪客,可以說每日的訪客數都大於第一個月整個月加起來的訪客數了。
去年的成果大致如下:
註冊會員數:423名
select count(*) from jforum_users where user_regdate < to_date('2008-01-01', 'yyyy-mm-dd')
已啟用帳號數:300人
select count(*) from jforum_users where user_active = 1 and user_regdate < to_date('2008-01-01', 'yyyy-mm-dd')
啟用率約為七成(300/423)
有發表文章人數:17人
select count(*) from jforum_users where user_regdate < to_date('2008-01-01', 'yyyy-mm-dd') and user_posts > 0
發文率約為5.67%(17/300)
發表文章數:222篇
select count(*) from jforum_posts where post_time < to_date('2008-01-01', 'yyyy-mm-dd')
今年的展望:
1.會員數成長到1000人,啟用率八成
2.發表文章數成長到500篇,發文率8%
希望大家多多發表自己練功的成果喔!
|
 |
|
最近找到了 JTrac這個用Java寫的問題追蹤軟體, License是Apache License,使用的框架是 Spring+ Hibernate+ Wicket,由於使用Hibernate所以理論上應該適用於所有Hibernate支援的資料庫,包括 HSQLDB, MySQL, PostgreSQL等。
簡易安裝:
先安裝好 JRE (Java Runtime Environment) 5.0 以上,然後直接由網站上 下載編譯好的binary zip檔,解開後點start.bat即可以開始執行。JTrac的這個zip檔內附了 Jetty這個Servlet Container及HSQLDB,如果您安裝的電腦上有安裝 Skype的話,需要先停用Skype,因為Skype會佔用port 80。另外,原來的軟體還沒有正體中文介面,我花了一個晚上翻譯了一下,可由附加檔案下載,放置於jtrac/WEB-INF/classes目錄下。
正式安裝:
我的環境是Linux,資料庫是PostgreSQL,網頁伺服器及應用伺服器是 Apache+ Tomcat,照網站上的 安裝說明,先把jtrac.war上傳到webapps目錄下,Tomcat會自動解開,產生一個jtrac目錄,這時再建立一個jtrac.home代表的目錄,為增加安全性,我們把它建在jtrac的WEB-INF下:
mkdir /home/andowson/www/jtrac/WEB-INF/data
chmod 775 /home/andowson/www/jtrac/WEB-INF/data
chown -R tomcat:tomcat /home/andowson/www/jtrac
接著編輯jtrac/WEB-INF/classes/jtrac-init.properties檔案,將剛剛的jtrac.home設定填上去:
jtrac.home=/home/andowson/www/jtrac/WEB-INF/data
這時可以先啟動一次jtrac以產生jtrac/WEB-INF/data/jtrac.properties這個資料庫連線設定檔(用的是HSQLDB),再修改成PostgreSQL或者乾脆自己產生一個,內容如下:
database.driver=org.postgresql.Driver
database.url=jdbc:postgresql://localhost:5432/jtrac
database.username=jtrac
database.password=jtrac
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=false
如果PostgreSQL的JDBC Driver不是放在Tomcat common/lib下的話,或者想要單獨給jtrac使用自己的jar檔,可以下載PostgreSQL的JDBC Driver到jtrac/WEB-INF/lib下
cd jtrac/WEB-INF/lib
wget http://jdbc.postgresql.org/download/postgresql-8.2-507.jdbc3.jar
然後建立一個新的PostgreSQL使用者jtrac和資料庫jtrac(參考 http://www.andowson.com/posts/list/190.page)
本來到這裡就可以啟動jtrac了,但是我實際上發現會有這個問題:
ERROR [org.hibernate.util.JDBCExceptionReporter] - ERROR: operator does not exist: integer = boolean
可透過修改jtrac/WEB-INF/classes/jtrac.hbm.xml將sql-type由integer改為boolean
最後記得修改/etc/httpd/conf.d/mod_jk.conf加上:
JkMount /jtrac/* loadbalancer
重新啟動Apache和Tomcat
使用說明:
存取 http://localhost/jtrac或http://your.server.name/jtrac
預設帳號跟密碼是admin和admin
登入後點選項即可開始新開專案空間和使用者,以及狀態轉換的工作流程,另外可以設定郵件主機以便發送通知。接著就可以新增Issue(Ticket)了。
|
 |
|
mohawk wrote:2.1.8版本找不到 template.dir
若自行加上 會出錯
安裝完成後的jforum-custom.conf是沒有template.dir這個參數沒錯, 但是在SystemGlobals.properties內是有的,它的值預設是default,我們可以自己手動加到jforum-custom.conf去, 這樣就可以覆蓋掉SystemGlobals.properties內的設定了(因JForum是先載入SystemGlobals.properties的參數值, 再載入jforum-custom.conf的參數值)
原先的檔案是針對JForum v2.1.7修改出來的, 當時花了不少時間去慢慢調整, 如果時間夠應該也可以對v2.1.8做更好的調整, 以下是我簡單的升級步驟, 供您參考
#下載JForum
cd /home/30elite
wget http://www.jforum.net/releases/jforum-2.1.8.zip
#解壓縮
unzip jforum-2.1.8.zip
#備份資料庫
su - postgres
pg_dump elite > /tmp/elite.bak
#更新schema
psql elite elite -f /home/30elite/jforum-2.1.8/upgrade/2.1.8/postgresql_2.1.7_to_2.1.8.sql
exit
#複製現有風格檔過去
cp -rfp /home/30elite/jforum-2.1.8/templates/default /home/30elite/jforum-2.1.8/templates/tp101
cp -p /home/30elite/www/templates/tp101/images/form_shadow.gif /home/30elite/jforum-2.1.8/templates/tp101/images/.
cp -p /home/30elite/www/templates/tp101/images/header.jpg /home/30elite/jforum-2.1.8/templates/tp101/images/.
cp -p /home/30elite/www/templates/tp101/images/header.swf /home/30elite/jforum-2.1.8/templates/tp101/images/.
cp -p /home/30elite/www/templates/tp101/images/member*.gif /home/30elite/jforum-2.1.8/templates/tp101/images/.
cp -p /home/30elite/www/templates/tp101/images/menu*.gif /home/30elite/jforum-2.1.8/templates/tp101/images/.
cp -p /home/30elite/www/templates/tp101/images/shadow*.gif /home/30elite/jforum-2.1.8/templates/tp101/images/.
cp -p /home/30elite/www/templates/tp101/images/top.jpg /home/30elite/jforum-2.1.8/templates/tp101/images/.
cp -p /home/30elite/www/templates/tp101/images/top2.jpg /home/30elite/jforum-2.1.8/templates/tp101/images/.
cp -p /home/30elite/www/templates/tp101/images/top_bg.jpg /home/30elite/jforum-2.1.8/templates/tp101/images/.
cp -p /home/30elite/www/templates/tp101/js/swfobject.js /home/30elite/jforum-2.1.8/templates/tp101/js/.
cp -rfp /home/30elite/www/templates/tp101/styles/style.css /home/30elite/jforum-2.1.8/templates/tp101/styles/.
cp -rfp /home/30elite/www/templates/tp101/header.htm /home/30elite/jforum-2.1.8/templates/tp101/header.htm
cp -rfp /home/30elite/www/templates/tp101/bottom.htm /home/30elite/jforum-2.1.8/templates/tp101/bottom.htm
#複製現有設定過去
cp -rfp /home/30elite/www/WEB-INF/config/jforum-custom.conf /home/30elite/jforum-2.1.8/WEB-INF/config/.
cp -rfp /home/30elite/www/upload/* /home/30elite/jforum-2.1.8/upload
cp -rfp /home/30elite/www/images/avatar/* /home/30elite/jforum-2.1.8/images/avatar
#更改權限為可寫入
chmod 775 /home/30elite/jforum-2.1.8/tmp
chmod -R 775 /home/30elite/jforum-2.1.8/upload
chmod -R 775 /home/30elite/jforum-2.1.8/images
chmod 775 /home/30elite/jforum-2.1.8/WEB-INF
chown -R 30elite:tomcat /home/30elite/jforum-2.1.8
#變更目錄名稱
mv /home/30elite/www /home/30elite/oldwww
mv /home/30elite/jforum-2.1.8 /home/30elite/www
#修改/home/30elite/www/WEB-INF/config/modulesMapping.properties ,將install改為註解或刪除
#install = net.jforum.view.install.InstallAction
#修改 /home/30elite/www/templates/tp101/header.htm,將v2.1.7版的<title>標籤上方換為v2.1.8版的templates/default/header.htm的<title>標籤上方程式碼
<#setting number_format = "#"/>
<#setting datetime_format = dateTimeFormat/>
<#assign logged = logged?default(false)/>
<#assign language = language?default("en_US")/>
<#assign hasCodeBlock = hasCodeBlock?default(false)/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=${encoding}" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<style type="text/css">@import url( ${contextPath}/templates/${templateName}/styles/style.css?${startupTime} );</style>
<style type="text/css">@import url( ${contextPath}/templates/${templateName}/styles/${language}.css?${startupTime} );</style>
<#if hasCodeBlock>
<style type="text/css">@import url( ${contextPath}/templates/${templateName}/styles/SyntaxHighlighter.css?${startupTime} );</style>
</#if>
<title>${pageTitle?default("JForum")?html}</title>
#加上熱門主題連結
<tr>
<td><a id="hottest" class="mainmenu" href="${JForumContext.encodeURL("/hottestTopics/list")}"><img src="${contextPath}/templates/${templateName}/images/icon_mini_recentTopics.gif" alt="[Hottest Topics]" /> ${I18n.getMessage("ForumBase.hottestTopics")}</a></td>
</tr>
#加上管理日誌連結
<#if canAccessModerationLog?default(false)>
<tr>
<td><a id="moderationlog" class="mainmenu" href="${JForumContext.encodeURL("/moderation/showActivityLog")}"><img src="${contextPath}/templates/${templateName}/images/icon_mini_members.gif" alt="[Moderation Log]" /> ${I18n.getMessage("ModerationLog.moderationLog")}</a></td>
</tr>
</#if>
#修改 /home/30elite/www/templates/tp101/bottom.htm,將v2.1.7的<iframe>標籤上方到</table>標籤間加上v2.1.8版的templates/default/bottom.htm的<iframe>標籤上方到</table>標籤間的程式碼
<#if hasCodeBlock>
<#include "highlighter_js.htm"/>
</#if>
#刪除forum_list.htm下方的登入表單
#修改post_show.htm
#刪除post_show_user_inc.htm中的<br>
#修改templates/tp101/styles/style.css,加上v.2.1.8新增的部分
附檔是我改過的tp101.zip(沒有psd檔)
|
 |
|
預先安裝函式庫: edtFTPj/Free
程式碼:
ftpdemo.jsp:
<%@ page import="java.io.File"%>
<%@ page import="java.util.Locale"%>
<%@ page import="com.enterprisedt.net.ftp.FTPClient"%>
<%@ page import="com.enterprisedt.net.ftp.FTPConnectMode"%>
<%@ page import="com.enterprisedt.net.ftp.FTPException"%>
<%@ page import="com.enterprisedt.net.ftp.FTPFile"%>
<%@ page import="com.enterprisedt.net.ftp.FTPMessageCollector"%>
<%@ page import="com.enterprisedt.net.ftp.FTPReply"%>
<%@ page import="com.enterprisedt.net.ftp.FTPTransferType"%>
<%@ page import="com.enterprisedt.net.ftp.UnixFileParser"%>
<%
// assign args to make it clear
String server = "192.168.1.2";
String username = "andowson";
String password = "changeit";
String directory = "download";
String filename = "C:\\Users\\Andowson\\Desktop\\jspSmartUpload.zip";
File filePut = new File(filename);
String filename2 = "C:\\Users\\Andowson\\Desktop\\commons-net-1.4.1.zip";
File fileGet = new File(filename2);
String filename3 = "jdk-6u3-windows-i586-p.exe";
FTPClient ftp = new FTPClient();
// We want to timeout if a response takes longer than 30 seconds
ftp.setTimeout(30000);
try {
// set up client
ftp.setRemoteHost(server);
FTPMessageCollector listener = new FTPMessageCollector();
ftp.setMessageListener(listener);
// connect
ftp.connect();
System.out.println("Connected to " + server + ".");
String messages = listener.getLog();
System.out.print(messages);
FTPReply reply = ftp.getLastReply();
if (reply != null) {
System.out.print(reply.getRawReply());
//String replyCode = reply.getReplyCode();
System.out.print(reply.getReplyCode());
}
// login
ftp.login(username, password);
// set up passive BINARY transfers
ftp.setConnectMode(FTPConnectMode.PASV);
// get directory and print it to console
UnixFileParser ufp = new UnixFileParser();
ufp.setLocale(new Locale("en", "US"));
String[] files = ftp.dir(directory, true);
long totalSize = 0L;
for (int i = 0; i < files.length; i++) {
//System.out.println(files[i]);
FTPFile file = ufp.parse(files[i]);
System.out.printf("%s %s [%d bytes]\n",
(file.isDir() ? "[D]" : " "), file.getName(), file.size());
if (!file.isDir()) {
totalSize += file.size();
}
}
System.out.println("totalSize = " + totalSize / (1024 * 1024) + "MB");
ftp.chdir(directory);
System.out.println(ftp.pwd());
ftp.setType(FTPTransferType.BINARY);
// copy file to server
ftp.put(filename, filePut.getName());
// copy file from server
ftp.get(filename2, fileGet.getName());
// delete file from server
ftp.delete(filename3);
// Shut down client
ftp.quit();
} catch (FTPException e) {
e.printStackTrace();
} finally {
if (ftp.connected()) {
try {
ftp.quit();
} catch (Exception e) {
// do nothing
}
}
}
%>
備註:
edtFTPj的函式名稱跟FTP指令的名稱相當接近,使用起來比較直覺,但39-44行部分印不出東西來,不知道為什麼抓不到replyCode,如果您有試出來,請告知一下。
|
 |
|
預先安裝函式庫: Apache Commons Net
程式碼:
ftptest.jsp:
<%@ page import="java.io.File"%>
<%@ page import="java.io.FileInputStream"%>
<%@ page import="java.io.FileOutputStream"%>
<%@ page import="java.io.IOException"%>
<%@ page import="org.apache.commons.net.ftp.FTP"%>
<%@ page import="org.apache.commons.net.ftp.FTPClient"%>
<%@ page import="org.apache.commons.net.ftp.FTPFile"%>
<%@ page import="org.apache.commons.net.ftp.FTPReply"%>
<%
String server = "192.168.1.2";
String username = "andowson";
String password = "changeit";
String directory = "download";
String filename = "C:\\Users\\Andowson\\Desktop\\jspSmartUpload.zip";
File filePut = new File(filename);
String filename2 = "C:\\Users\\Andowson\\Desktop\\commons-net-1.4.1.zip";
File fileGet = new File(filename2);
String filename3 = "jdk-6u3-windows-i586-p.exe";
FTPClient ftp = new FTPClient();
// We want to timeout if a response takes longer than 30 seconds
ftp.setDefaultTimeout(30000);
try {
int reply;
ftp.connect(server);
System.out.println("Connected to " + server + ".");
System.out.print(ftp.getReplyString());
// After connection attempt, you should check the reply code to verify
// success.
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
return;
}
// transfer files
if (ftp.login(username, password)) {
long totalSize = 0L;
for (FTPFile file : ftp.listFiles(directory)) {
System.out.printf("%s %s [%d bytes]\n",
(file.isDirectory() ? "[D]" : " "), file.getName(), file.getSize());
if (!file.isDirectory()) {
totalSize += file.getSize();
}
}
System.out.println("totalSize = " + totalSize/(1024 * 1024) + "MB");
// PASV
ftp.enterLocalPassiveMode();
// CWD
ftp.changeWorkingDirectory(directory);
// PWD
System.out.println(ftp.printWorkingDirectory());
// TYPE I
ftp.setFileType(FTP.BINARY_FILE_TYPE);
// PUT
ftp.storeFile(filePut.getName(), new FileInputStream(filePut));
// GET
ftp.retrieveFile(fileGet.getName(), new FileOutputStream(fileGet));
// DELE
ftp.deleteFile(filename3);
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
// do nothing
}
}
}
%>
參考資料:
http://commons.apache.org/net/apidocs/index.html
|
 |
|
要被下載的檔案先寫入到一個特定的目錄下如/WEB-INF/export,然後呼叫download.jsp?file=targetFileName取得,下載後並將檔案刪除。
程式碼:
download.jsp
<%@ page import= "java.io.*" %>
<%!
private static final int BUFSIZE = 2048;
/**
* Sends a file to the ServletResponse output stream. Typically
* you want the browser to receive a different name than the
* name the file has been saved in your local database, since
* your local names need to be unique.
*
* @param request The request
* @param response The response
* @param filename The name of the file you want to download.
* @param original_filename The name the browser should receive.
*/
private void doDownload( HttpServletRequest request, HttpServletResponse response,
String filename, String original_filename )
throws IOException
{
File f = new File(filename);
int length = 0;
ServletOutputStream op = response.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType( filename );
//
// Set the response and go!
//
//
response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
response.setContentLength( (int)f.length() );
response.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );
//
// Stream to the requester.
//
byte[] bbuf = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(f));
while ((in != null) && ((length = in.read(bbuf)) != -1))
{
op.write(bbuf,0,length);
}
in.close();
op.flush();
op.close();
}
%>
<%
String original_filename = request.getParameter("file");
// Security Isuue: User can type file=../WEB-INF/web.xml
//String filename = application.getRealPath(original_filename);
boolean error = false;
if (original_filename != null && !"".equals(original_filename) && !original_filename.startsWith("../")) {
String filename = application.getRealPath("/")+"WEB-INF/export/" + original_filename;
File file = new File(filename);
if (file.exists()) {
doDownload(request, response, filename, original_filename);
// delete the file after download
boolean deleted = file.delete();
System.out.println("File " + original_filename + " deleted: " + deleted);
} else {
error = true;
}
} else {
error = true;
}
if (error) {
response.setContentType("text/html; charset=UTF-8");
out.println("File not found: " + original_filename);
}
%>
參考資料:
http://www.jspwiki.org/wiki/MakingADownloadServlet
|
 |
|
使用Streaming API的方式:
程式碼:
fileupload_streaming.html:
<html>
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
</head>
<body>
檔案上傳
<form name="upload" enctype="multipart/form-data" method="post" action="fileupload_streaming.jsp">
上傳檔案: <input type="file" name="file" size="20" maxlength="20">
檔案說明: <input type="text" name="filedesc" size="30" maxlength="50">
<input type="submit"value="上傳"> <input type="reset" value="清除">
</form>
</body>
</html>
fileupload_streaming.jsp:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="java.io.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.util.Streams"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>
<%
String saveDirectory = application.getRealPath("/upload");
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
out.println("isMultipart="+isMultipart+"<br>");
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
//Create a progress listener
ProgressListener progressListener = new ProgressListener(){
private long megaBytes = -1;
public void update(long pBytesRead, long pContentLength, int pItems) {
long mBytes = pBytesRead / 1000000;
if (megaBytes == mBytes) {
return;
}
megaBytes = mBytes;
System.out.println("We are currently reading item " + pItems);
if (pContentLength == -1) {
System.out.println("So far, " + pBytesRead + " bytes have been read.");
} else {
System.out.println("So far, " + pBytesRead + " of " + pContentLength
+ " bytes have been read.");
}
}
};
upload.setProgressListener(progressListener);
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
String value = Streams.asString(stream);
out.println(name + "=" + value+"<br>");
} else {
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
// Process the input stream
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
out.println("fieldName="+fieldName+"<br>");
out.println("fileName="+fileName+"<br>");
out.println("contentType="+contentType+"<br>");
if (fileName != null && !"".equals(fileName)) {
fileName= FilenameUtils.getName(fileName);
out.println("fileName saved="+fileName+"<br>");
File uploadedFile = new File(saveDirectory, fileName);
FileOutputStream uploadedFileStream =
new FileOutputStream(uploadedFile);
Streams.copy(stream, uploadedFileStream, true);
}
}
}
%>
參考資料:
http://commons.apache.org/fileupload/streaming.html
|
 |
|
預先安裝函式庫: Apache Commons FileUpload, Apache Commons IO
程式碼:
fileupload.html:
<html>
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=big5" />
</head>
<body>
檔案上傳
<form name="upload" enctype="multipart/form-data" method="post" action="fileupload.jsp">
上傳檔案: <input type="file" name="file" size="20" maxlength="20" />
檔案說明: <input type="text" name="filedesc" size="30" maxlength="50" />
<input type="submit"value="上傳" /> <input type="reset" value="清除" />
</form>
</body>
</html>
fileupload.jsp:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="java.io.File"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.util.List"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.io.FilenameUtils"%>
<%
String saveDirectory = application.getRealPath("/upload");
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
out.println("isMultipart="+isMultipart+"<br>");
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
//Create a progress listener
ProgressListener progressListener = new ProgressListener(){
private long megaBytes = -1;
public void update(long pBytesRead, long pContentLength, int pItems) {
long mBytes = pBytesRead / 1000000;
if (megaBytes == mBytes) {
return;
}
megaBytes = mBytes;
System.out.println("We are currently reading item " + pItems);
if (pContentLength == -1) {
System.out.println("So far, " + pBytesRead + " bytes have been read.");
} else {
System.out.println("So far, " + pBytesRead + " of " + pContentLength
+ " bytes have been read.");
}
}
};
upload.setProgressListener(progressListener);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
// Process a regular form field
//processFormField(item);
String name = item.getFieldName();
String value = item.getString();
value = new String(value.getBytes("UTF-8"), "ISO-8859-1");
out.println(name + "=" + value+"<br>");
} else {
// Process a file upload
//processUploadedFile(item);
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
out.println("fieldName="+fieldName+"<br>");
out.println("fileName="+fileName+"<br>");
out.println("contentType="+contentType+"<br>");
out.println("isInMemory="+isInMemory+"<br>");
out.println("sizeInBytes="+sizeInBytes+"<br>");
if (fileName != null && !"".equals(fileName)) {
fileName= FilenameUtils.getName(fileName);
out.println("fileName saved="+fileName+"<br>");
File uploadedFile = new File(saveDirectory, fileName);
item.write(uploadedFile);
}
}
}
%>
注意:
請自行在您網頁應用程式的根目錄下建立一個upload的子目錄,並確認或設定讓Tomcat對upload目錄具有可寫入權限(Linux環境)。
參考資料:
http://commons.apache.org/proper/commons-fileupload/using.html
|
 |
|
預先安裝函式庫: Apache Commons Email, Sun JavaMail API, JavaBeans Activation Framework (JAF)
程式碼:
<%@ page contentType="text/html; charset=big5"%>
<%@ page import="org.apache.commons.mail.SimpleEmail"%>
<%
String subject="歡迎光臨";
String message = "這是一封測試信,收到請自行刪除";
SimpleEmail simpleEmail = new SimpleEmail();
simpleEmail.setHostName("smtp.mycompany.com");
simpleEmail.setCharset("Big5");
simpleEmail.addTo("you@yourcompany.com", "親愛的會員");
simpleEmail.setFrom("service@mycompany.com", "網站客服中心");
simpleEmail.setSubject(subject);
simpleEmail.setMsg(message);
simpleEmail.send();
out.println("郵件發送成功");
%>
|
 |
|