2015年11月30日 星期一

Eclipse : JNDI建立 use DB2 DataBase

1.
META-INF/context.xml

<Context>

   <Resource  name="jdbc/dbname" auth="Container" type="javax.sql.DataSource"
               maxTotal="100" maxIdle="30" maxWaitMillis="15000"
               username="name" password="pw" driverClassName="com.ibm.db2.jcc.DB2Driver"
               url="jdbc:db2://10.10.10.10:50000/dbname"/>

</Context>

2.
WEB-INF/web.xml

<web-app >

 <resource-ref>
     <description>dbname connect description</description>
     <res-ref-name>jdbc/dbname</res-ref-name>
     <res-type>javax.sql.DataSource</res-type>
     <res-auth>Container</res-auth>
   </resource-ref>

</web-app>

3.
JSP page

<%
        Context initContext  = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource dataSource = (DataSource)envContext.lookup("jdbc/dbname");

Connection con = dataSource.getConnection();
Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM  DB");
%>

2015年9月10日 星期四

Java : Email setting

boolean sessionDebug = false;
InternetAddress[] address;

//設定所要用的Mail伺服器和所使用的傳輸協定
java.util.Properties props = System.getProperties();
props.put("mail.host","202.203.201.11");
props.put("mail.transport.protocol","smtp");

//產生新的maill session
javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(props,null);
mailSession.setDebug(sessionDebug);
MimeMessage msg = new MimeMessage(mailSession);

//設定傳送郵件的發信人
msg.setFrom(new InternetAddress("ccccxxx@gmail.com","USERNAME"));

//設定收信人的信箱
address = InternetAddress.parse(sendmail,false);
msg.setRecipients(Message.RecipientType.TO, address);

//設定郵件主題
msg.setSubject(sub,"BIG5");

//設定發信時間
msg.setSentDate(new java.util.Date());

//設定郵件內容
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();

//設定傳送信的MIME Type
mbp.setContent(message,"text/html;charset=Big5");
mp.addBodyPart(mbp);
msg.setContent(mp);

//傳送郵件
Transport.send(msg);

Html : 列印跨頁(pinrt automatic page spread)

<P style='page-break-after:always'>

Java : 讀取目錄下所有CSV檔案內資料 (get all CSV date in same folder)

public class csv {

public static void main(String[] args)
{

FileReader fr = null;

  File dir = new File("F:/log");
  File[] files = dir.listFiles();

  try
  {
    if(files != null)
    {
        for (int i = 0; i < files.length; i++)
      {

        String filePath = files[i].getAbsolutePath().toLowerCase().trim();
        String filename=files[i].getName();

        int startIndex = filename.lastIndexOf('.') + 1;

        String  fcsv = filename.substring(startIndex);
      System.out.println( "fcsv    :"+fcsv );

        if(fcsv.equals("csv"))
        {

          System.out.println(filePath);
          System.out.println( "filesName():"+filename );

          fr = new FileReader(filePath);

            //放到BufferedReader一筆筆讀出
          BufferedReader br = new BufferedReader(fr);

          ArrayList taglist = new ArrayList(getTagList(br));

          for(int k=0; k<taglist.size(); k++)
           {

            System.out.println( k+":" );
            System.out.println(  ((String[])taglist.get(k))[0]);
            System.out.println(  ((String[])taglist.get(k))[1]);
             System.out.println(  ((String[])taglist.get(k))[2]);
            System.out.println(  ((String[])taglist.get(k))[3]);
            System.out.println( "--------" );
            }

          br.close();
        }
        }

  }
} catch (Exception e) {
    e.printStackTrace();
}

}

  public static ArrayList getTagList (BufferedReader br)
  {
    ArrayList taglist = new ArrayList();
    String sData = null;
    try
    {

      while ((sData = br.readLine()) != null)
      {
        String strArray[] = sData.split(",");
        taglist.add(strArray);
      }
    }
    catch (Exception e){
      e.printStackTrace();
    }
    return taglist;
  }
}

Java : 連結DB2資料庫(connect to DB2 database)

public class connectDb2{

public static void main(String[] args) throws Exception
{

DB_URL = "jdbc:db2://10.10.10.18/XXX";
Class.forName("com.ibm.db2.jcc.DB2Driver");
conn = DriverManager.getConnection(DB_URL, "USER", "PW");

//select
      PreparedStatement preStmt = conn.prepareStatement("Select * from DB2DATA");
ResultSet rs = preStmt.executeQuery();

if(rs.next())
{
String no = rs.getString("NO").toString();
}

//insert
PreparedStatement  preStmt = conn.prepareStatement("insert into DB2DATA");
preStmt.execute();

}

}

Java : 連結access資料庫(connect to MS access database)

public class connectAccess{

public static void main(String[] args) throws Exception
{
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      //access 路徑
      String str1="jdbc:odbc:DRIVER=Microsoft Access Driver(*.mdb);DBQ=C:/acc.mdb";

      Connection conn=DriverManager.getConnection(str1,"","");
      Statement stmt = conn.createStatement();
      ResultSet rs;

      try
     {
         //select
         rs = stmt.executeQuery("select *  from  data" );
         while(rs.next())
         {
            String no=rs.getString("NO").toString();
         }
       
         //insert
         stmt.executeUpdate("insert into data");
       
         //update
         stmt.executeUpdate("update data set NO=''");

      } catch (Exception e) {
         e.printStackTrace();
     }finally{
          stmt.close();
          conn.close();
      }
}

}

2015年3月25日 星期三

JavaScript : E-mail格式檢核 (E-mail format check)

function checkEmail(mail)
{
if(mail.value!="")
        {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail.value))
                {
return;
                 }
        alert("E-mail不正確");
        mail.value="";
}
}

jQuery : 判斷radio有無選取 (check radio type is checked)

html

<input id="labt1" type="radio" name="LABTYPE" name="LAB" value="1" >LAB1
<input id="labt2" type="radio" name="LABTYPE" name="LAB" value="2" >LAB2


--------------------------------------------

JavaScript

if(typeof($("input[name=LABTYPE]:checked").val()) === "undefined" )
{
alert("請選擇LAB");
return false;
}

jQuery : 判斷html text不可空白 (check html input tag value not null)

html

<form id="FROMTAG" name="form1" method="post">
<input type="text">

----------------------------------------------------------------

JavaScript

$("#FROMTAG").find(':input').each(function()
{
var ty = this.type;
var val = $(this).val();

if(ty=="text" && val=="")
{
alert("欄位不可空白");
return false;
}
});

2015年3月24日 星期二

jQuery : Ajax html

var div
var organ

$.ajax({
url: '/html/text/pages/Mean.jsp',
dataType: 'html',
type:'POST',
async:false,
data: { No: div, Size: organ },

error: function(xhr) {
alert('Ajax request 發生錯誤');
},
success: function(response) {
$("#ID").html($.trim(response));
        }
});

2015年3月19日 星期四

Jsp : 轉成csv (download csv)

<%@ page language="java" contentType="text/html; charset=BIG5" %>
<%@ page import="java.util.*" %>

<%
        ArrayList list = new ArrayList();

list =  from select database data (use map in list)
 
  String filename = "test.csv";

response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
out.clear();

        out.write("COM1NAME,COM2NAME");

out.newLine();

if(list.size()>0 )
{
for(int i=0; i<list.size(); i++)
{
HashMap map = (HashMap)list.get(i);

out.write(map.get("COM1")+","+map.get("COM2") );
out.newLine();
}
}

%>

2015年1月6日 星期二

DB2 : 補0(padding 0)

price type is number

right(digits(price),10)

or

right(digits(cast(price as bigint)),14)