2013年1月31日 星期四

MyFirstServlet


這個Servlet 擴充了HttpServlet 類別,並改寫繼承的doGet()方法,當伺服器收到送往這Servlet的Get Request 時,伺服器便會呼叫 doGet(),並傳入一個HttpServletRequest 物件和HttpServletResponse物件。

HttpServletRequest 物件代表client提出的申請,讓servlet 得到client的資訊
request的參數。HttpServletResponse 物件代表Servlet 要回傳給client的回覆
,內容可以是各種型態,但必須在response中註明是何種type。在此程式中先用setContenType 方法將內容型態定義為"text/html"

在NetBeans中的使用方式如下


=============================================================


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class HelloWorld extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet HelloWorld</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet HelloWorld at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request
            , HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        out.println("<HTML>");
        out.println("<HEAD><TITLE>hello World</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("<Big>Hello World11</Big>");
        out.println("</BODY></html>");
//        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

2013年1月29日 星期二

淺談setDefaultCloseOperation() 的四個參數


java Swing 開發視窗 , 當你在點下視窗上 X 按鍵時 ,





會關閉視覺化的視窗 ,但如未設定視窗跳出的方法(system.exit) ,所關閉的程序還是會一直存在記憶体中無法消去

此時可以使用此方法 setDefaultCloseOperation(int operation)

在參數(int operation) 中 有四個參數可以選擇, 也可填入相對應的數字 


1.將X退出鍵 設為失效 , 也就是使點擊後無效 , 不起作用。
  setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
 =setDefaultCloseOperation(0);



2.點擊退出時,只是將視覺化的介面(HIDE),實際程序還是在後台執行(記憶体未釋放)
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE );
 =setDefaultCloseOperation(1);


3.先退出介面等待處理后再釋放記憶体
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOS);
 =setDefaultCloseOperation(2);

4.直接退出介面並釋放記憶体
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 =setDefaultCloseOperation(3);

NetBean 的第一隻程式





  1. 開啟NetBeans
  2. 在IDE環境中選擇FILE> New Project (Ctrl-Shift-N),如下圖所示
  1. 在新專案精靈中,展開JAVA的分類,並選擇Java Application,並選Next,如下圖所示。

  1. 在Name and Location 的精靈頁中,輸入以下設定
  • 在Project Name欄位中,輸入HelloWorldApp
  • 取消Use Dedicated Folder for Storing Libraries的打勾部分
  • 勾選Create Main Class的部分並輸入   helloworldapp.HelloWorldApp.
  • 勾選 Set as Main Project 的部分
  1. 選擇Finish
專案將自動建立並在IDE環境中自動被開啟,您可以參考下面的元件
在Projects 視窗中,可以看到Project的元件的樹狀結構包含source files,您寫程式時會參考到的libraries等。
HelloWorldApp  會在Source 編輯器的視窗中自動被開啟。
在Navigator視窗中,您可以快速的瀏覽所選的類別中的元素
在 Tasks 視窗中列出編譯錯誤,以及關鍵字

Adding Code to the Generated Source File
因您在新專案精靈中將Create Main Class checkbox勾選,IDE將自動幫您產生一個main 類別的骨架,您可以在骨架中藉由下面的程式加入Hello World的訊息
           // TODO code application logic here
           System.out.println("Hello World!");

由File>Save中選擇存檔
檔案看起來會長的如下面的樣子
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package helloworldapp;

/**
*
* @author <your name>
*/
public class HelloWorldApp {

   /**
    * @param args the command line arguments
    */
   public static void main(String[] args) {
           System.out.println("Hello World!");
   }

}

Adding Code to the Generated Source File
IDE會在您存檔時自動compile,您不需要為了執行您的程式而再手動編譯您的專案,要執行程式時您可以選擇Run>Run Main Project(F6)

麥肯錫邏輯思考力

Android AlertDailog 應用


由mydialog1 複製過來,重新命名為mydialog2,並針對 com.example.mydialog1 
refactor 為 com.example.mydialog2。

showDialog()函數中,定義字串陣列 String[] items = {"Android", "iOS", "Win8", "Other"}; 按下選單時觸發builder.setItems 函數,


builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

}
})

詳細程式如下



package com.example.mydialog2;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mydialog1.R;

