顯示具有 Java 標籤的文章。 顯示所有文章
顯示具有 Java 標籤的文章。 顯示所有文章

2011年6月28日 星期二

將xsd檔轉成Java Code

要將xsd轉成Java只需要使用到xjc這個指令即可,而xjc這個指令就位於jdk下的bin目錄中。

以下指令-p參數表示你要輸出的PackageName

xjc -p your.package.name yourXsdFile.xsd


2010年3月3日 星期三

Java AES Encrypt & Decrypt Example(加解密)

範例程式
//欲加密的字串
String msg = "This is a message.";
System.out.println("原始字串:"+new String(msg));
//設定要使用的加密演算法
KeyGenerator keyG = KeyGenerator.getInstance("AES");
//設定key的長度
keyG.init(256);
//產生SecretKey
SecretKey secuK = keyG.generateKey();
//取得要用來加密的key(解密也需使用這把key)
byte[] key = secuK.getEncoded();
System.out.println("key:"+new String(key));
SecretKeySpec spec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
//設定為加密模式
cipher.init(Cipher.ENCRYPT_MODE, spec);
//將字串加密,並取得加密後的資料
byte[] encryptData = cipher.doFinal(msg.getBytes());
System.out.println("加密後字串:"+new String(encryptData));

//使用剛剛用來加密的key進行解密
spec = new SecretKeySpec(key, "AES");
cipher = Cipher.getInstance("AES");
//設定為解密模式
cipher.init(Cipher.DECRYPT_MODE, spec);
byte[] original = cipher.doFinal(encryptData);
System.out.println("解密後字串:"+new String(original));

輸出結果
原始字串:This is a message.
key:�U{� jPk ���@7 .�A@��&]W LK���ݣ
加密後字串:��� � ����tl7Q U!���d�{4R) �� .
解密後字串:This is a message.


2010年3月2日 星期二

Java date to string(日期轉字串)

Java 日期轉字串範列
//目前時間
Date date = new Date();
//設定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//進行轉換
String dateString = sdf.format(date);
System.out.println(dateString);


輸出結果
2010-03-02 19:15:57


Java string to date(字串轉日期)

Java字串轉日期範例
//欲轉換的日期字串
String dateString = "20010-03-02 20:25:58";
//設定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//進行轉換
Date date = sdf.parse(dateString);
System.out.println(date);

輸出結果
Tue Mar 02 20:25:58 CST 20010


Java string split(字串切割)

Java字串切割範例
//欲切割的字串
String splitString = "Bob:Stev:David:John";
//使用「:」進行切割
String[] names = splitString.split(":");
for(String name:names){
    System.out.println(name);
}

輸出結果
Bob
Stev
David
John


Java int to String(整數轉字串)

1. String stringValue = Integer.toString(12345);

2. String stringValue = String.valueOf(12345);

3. String stringValue = new String(""+12345);


Java string to int(字串轉整數)

1. int intValue = Integer.valueOf("12345");

2. int intValue = Integer.parseInt("12345");


2010年1月19日 星期二

Java - 使用iText輸出pdf檔(三) 表格(table)範例

1. 參考Java - 使用iText輸出pdf檔(一) Hello world範例

2. 表格(table)範例。
//建立PdfPTable物件並設定其欄位數
PdfPTable table = new PdfPTable(2);
//設定table的寬度
table.setWidthPercentage(100f);
//設定每個欄位的寬度
table.setWidths(new float[]{0.20f, 0.90f});

PdfPCell title = new PdfPCell();
//合併儲存格
title.setColspan(2);
title.addElement(new Phrase("Table's Title"));
table.addCell(title);

//設定第一個欄位的內容
PdfPCell cell_1 = new PdfPCell();
cell_1.addElement(new Phrase("Column 1"));
table.addCell(cell_1);

//設定第二個欄位的內容
PdfPCell cell_2 = new PdfPCell();
cell_2.addElement(new Phrase("Column 2"));
table.addCell(cell_2);

document.add(table);


Java - 使用iText輸出pdf檔(二) 中文字範例

1. 參考Java - 使用iText輸出pdf檔(一) Hello world範例

2. 設定中文字型。
//指定要使用的字型(KAIU.TTF為Windows內建的標楷體)
BaseFont bf = BaseFont.createFont("C:\\WINDOWS\\Fonts\\KAIU.TTF", BaseFont.IDENTITY_H,  BaseFont.NOT_EMBEDDED);
//設定中文字型(BaseFont、字型大小、字型型態)
Font chineseFont = new Font(bf, 12, Font.NORMAL);
//套用中文字型
document.add(new Phrase("這是中文",chineseFont));


2010年1月18日 星期一

Java - 使用iText輸出pdf檔(一) Hello world範例

1. 下載iText Jar檔

2. Hello world範例。
FileOutputStream fos = new FileOutputStream(new File("C:/Hello world.pdf"));
//建立一個Document物件,並設定頁面大小及左、右、上、下的邊界
Document document = new Document(PageSize.A4, 10, 20, 30, 40);
//設定要輸出的Stream
PdfWriter.getInstance(document, fos);
document.open();
//設定作者
document.addAuthor("Author");
//設定建立者
document.addCreator("createor");
//設定主題
document.addSubject("subject");
//設定標題
document.addTitle("title");
//設定建立時間(為當下時間)
document.addCreationDate();

document.add(new Phrase("Hello world\n"));

document.close();


2010年1月17日 星期日

