擴充原本JDK Properties Class,讓Properties裡面的可以宣告變數。
星期四, 6月 30, 2011
星期三, 6月 29, 2011
Multiple File Upload Plugin
多檔上傳元件:
Flash:
http://www.uploadify.com/
http://digitarald.de/project/fancyupload/3-0/showcase/attach-a-file/
No Flash:
http://valums.com/ajax-upload/ License:GPL2 LGPL2
http://aquantum-demo.appspot.com/file-upload License:MIT
PS:上面的連結常常會失效,請改到github查看使用說明
https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
other:
http://the-stickman.com/web-development/javascript/upload-multiple-files-with-a-single-file-element/
Flash:
http://www.uploadify.com/
http://digitarald.de/project/fancyupload/3-0/showcase/attach-a-file/
No Flash:
http://valums.com/ajax-upload/ License:GPL2 LGPL2
http://aquantum-demo.appspot.com/file-upload License:MIT
PS:上面的連結常常會失效,請改到github查看使用說明
https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
other:
http://the-stickman.com/web-development/javascript/upload-multiple-files-with-a-single-file-element/
星期一, 6月 27, 2011
[jQuery plugin] How to sorting JSON Array
原理是使用javascript的sort()函數,此函數也提供讓使用者自訂sort function。
<script type="text/javascript">
var arr = [
{ "ID": 135, "Name": "Fargo Chan", "Address": "34, Baker Street" },
{ "ID": 432, "Name": "Aaron Luke", "Address": "BLDG 1, J Street" },
{ "ID": 252, "Name": "Dilip Singh", "Address": "Hotel J, SE" }
];
// Before Sorting
document.write("<b>Before Sorting </b><br/>");
for (var n = 0; n < arr.length; n++) {
document.write(arr[n].ID + ' ' + arr[n].Name + '<br>');
}
// ascending order
function SortByID(x,y) {
return x.ID - y.ID;
}
function SortByName(x,y) {
return ((x.Name == y.Name) ? 0 : ((x.Name > y.Name) ? 1 : -1 ));
}
// Call Sort By Name
arr.sort(SortByName);
document.write("<br/><b>After Sorting </b> <br/>");
for(var n=0;n<arr.length;n++){
document.write(arr[n].ID + ' ' + arr[n].Name + '<br>');
}
</script>
可重覆使用的範例:參考至How to sort a JSON array ?
Here's a more flexible version, which allows you to create reusable sort functions, and sort by any field
var sort_by = function(field, reverse, primer){
reverse = (reverse) ? -1 : 1;
return function(a,b){
a = a[field];
b = b[field];
if (typeof(primer) != 'undefined'){
a = primer(a);
b = primer(b);
}
if (a<b) return reverse * -1;
if (a>b) return reverse * 1;
return 0;
}
}
Now you can sort by any field at will
// Sort by price high to low
homes.sort(sort_by('price', true, parseInt));
// Sort by city, case-insensitive, A-Z
homes.sort(sort_by('city', false, function(a){return a.toUpperCase()}));
可以改寫成jQuery plugin的寫法:
(function($) {
$.extend({
sortBy : function(objects, field, reverse, fieldValueFunc) {
//ASC or DESC
//if reverse is true, data will be sorted using DESC
reverse = (reverse) ? -1 : 1;
//init sort func
var sortFunc = function(elA, elB) {
//get value by field name
elA = elA[field];
elB = elB[field];
if (typeof (fieldValueFunc) != 'undefined') {
elA = fieldValueFunc(elA);
elB = fieldValueFunc(elB);
}
//return element comparison value
if (elA < elB)
return reverse * -1;
if (elA > elB)
return reverse * 1;
return 0;
};
//call sort() method using sortFunc
objects.sort(sortFunc);
}
});
})(jQuery);
使用方式
$.sortBy(arr,"ID",false,parseInt);
[Java] Reading InputStream
如何使用Java 讀取InputStream資料。
可指定編碼格式UTF-8
//預設編碼為ANSI(ASCII)
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream));
String currentLine = null;
while((currentLine = in.readLine()) != null){
System.out.println("currentLine" + currentLine);
}
可指定編碼格式UTF-8
BufferedReader in = new BufferedReader( new InputStreamReader(inputStream,"UTF-8"));
星期四, 6月 23, 2011
[Java] Base64 Encoder
1. 下載所需的Jar檔。(這裡我們是使用Apache的commons-codec套件)
2. import org.apache.commons.codec.binary.Base64;
3. 使用Base64 Class進行編碼與解碼
Reference:
Java Base64 Encode & Decode(編碼和解碼)
2. import org.apache.commons.codec.binary.Base64;
3. 使用Base64 Class進行編碼與解碼
Base64 base64 = new Base64();
//使用Base64進行字串編碼
String encodeString = new String(base64.encode("This is source string.".getBytes()));
//輸出結果將為"VGhpcyBpcyBzb3VyY2Ugc3RyaW5nLg=="
System.out.println(encodeString);
//使用Base64進行字串解碼
String decodeString = new String(base64.decode(encodeString.getBytes()));
//輸出結果將為"This is source string."
System.out.println(decodeString);
Reference:
Java Base64 Encode & Decode(編碼和解碼)
[Java] Read Microsoft XLS using JDBC
import java.sql.*;
public class MainWindow {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con= DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=d:/desktop/test.xls");
Statement st=con.createStatement();
ResultSet rs= st.executeQuery("select * from [Sheet1$]");//Sheet1是工作表名稱
while(rs.next()){
System.out.println(rs.getInt("id")+" "+rs.getString("name"));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Reference:
Apache POI - Code Sample
Handle Excel files
星期一, 6月 13, 2011
regular expression 正則式筆記
蒐集常用的正則式,不定期更新。
Regex 所使用的符號彙整
找出所有非特殊字元
[^\W_]+
找出特殊字元
[\W_]+
找出HTML Tag
<([\s\S]+)?>
驗證是否符合a-z A-Z 0-9 中文字
[a-zA-Z0-9\u4e00-\u9fa5]+
Reference:
過濾特殊字元
[入門][Regex] Regular Expression 詳論
正则表达式:英文、中文、数字、下划线
Regex 所使用的符號彙整
| 記號 | 說明 |
| 字元 | 代表該字元, 例如輸入 a 就代表那個地方應該出現 a 這個字元 |
| ^ | 限制字串必須出現於行首, 例如 ^a 表這串字必須以 a 開頭; 如果 a 出現在其它地方, 都不算數 |
| $ | 限制字串必須出現於行末, 例如 a$ 表這串字必須以 a 結尾; 如果 a 出現在其它地方, 都不算數 |
| \ | 將特殊字元還原成字面意義的字元, 例如 \( 代表 ( 這個符號, \\ 代表 \ 這個符號; 這種表示法適用於 (, ), [, ] 等在 Regex 有特殊意義的字元 |
| ^ | 某字元以外的任何字元, 必須包在中括號裡面。例如 [^a] 表示 a 除外的任何字元或符號, [^a\t] 表示 a 和 tab 除外的任何字元或符號 |
| - | 字元集合中可使用 - 來指定字元的區間, 必須包在中括號裡面。例如 [a-z] 表示從 a 到 z 的英文小寫字元, [1-3] 表示從 1 到 3 這三個數字之一 |
| + | 其前的字元或字元集合出現一次或一次以上, 例如 a+ |
| ? | 其前的字元或字元集合可出現一次或不出現, 例如 a? |
| * | 其前的字元或字元集合可出現任何次數或不出現, 例如 a* |
| (...) | 用以括住一群字元,且將之視成一個集合, 通常用來集合表示多個檢核式 |
| {n} | 重複 n 次 |
| {n,m} | 重複 n 到 m 次 |
| {n,} | 至少重複 n 次 |
| [] | 其中之一字元可出現可不出現,例如 [abc] 表示不論出現 a 或 b 或 c 都算符合 |
| | | 代表「或」, 例如 (Sun|Mon|Tue|Wed|Thu|Fri|Sat), (日|一|二|三|四|五|六) ; 必須以左右括號括住 |
| . (句點符號) | 代表除了換行符號 (\n) 以外的任一字元。如果要包括換行符號,請使用 [\s\S] |
| \w (\W) | 代表任何英文(以外的) 字元 - 請注意, 數字字元也被承認 |
| \s (\S) | 代表空白 (以外的) 字元 |
| \d (\D) | 代表數字 (以外的) 字元 |
| \b (\B) | 代表位於文字邊界的 (以外的) 字元, 例如 \bA 可以檢核出 AB, A\b 可以檢核出 BA, \bAA\b 可以檢核出 AA |
| \r | 代表換行字元 (或稱 CR, Carriage Return) |
| \n | 代表換行字元 (或稱 LF, Line Feed; 通常和 \r 一同出現, 所以一般以 \r\n 代表換行, 但根據我的測試, 無論使用 \r 或 \n 或 \r\n 都會得到相同的結果, 但唯獨不能寫成 \n\r, 但建議使用 \r?\n) |
| \t | 代表 TAB 字元 (或稱 HT, Horizontal Tab) |
| \( | 代表左括號 |
| \) | 代表右括號 |
| \x | 以十六進位字元碼代表某個字元; 例如 [\x21-\x7E] 可代表所有看得到的字元 ([\x20-\x7E] 則包括空白字元)。不過注意 \x 之後要使用兩個數字, 不足兩個數字者請補 0, 例如 \x01 |
| \1, \2... | (Backreference Constructs) 表示出現過的群組; 例如 "(\d)(\D)" 樣式中有兩個群組, 若使用 "(\d)(\D)\1" 可檢出 "2A3"; 若使用 "(\d)(\D)\2+" 則可檢出 "2AB"; 餘此類推 |
| \k | 同上, 但適用於命名的群組; 例如 "(? |
| \p{Lu} (\P{Lu}) | 檢出大寫(非大寫)的字母, 例如 (?-i:\p{Lu}) 可檢出字串中所有大寫字母, 而 (?-i:\P{Lu}) 可檢出所有非大寫 (包括數字、空白等) 的字母 |
找出所有非特殊字元
[^\W_]+
找出特殊字元
[\W_]+
找出HTML Tag
驗證是否符合a-z A-Z 0-9 中文字
[a-zA-Z0-9\u4e00-\u9fa5]+
Reference:
過濾特殊字元
[入門][Regex] Regular Expression 詳論
正则表达式:英文、中文、数字、下划线
星期三, 6月 08, 2011
星期二, 6月 07, 2011
[Java] Upload file using Jersey
目前使用Jersey接收上傳檔案只能使用HttpServletRequest來接收上傳成功!!
尚未解決使用@FormDataParam無法上傳的錯誤!!待解
以下範例是使用Apache FileUpload Module 來取得上傳的檔案物件
Reference:
Multiple file upload using RESTful web service (Jersey)
尚未解決使用@FormDataParam無法上傳的錯誤!!待解
//目前會HTTP Status 415 - Unsupported Media Type大爆炸
@POST
@Path("/simpleupload2")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void simpleUpload2(
@FormDataParam("username") final String username,
@FormDataParam("filedata") final InputStream file,
@FormDataParam("filedata") final FormDataContentDisposition disposition){
System.out.println("username:" + username);
}
以下範例是使用Apache FileUpload Module 來取得上傳的檔案物件
@POST
@Path("/simpleupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void simpleUpload(
//@Context UriInfo ui,
@Context HttpServletRequest request
){
String fileRepository = "D:\\";
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
if (items != null) {
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField() && item.getSize() > 0) {
System.out.println("File is found.");
String fileName = processFileName(item.getName());
try {
String savePath = fileRepository + fileName;
System.out.println("savePath:" + savePath);
item.write(new File(savePath));
} catch (Exception e) {
e.printStackTrace();
}
}else{
System.out.println("getFieldName:" + item.getFieldName());
System.out.println(item.getString());
}
}
}
}
}
Reference:
Multiple file upload using RESTful web service (Jersey)
星期一, 6月 06, 2011
[Java] UnicodeFormatter
/*
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
public class UnicodeFormatter {
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
}
星期三, 6月 01, 2011
[Java] Fake UTF-16
static public String CoverterUtf8ToFakeUtf16(String utf8String) throws UnsupportedEncodingException {
byte[] inputBytes = utf8String.getBytes("UTF-8");
printBytes(inputBytes,"input bytes:");
ArrayList list = new ArrayList();
//convert input bytes to utf-16
for(int i=0;i<inputBytes.length;i++){
list.add(new Byte("00"));
list.add(inputBytes[i]);
}
byte[] returnByte = new byte[list.size()];
for(int i=0;i<returnByte.length;i++){
returnByte[i] = (Byte)list.get(i);
}
returnByte = new String(returnByte, Charset.forName("UTF-16")).getBytes("UTF-8");
printBytes(returnByte,"return bytes:");
String fakeUtf16 = new String(returnByte,Charset.forName("UTF-8"));
printBytes(fakeUtf16.getBytes("UTF-8"),"fakeUtf16 bytes:");
return fakeUtf16;
}
Testing
public void fakeUtf16(InputStream requestBodyStream ) throws UnsupportedEncodingException {
String requestBODY = RequestBODY.get(requestBodyStream,Charset.forName("utf-8"));
System.out.println("requestBODY:" + requestBODY);
String fakeUtf16 = UnicodeFormatter.CoverterUtf8ToFakeUtf16(requestBODY);
System.out.println("fakeUtf16:" + fakeUtf16);
}
Console 輸出訊息--fakeUtf16--
charset:UTF-8
requestBODY:中
input bytes:[0] = 0xe4
input bytes:[1] = 0xb8
input bytes:[2] = 0xad
return bytes:[0] = 0xc3
return bytes:[1] = 0xa4
return bytes:[2] = 0xc2
return bytes:[3] = 0xb8
return bytes:[4] = 0xc2
return bytes:[5] = 0xad
fakeUtf16 bytes:[0] = 0xc3
fakeUtf16 bytes:[1] = 0xa4
fakeUtf16 bytes:[2] = 0xc2
fakeUtf16 bytes:[3] = 0xb8
fakeUtf16 bytes:[4] = 0xc2
fakeUtf16 bytes:[5] = 0xad
fakeUtf16:ä¸
fakeUtf16:[0] = 0xfe
fakeUtf16:[1] = 0xff
fakeUtf16:[2] = 0x00
fakeUtf16:[3] = 0xe4
fakeUtf16:[4] = 0x00
fakeUtf16:[5] = 0xb8
fakeUtf16:[6] = 0x00
fakeUtf16:[7] = 0xad
--/fakeUtf16--
星期四, 5月 19, 2011
星期日, 5月 15, 2011
[JQuery Plugin] AJAX Form using Jquery
使用jquery達到ajax form submit的需求。
請參考這個元件jQuery Form Plugin
javascript:
請參考這個元件jQuery Form Plugin
javascript:
$(function(){
// bind to the form's submit event
$("#formAJAX").ajaxForm({
url: "http://localhost:8080/webproject/yourpage" ,
beforeSubmit: showRequest,
type: "get",
dataType: "json",
success: showResponse
});
});
//pre-submit callback
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert(queryString);
return true;
}
//post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);//單純的Text
}
//發現用showResposne的時候,responseText才會被直接轉換成JSON Object
function showResponse(responseText)
html page:<form id="formAJAX" > <input id="doSubmit" type="submit" name="button" value="submit" /> </form>
[Javascript] 使用javascript取代所有比對的字串
在javascript的replace函式如果不使用正則表示式的格式的話,只能取代第一個符合的字串規則。
請參考以下這篇文章:
The JavaScript function for String Replace replaces the first occurrence in the string. The function is similar to the php function str_replace and takes two simple parameters. The first parameter is the pattern to find and the second parameter is the string to replace the pattern with when found. The javascript function does not Replace All...
To ReplaceAll you have to do it a little differently. To replace all occurrences in the string, use the g modifier like this:
Reference:
JavaScript String Replace All
請參考以下這篇文章:
The JavaScript function for String Replace replaces the first occurrence in the string. The function is similar to the php function str_replace and takes two simple parameters. The first parameter is the pattern to find and the second parameter is the string to replace the pattern with when found. The javascript function does not Replace All...
str = str.replace(”find”,”replace”)
To ReplaceAll you have to do it a little differently. To replace all occurrences in the string, use the g modifier like this:
str = str.replace(/find/g,”replace”)
Reference:
JavaScript String Replace All
星期三, 5月 11, 2011
[JSP] JSP-防止瀏覽器快取網頁
今天工作處理IE8異常cache網頁導致ajax異常,多虧FIDDLER這個好用的http tool。
以下為參考的資料:
JSP技巧篇---防止瀏覽器快取網頁
(資料來源:Java Server Page 學習網 -- http://www.jsp.mlc.edu.tw )
瀏覽器為了加速使用者的瀏覽速度,常會將瀏覽過的網頁快取到硬碟,
下次瀏覽同一頁時,便去硬碟裡面去找,但現在的網頁常是動態的,
為了避免使用者抓到硬碟內過期的資料,JSP可用下面的方式來防止瀏
覽器快取住網頁,此方法便可保證使用者到這個網頁時始終都可看到
1.JSP語法
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-cache");
//prevents caching at the proxy server
response.setDateHeader("Expires", 0);
%>
2.也可以用以下的HTML語法,可用在靜態網頁上
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
201203/14更新
今天仔細測了一下,就算加了這些Header可以清Cache,但並非馬上就會更新。
需要多按幾次重新整理才會馬上更新!!
以下為參考的資料:
JSP技巧篇---防止瀏覽器快取網頁
(資料來源:Java Server Page 學習網 -- http://www.jsp.mlc.edu.tw )
瀏覽器為了加速使用者的瀏覽速度,常會將瀏覽過的網頁快取到硬碟,
下次瀏覽同一頁時,便去硬碟裡面去找,但現在的網頁常是動態的,
為了避免使用者抓到硬碟內過期的資料,JSP可用下面的方式來防止瀏
覽器快取住網頁,此方法便可保證使用者到這個網頁時始終都可看到
1.JSP語法
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-cache");
//prevents caching at the proxy server
response.setDateHeader("Expires", 0);
%>
2.也可以用以下的HTML語法,可用在靜態網頁上
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
201203/14更新
今天仔細測了一下,就算加了這些Header可以清Cache,但並非馬上就會更新。
需要多按幾次重新整理才會馬上更新!!
星期一, 5月 09, 2011
[JQuery Plugin] Checkbox 按鈕skin
想要在Web上面使用像iphone的enable按鈕嗎?
以下這個外掛可以達到你的需求!!
Jquery check box
Lightweight custom styled checkbox implementaion for jQuery 1.2.x and 1.3.x.
How to use:
增加按鈕是否被按下,請使用bind的方法
adds new checkbox events "check", "uncheck", "disable", "enable", ready to use in jQuery.bind() method
http://widowmaker.kiev.ua/checkbox/
以下這個外掛可以達到你的需求!!
Jquery check box
Lightweight custom styled checkbox implementaion for jQuery 1.2.x and 1.3.x.
How to use:
$("input:checkbox").checkbox({
empty: 'images/empty.png'
});
PS:支援checkbox的disabled、checked,會讓UI樣式不一樣。增加按鈕是否被按下,請使用bind的方法
adds new checkbox events "check", "uncheck", "disable", "enable", ready to use in jQuery.bind() method
$("input:checkbox").bind('check',function(){
//被按了
});
http://widowmaker.kiev.ua/checkbox/
星期五, 5月 06, 2011
星期三, 5月 04, 2011
[Javascript] 字串處理 (String Operations)
Javascript 字串處理 (String Operations)
尋找字串(search)
stringObject.search(searchstring)
stringObject.search(尋找的字串)
大小寫必須相符
var str = "test String";
alert(str.search("Str"));
alert(str.search("str"));
輸出結果:5
輸出結果:-1
尋找字串(search)
stringObject.search(searchstring)
stringObject.search(尋找的字串)
大小寫必須相符
var str = "test String";
alert(str.search("Str"));
alert(str.search("str"));
輸出結果:5
輸出結果:-1
訂閱:
意見 (Atom)