public class MainActivity extends Activity {
private Button click1;
private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click1=(Button) findViewById(R.id.click1);
click1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog();
}
});


}

private void showDialog()
{
AlertDialog dialog1;
AlertDialog.Builder builder=new AlertDialog.Builder(this);
String[] items = {"Android", "iOS", "Win8", "Other"};

builder.setTitle("請選擇");
builder.setCancelable(false);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "" + which, Toast.LENGTH_SHORT).show();
}
});
dialog1=builder.create();
dialog1.show();
}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}






2013年1月28日 星期一

JAVA 連結 ACCESS 範例



本程式主要透過ODBC連結ACCESS,故須先設計一資料庫MFG,其中Table1 欄位如下


 ODBC 設定如下





主要JAVA 程式碼如下


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Login;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;


/**
 *
 * @author jackylin
 */
public class login {        
            Connection Conn;            
            Statement st;
            ResultSet rs;
            JFrame f=new JFrame("Login ");
            JLabel l=new JLabel("User:");
            JTextField t=new JTextField(10);
            JLabel l1=new JLabel("Pass:");
            JTextField t1=new JTextField(10);
            JButton b=new JButton("Login");
            JPanel p=new JPanel();
         
          public login()
        {
                connect();
                frame();
        }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
            new login();            
            System.out.print("Hello db");    
    }

    private void connect() {
        
        try {
                String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
/*你可以使用Class的靜態forName()方法實現動態加載類別
透過java.lang.Class類別的forName()來載入並向DriverManager註冊JDBC
驅動程式(驅動程式會自動透過 DriverManager.registerDriver()方法註冊)*/

                Class.forName(driver);
                String db="jdbc:odbc:db1";
/*要連線資料庫,我們可以從DriverManager要求並取得Connection物件,它代表資
 料庫連線物件*/
                Conn=DriverManager.getConnection(db);
                st=Conn.createStatement();                              
                } catch (ClassNotFoundException | SQLException ex) {
                }       
         }

    private void frame() {
            f.setSize(180,200);            

            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
            p.add(l);
            p.add(t);
            p.add(l1);
            p.add(t1);
            p.add(b);   
            f.add(p);
             b.addActionListener(
                     new ActionListener()
                     {
                                //實作
         public void actionPerformed(ActionEvent e) {
         String user=t.getText().trim();
         String pass=t.getText().trim();
         String sql="Select * from table1 Where user='"
         +user+"' and password='"+pass+"'"                                                    + ""; 
          try
          { rs=st.executeQuery(sql);  
            int count=0;
            while (rs.next())
            { count++;} 
          if (count==0)                      OptionPane.showMessageDialog(null,"Access denied","Login  Fail",3);                                                                                                       
           }catch(Exception ex) {}                                              
          }                                      
                     );       
}
}

Java 學習筆記~2維陣列變數


class Data
{
    // 宣告x2維陣列
    private  static int x[][]=new int[2][];
    private static double  w[]=new double [2];
    public static void setX(int[][] aX) { x = aX; }
    public static int[][] getX() {  return x;    }   
    public static double[] getW() {return w; }
    public static void setW(double[] aW) {w = aW;   }   
   
}
public class preceptron {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         //x 為一4x2 陣列
        int x[][]={{0,0},{0,1},{1,0},{1,1}};    
        double w[][]={{0.5,0.5}};      
        int i,j;       
        Data.setX(x);
        for (i=0;i<4;i++)
        {
             for (j=0;j<2;j++)  
                 System.out.print(Data.getX()[i][j]);
                 System.out.println();
        }

   /* Data.setW(w[0]);
    for (j=0;j<2;j++)
    System.out.println(Data.getW()[j]);    */
    }

}

Delphi 學習筆記偵測檔案夾的檔案個數


如何偵測檔案夾的檔案個數

function FileCount(filePath:string):integer;
var pathstr:string;
    sr: TSearchRec;
    FileAttrs: Integer;