Java keytool 基本指令介紹

1. 匯入憑證到keystore
      keytool –import –alias xxx –file xxx.cer –keystore .keystore

2. 查詢keystore的內容
      keytool –list –v –keystore .keystore

3. 刪除keystore內的其中一個憑證
      keytool –delete –alias xxx –keystore .keystore

4. 產生金錀對(RSA為非對稱加密的演算法)
      keytool -genkey -alias xxx -keyalg RSA -keystore .keystore

5. 產生憑證申請檔
      keytool -certreq -alias xxx -file certreq.txt -keystore .keystore

6. 查詢PKCS12類型keystore的內容
      keytool –list –v –keystore .keystore -storetype pkcs12

7. 建立一個含有私鑰的keystore
      keytool -genkey -alias keyAlias -keyalg RSA -keystore keystore.jks

8. 修改keystore的密碼
      keytool -storepasswd -new newPassword -keystore keystore.jks


Java Base64 Encode & Decode(編碼和解碼)

1. 下載所需的Jar檔。(這裡我們是使用Apache的commons-codec套件)

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);


2010年1月12日 星期二

Direct Web Remoting(DWR) - Reverse Ajax

1. 要使用DWR Reverse Ajax需先指定參數activeReverseAjaxEnabled為true。

<servlet>
   <servlet-name>dwr-invoker</servlet-name>
   <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
   <init-param>
     <param-name>debug</param-name>
     <param-value>true</param-value>
   </init-param>
   <init-param>
     <param-name>activeReverseAjaxEnabled</param-name>
     <param-value>true</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
 </servlet>

2. 在要使用DWR Reverse Ajax的頁面(reverseAjax.jsp)加入以下設定。

<!-- DWR相關的Javascript -->
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<!-- 頁面載入時,即建立ReverseAjax連線 -->
<body onload="dwr.engine.setActiveReverseAjax(true);">
<!-- 從Server push回來的內容 -->
<span id="show"></span>


3. 觸發要回傳資料給Client端的Servlet。

ServerContext wctx = ServerContextFactory.get(this.getServletContext());
//取得要觸發的頁面
Collection sessions = wctx.getScriptSessionsByPage("/reverseAjax.jsp");
Util utilAll = new Util(sessions);
//設定回傳的內容,並指定放到DOM的哪個id內
utilAll.setValue("show", "這是Server回傳的資料");


2009年11月21日 星期六

Java keytool 基本指令介紹

1. 匯入憑證到keystore
      keytool –import –alias xxx –file xxx.cer –keystore .keystore

2. 查詢keystore的內容
      keytool –list –v –keystore .keystore

3. 刪除keystore內的其中一個憑證
      keytool –delete –alias xxx –keystore .keystore

4. 產生金錀對(RSA為非對稱加密的演算法)
      keytool -genkey -alias xxx -keyalg RSA -keystore .keystore

5. 產生憑證申請檔
      keytool -certreq -alias xxx -file certreq.txt -keystore .keystore
 
6. 查詢PKCS12類型keystore的內容
      keytool –list –v –keystore .keystore -storetype pkcs12

7. 建立一個含有私鑰的keystore
      keytool -genkey -alias keyAlias -keyalg RSA -keystore keystore.jks

8. 修改keystore的密碼
      keytool -storepasswd -new newPassword -keystore keystore.jks


2009年11月20日 星期五

Direct Web Remoting(DWR)簡介

DWR可以在Web Application上直接處理XMLHttpRequest,因此你可以在 有的架構下利用DWR來產生Ajax的
效果。而且DWR非常簡單,只要再web.xml加入DRW的Servlet並新增一個dwr.xml的設定檔。就可以直接在Client端
利用Javascript直接呼叫Server端的Java方法。
以下建構一個簡單的例子,在Client端輸入一串字串,Servler端在收到這一個字串後,回傳Client端輸入的字串並回傳
Server端目前系統時間。


1. 下載dwr.jar檔。


2. 在web.xml加入DRW的Servlet。
<servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>
            org.directwebremoting.servlet.DwrServlet
    </servlet-class>
    <init-param>
        <param-name>debug</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
</servlet-mapping>


3. 在WEB-INF下新增一個dwr.xml的設定檔。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
"http://www.getahead.ltd.uk/dwr/dwr20.dtd">
<dwr>
    <allow>
        <create creator="new" javascript="AjFuns">
            <param name="class" value="tw.nicky.dwr.AjaxFunctions"/>
       </create>
    </allow>
</dwr>



4. 建立AjaxFunctions.class(此類別就是用戶端要呼叫的類別)
package tw.nicky.dwr;
import java.util.Date;
public class AjaxFunctions {
    public String getEchoTime(String msg) {
        String result = "";
        result = result + "your input: "+msg+" ";
        result = result + "server time: "+new Date();
        return result;
    }
}




5.最後建立呈現在用戶端的網頁()
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>dwr_example</title>
        <script type='text/javascript' src='dwr/interface/AjFuns.js'></script>
        <script type='text/javascript' src='dwr/engine.js'></script>
        <script type='text/javascript'>
            function getEchoTime(){
                var msg = document.getElementById("msg").value;
                AjFuns.getEchoTime(msg,function(ret){
                    document.getElementById("results").innerHTML = ret;
                });

            }
        </script>
    </head>
    <body>
        <input type="text" id="msg">
        <input type="button" value="確定" onClick="getEchoTime()">
        <div id="results">
        </div>
    </body>
</html>