begin
    pathstr:=GetCurrentDir;
    pathstr:=pathstr+'\sqlFile\*.*';
    Form1.Edit1.Text:=pathstr;
    FileAttrs := FileAttrs + faAnyFile;
    FileCount:=0;
    // FindFirst returns 0 if a file was successfully located, otherwise, it returns an //error code.

    if SysUtils.FindFirst('K:\torch\sqlFile\*.*', FileAttrs, sr) = 0 then
    begin
            with Form1.stringgrid1 do
            begin
                rowCount:=1;
                repeat
                if (sr.Attr and FileAttrs) = sr.Attr then
                begin
                   RowCount := RowCount + 1;
                   Cells[1,RowCount-1] := sr.Name;
                   Cells[2,RowCount-1] := IntToStr(sr.Size);
                   inc(FileCount);
                end;
//FindNext returns the next entry that matches the name and attributes specified in a //previous call to FindFirst. The search record must be one that was passed to FindFirst. //The return value is zero if the function was successful. Otherwise the return value is an //error code.            
    until FindNext(sr) <> 0;
            end;
    end;
end;

Delphi 學習筆記 指標


@』是一個運算子,放在變數前面,傳回該變數再記憶體所在之位置。@也可以傳回程序或函數的記憶體位置。『^』有兩種用法,放在型態前面表示要宣告一個指標變數。放在指標變數後面,則為一個運算子,會傳回指標變數所紀錄的記憶體位置的資料值。


ex:

var x,y:Integer;
    p:^Integer;
begin
    x:=17 ;
    p:=@x;
    y:=p^;    showmessage(inttostr(y));
end;

type PInteger=^Integer; //宣告指標形態
var R:Real;
    I:Integer;
    P:Pointer;          //宣告通用型指標變數
    PI:PInteger;
begin

    P:=@R;             //任何型態變數均可指派記憶體位置給p
    PI=Pinteger(P);    //轉換通用型態指標P為整數指標
    I:=PI^;
end;


Pointer型態為通用型態指標,因為指定任何型態資料的記憶體位址,可以利用多用途的指標型態進行強制的資料型態轉換


程序型態允許開發人員以處理變數數值的方式來處理程序和函數

function Max(x,y:Integer):Integer;
begin
    if x>y then result:=x
    else result:=y;

procedure TForm1.Button3Click(Sender: TObject);
var F:function(x,y:Integer):Integer;
begin
   F:=Max; //可以將函數Max 指定給F
   showmessage(inttostr(F(3,5)));
end;end;

共用資料Shared Preferences

共用資料類別是用來處理基本型別的key-value 成對名稱與資料,該類別建構的物件可以存放Int、float、boolean 及字串型別


取得SharedPreferences類別的方式有:
getSharedPreferences(String name,int mode); 呼叫該方法需傳入兩個參數;第一個參數為自訂的儲存資料檔案名稱,如果指定的檔案不存在,則會在實際進行存取動作時自動建立。第二個參數為指定的操作模式
MODE_PRIVATE 只有呼叫的應用程式可以存取
MODE_WORLD_READABLE(1):允許其他應用程式可以讀取已經建立的檔案
MODE_WORLD_WRITABLE(2):允許其他應用程式可以寫入已經建立的檔案
最後呼叫COMMIT() 方法將資料存放


main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".Main" >

<RelativeLayout
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" >

  <Button
      android:id="@+id/write"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="write"
      />
  <Button
      android:id="@+id/read"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_toRightOf="@id/write"
  android:text="read"
      />   
  </RelativeLayout>
  
   <TextView
       android:id="@+id/tv"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"  
       />

</LinearLayout>





Main.java
package com.example.myiotest1;

import java.io.File;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {

private Button write,read;
private TextView tv;
private  SharedPreferences sp;
private  SharedPreferences.Editor editor;
private File sdroot,approot,newfile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
write=(Button)findViewById(R.id.write);
read=(Button)findViewById(R.id.read);
tv=(TextView)findViewById(R.id.tv);
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sp=getSharedPreferences("mydata", MODE_PRIVATE);
editor=sp.edit();
editor.putString("user", "Jacky");
editor.putBoolean("Sound", true);
editor.putInt("Stage", 3);
editor.commit();
}
});

read.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sp=getSharedPreferences("mydata", MODE_PRIVATE);
editor=sp.edit();

tv.append(" "+sp.getInt("stage", 0));
tv.append(sp.getBoolean("Sound", true)?"true":"false");
tv.append(sp.getString("user", "who") );

}
});


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}