亚洲VA中文字幕无码一二三区,亚洲春色在线视频,老司机亚洲精品影视wwwhttp://www.tkk7.com/tinguo002/category/52098.html<script async src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- iteye 460 60 --> <ins class="adsbygoogle" style="display:inline-block;width:468px;height:60px" data-ad-client="ca-pub-2876867208357149" data-ad-slot="0418982663"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> zh-cnFri, 07 Nov 2014 14:49:30 GMTFri, 07 Nov 2014 14:49:30 GMT60Linux 下配置 JDK 環境變量http://www.tkk7.com/tinguo002/archive/2014/08/25/417314.html一堣而安一堣而安Mon, 25 Aug 2014 13:38:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/08/25/417314.htmlhttp://www.tkk7.com/tinguo002/comments/417314.htmlhttp://www.tkk7.com/tinguo002/archive/2014/08/25/417314.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/417314.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/417314.html介紹在linux下配置jdk環境變量的幾種常用方法。

首先在linux下安裝jdk,如果出現提示權限不夠(且root下也提示權限不夠),可用#ls -l filename命令查看一下,如果顯示類似如:

-rw-rw-rw- 1 root root ….

則表示任何用戶都沒有可執行權限(即使是root用戶)。

解決方法:

#chmod a+x filename

這樣,安裝好后,就可以接下來進行環境變量的配置了。這里給出三種可選方法:

一、修改/etc/profile文件

當本機僅僅作為開發使用時推薦使用這種方法,因為此種配置時所有用戶的shell都有權使用這些環境變量,可能會給系統帶來安全性問題。

用文本編輯器打開/etc/profile,在profile文件末尾加入:

JAVA_HOME=/usr/share/jdk1.5.0_05
PATH=$JAVA_HOME/bin:$PATH
CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export JAVA_HOME
export PATH
export CLASSPATH搜索

重新登錄即可。

二、修改.bashrc文件

這種方法更為安全,它可以把使用這些環境變量的權限控制到用戶級別,如果需要給某個用戶權限使用這些環境變量,只需要修改其個人用戶主目錄下的.bashrc文件就可以了。

用文本編輯器打開用戶目錄下的.bashrc文件,在.bashrc文件末尾加入:

set JAVA_HOME=/usr/share/jdk1.5.0_05
export JAVA_HOME
set PATH=$JAVA_HOME/bin:$PATH
export PATH
set CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export CLASSPATH

重新登錄。

三、直接在shell下設置變量

不推薦使用這種方法,因為換個shell,該設置就無效了。這種方法僅僅是臨時使用,以后要使用的時候又要重新設置,比較麻煩。

只需在shell終端執行下列命令:

export JAVA_HOME=/usr/share/jdk1.5.0_05
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar

注意:

1.要將 /usr/share/jdk1.5.0_05jdk 改為jdk安裝目錄
2. linux下用冒號”:”來分隔路徑
3. $PATH / $CLASSPATH / $JAVA_HOME 是用來引用原來的環境變量的值在設置環境變量時特別要注意不能把原來的值給覆蓋掉了。
4. CLASSPATH中當前目錄”.”不能丟掉。
5. export是把這三個變量導出為全局變量。
6. 大小寫必須嚴格區分。

一堣而安 2014-08-25 21:38 發表評論
]]>
圖片轉字符串 http://www.tkk7.com/tinguo002/archive/2014/08/05/416579.html一堣而安一堣而安Tue, 05 Aug 2014 03:30:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/08/05/416579.htmlhttp://www.tkk7.com/tinguo002/comments/416579.htmlhttp://www.tkk7.com/tinguo002/archive/2014/08/05/416579.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/416579.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/416579.htmlpackage com.apexsoft.mobile.utils;import java.io.FileInputStream;import java.io.Fil...  閱讀全文

一堣而安 2014-08-05 11:30 發表評論
]]>
java中InputStream轉化為byte[]數組 http://www.tkk7.com/tinguo002/archive/2014/08/04/416551.html一堣而安一堣而安Mon, 04 Aug 2014 13:12:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/08/04/416551.htmlhttp://www.tkk7.com/tinguo002/comments/416551.htmlhttp://www.tkk7.com/tinguo002/archive/2014/08/04/416551.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/416551.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/416551.html在commons-io包中org.apache.commons.io.IOUtils類的toByteArray(InputStream input)已經有實現了,我們可以參考下思路,完成我們的方法,我們可以用類似下面的代碼實現inputStream轉化為byte[]數組
public static byte[] toByteArray(InputStream input) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];
    int n = 0;
    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
    }
    return output.toByteArray();
}

下面是IOUtils中摘錄出與toByteArray相關的方法

org.apache.commons.io.IOUtils.toByteArray

方法如下:
public static byte[] toByteArray(InputStream input)
  throws IOException
{
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  copy(input, output);
  return output.toByteArray();
}

public static int copy(InputStream input, OutputStream output)
  throws IOException
{
  long count = copyLarge(input, output);
  if (count > 2147483647L) {
    return -1;
  }
  return (int)count;
}

public static long copyLarge(InputStream input, OutputStream output)
  throws IOException
{
  byte[] buffer = new byte[4096];
  long count = 0L;
  int n = 0;
  while (-1 != (n = input.read(buffer))) {
    output.write(buffer, 0, n);
    count += n;
  }
  return count;
}

文章詳細出處:http://blog.csdn.net/zdwzzu2006/article/details/7745827


一堣而安 2014-08-04 21:12 發表評論
]]>
tomcat虛擬目錄配置 http://www.tkk7.com/tinguo002/archive/2014/08/04/416549.html一堣而安一堣而安Mon, 04 Aug 2014 12:57:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/08/04/416549.htmlhttp://www.tkk7.com/tinguo002/comments/416549.htmlhttp://www.tkk7.com/tinguo002/archive/2014/08/04/416549.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/416549.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/416549.htmlTomcat6.0虛擬目錄配置[]
設虛擬目錄 "site",通過 http://localhost:8080/site 訪問物理路徑 D:"site 文件夾里面的內容。設置過程如下:
1.
復制 Tomcat6.0"webapps"ROOT 目錄下的 WEB-INF 文件夾到 D:"site 目錄下。
2.
打開 D:"site"WEB-INF 目錄下的 web.xml 文件, </description> 之后加入:
<!--JSPC servlet mappings start -->
<!--JSPC servlet mappings end -->
3.
打開 Tomcat6.0"conf"server.xml 文件,在 <Host> </Host> 之間加入:
<Context path="/site" docBase="d:"site"></Context>
path="/site"
就是虛擬目錄的名稱
docBase="d:"site">
為物理路徑
4.
打開 Tomcat6.0"conf"web.xml 文件,找到:
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
false設成true保存,重啟Tomcat,現在就可以應用 http://localhost:8080/site 虛擬目錄了。

Tomcat6設置虛擬目錄的方法, 不修改server.xml


tomcat文件夾的conf"catalina"localhost(對于Tomcat6版本及其以上,需要自己創建catalinalocalhost這兩個文件夾)

增加project .xml文件(該文件名的project要和下面的“path=“/xxx"”xxx相同)

文件內容:

<Context path="/project" reloadable="true" docBase="E:"javastudio"oob" workDir="E:"javastudio"oob"work" />


docBase
是項目文件夾的web-inf文件夾的上一層目錄
workDir
是指Tomcat解析Jsp轉換為Java文件,并編譯為class存放的文件夾,設置在項目文件夾里面,可以避免移植到其他地方首次讀取jsp文件需要重新解析 。一般格式:項目文件夾"work
reloadable
是指可以重新加載,一般設置為true,方便使用,不需要經常重啟Tomcat
 

以后啟動Tomcat,在瀏覽器輸入http://localhost:8080/project就能訪問
該項目的welcome文件。

轉:TomCat 6.0虛擬目錄配置!20080309 星期日 13:51之前在5.0下配置虛擬目錄,我一般是采用在conf"server.xml中增加<Context .../>的方法,可是此法在6.0中失效(后經驗證有效,可能是之前實驗過程中有誤)。按照tomcat 6.0啟動之后的相關文檔的說明http://localhost:8080/docs/config/context.html,嘗試了一些方法:

-----------------------------tomcat6.0文檔中關于Context的說明-------------------
You may define as many Context elements as you wish. Each such Context MUST have a unique context path. In addition, a Context must be present with a context path equal to a zero-length string. This Context becomes the default web application for this virtual host, and is used to process all requests that do not match any other Context's context path.

For Tomcat 6, unlike Tomcat 4.x, it is NOT recommended to place <Context> elements directly in the server.xml file. This is because it makes modifing the Context configuration more invasive since the main conf/server.xml file cannot be reloaded without restarting Tomcat.


Context elements may be explicitly defined:

in the $CATALINA_HOME/conf/context.xml file: the Context element information will be loaded by all webapps
in the $CATALINA_HOME/conf/[enginename]/[hostname]/context.xml.default file: the Context element information will be loaded by all webapps of that host
in individual files (with a ".xml" extension) in the $CATALINA_HOME/conf/[enginename]/[hostname]/ directory. The name of the file (less the .xml) extension will be used as the context path. Multi-level context paths may be defined using #, e.g. context#path.xml. The default web application may be defined by using a file called ROOT.xml.
if the previous file was not found for this application, in an individual file at /META-INF/context.xml inside the application files
inside a Host element in the main conf/server.xml
-------------------------------------------------------------------------------

逐一驗證,方法12均無效,成功的有以下2種:(下文用%tomcat%表示Tomcat6.0的安裝目錄,希望在瀏覽器中通過http://localhost:8080/abc/default.jsp 來訪問d:"myJsp"default.jsp)

方法一:(文檔中說不建議使用)

找到%tomcat%"conf"server.xml,在</Host>之前加入:
<Context docBase="d:"myJsp" path="/abc" />
保存文件之后,重啟Tomcat即可。注意:大小寫不能錯! 斜桿"/""""的方向別搞錯。

方法二:該方法推薦使用,比較簡單。

%tomcat%"conf"Catalina"locahost(該目錄可能需要手工創建)下新建一個文件abc.xml,注意文件名中的abc就表示虛擬目錄的名稱,所以不可隨意命名,該文件的內容為:
<Context docBase="d:"myJsp" />
重啟Tomcat即可。

-------------------------------------------------------------------------------------------
其它設置:當url中未明確指定文件名時,是否列出相關目錄下所有文件的開關設置:

打開 %tomcat%"conf"web.xml 文件,找到:
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
false改成true即可。

-------------------------------------------------------------------------------------------
其他人的同類經驗:http://fengzhiyu-sh.javaeye.com/blog/153506 經驗證無需設置文中的web application下的web.xml文件。


文章詳細參考:http://www.cnblogs.com/bingoidea/archive/2009/06/06/1497787.html

一堣而安 2014-08-04 20:57 發表評論
]]>
Tomcat的窗口名稱修改http://www.tkk7.com/tinguo002/archive/2014/08/04/416548.html一堣而安一堣而安Mon, 04 Aug 2014 12:56:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/08/04/416548.htmlhttp://www.tkk7.com/tinguo002/comments/416548.htmlhttp://www.tkk7.com/tinguo002/archive/2014/08/04/416548.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/416548.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/416548.htmlcatalina.bat

找到下面的東東:


:doStart
shift
if not "%OS%" == "Windows_NT" goto noTitle
set _EXECJAVA=start "Tomcat" %_RUNJAVA%
goto gotTitle

修改紅色部分

一堣而安 2014-08-04 20:56 發表評論
]]>
java下載網頁內容和網絡圖片 http://www.tkk7.com/tinguo002/archive/2014/08/04/416542.html一堣而安一堣而安Mon, 04 Aug 2014 10:38:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/08/04/416542.htmlhttp://www.tkk7.com/tinguo002/comments/416542.htmlhttp://www.tkk7.com/tinguo002/archive/2014/08/04/416542.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/416542.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/416542.htmlimport java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlResource {

    
public static void main(String[] args){
        
try {
            System.out.println(UrlResource.getUrlDetail(
"http://www.baidu.com",true));
            saveUrlFile(
"http://www.baidu.com/img/baidu_jgylogo3.gif""D:\\1.gif");
        }
 catch (Exception e) {
            e.printStackTrace();
        }

    }

    
    
//獲取網絡文件,轉存到fileDes中,fileDes需要帶文件后綴名
    public static void saveUrlFile(String fileUrl,String fileDes) throws Exception
    
{
        File toFile 
= new File(fileDes);
        
if (toFile.exists())
        
{
//            throw new Exception("file exist");
            return;
        }

        toFile.createNewFile();
        FileOutputStream outImgStream 
= new FileOutputStream(toFile);
        outImgStream.write(getUrlFileData(fileUrl));
        outImgStream.close();
    }

    
    
//獲取鏈接地址文件的byte數據
    public static byte[] getUrlFileData(String fileUrl) throws Exception
    
{
        URL url 
= new URL(fileUrl);
        HttpURLConnection httpConn 
= (HttpURLConnection) url.openConnection();
        httpConn.connect();
        InputStream cin 
= httpConn.getInputStream();
        ByteArrayOutputStream outStream 
= new ByteArrayOutputStream();
        
byte[] buffer = new byte[1024];
        
int len = 0;
        
while ((len = cin.read(buffer)) != -1{
            outStream.write(buffer, 
0, len);
        }

        cin.close();
        
byte[] fileData = outStream.toByteArray();
        outStream.close();
        
return fileData;
    }

    
    
//獲取鏈接地址的字符數據,wichSep是否換行標記
    public static String getUrlDetail(String urlStr,boolean withSep) throws Exception
    
{
        URL url 
= new URL(urlStr);
        HttpURLConnection httpConn 
= (HttpURLConnection)url.openConnection();
        httpConn.connect();
        InputStream cin 
= httpConn.getInputStream();
        BufferedReader reader 
= new BufferedReader(new InputStreamReader(cin,"UTF-8"));
        StringBuffer sb 
= new StringBuffer();
        String rl 
= null;
        
while((rl = reader.readLine()) != null)
        
{
            
if (withSep)
            
{
                sb.append(rl).append(System.getProperty(
"line.separator"));
            }

            
else
            
{
                sb.append(rl);
            }

        }

        
return sb.toString();
    }

    
}

// 禁止圖像緩存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);


文章詳細參考:http://blog.csdn.net/pandakong/article/details/7430844


一堣而安 2014-08-04 18:38 發表評論
]]>
redis使用http://www.tkk7.com/tinguo002/archive/2014/07/30/416340.html一堣而安一堣而安Wed, 30 Jul 2014 04:13:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/07/30/416340.htmlhttp://www.tkk7.com/tinguo002/comments/416340.htmlhttp://www.tkk7.com/tinguo002/archive/2014/07/30/416340.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/416340.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/416340.html

閱讀

 


下載的windows版本是redis-2.0.2,解壓到D盤下:

D:\redis-2.0.2


進到該目錄下,有下列文件:

 redis-server.exe:服務程序

   redis-check-dump.exe:本地數據庫檢查

   redis-check-aof.exe:更新日志檢查

   redis-benchmark.exe:性能測試,用以模擬同時由N個客戶端發送M個 SETs/GETs 查詢 (類似于 Apache 的ab 工具).


啟動Redis服務(conf文件指定配置文件,若不指定則默認):

D:\redis-2.0.2>redis-server.exe redis.conf



啟動cmd窗口要一直開著,關閉后則Redis服務關閉

這時服務開啟著,另外開一個窗口進行,設置客戶端:

D:\redis-2.0.2>redis-cli.exe -h 202.117.16.133 -p 6379

然后可以開始玩了:



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

 

Redis提供了多種語言的客戶端,包括Java,C++,python。

 

Redis官網上推薦的Java包是Jedis,去下載Jedis,在Java項目中導入Jedis包,開始發現有錯誤,是因為缺少org.apache.commons這個包,

去網上找此包,下載導入后,Jedis就沒有錯誤了。


可以開始了,用Jedis來操作Redis:






http://www.cnblogs.com/kkgreen/archive/2011/11/09/2243554.htm




你的
redis在真實環境中不可以誰想訪問就訪問,所以,必須要設置密碼。

設置密碼的步驟如下:

<!--[if !supportLists]-->1.       <!--[endif]-->修改redis.conf文件配置

 

root@ubuntu:/usr/local/redis-2.4.14#  vim redis.conf

#  requirepass foobared去掉注釋,foobared改為自己的密碼,我在這里改為123456

requirepass  123456

 

<!--[if !supportLists]-->2.       <!--[endif]-->啟動服務

 

root@ubuntu:/usr/local/redis-2.4.14# ./src/redis-server redis.conf

 

<!--[if !supportLists]-->3.       <!--[endif]-->客戶端連接

 

naxsu@ubuntu:/usr/local/redis-2.4.14$ ./src/redis-cli

redis 127.0.0.1:6379> get a

(error) ERR operation not permitted

redis 127.0.0.1:6379>

提示沒有權限

naxsu@ubuntu:/usr/local/redis-2.4.14$ ./src/redis-cli -a 123456

redis 127.0.0.1:6379> get a

"b"

 

到此說明設置密碼有效了。

設置隨機啟動

在服務器上,你每次重啟機器后再去啟動redis的服務,這是很麻煩的,所以將Redis作為 Linux 服務隨機啟動是很有必要的。

修改/etc/rc.local文件

 

root@ubuntu:/usr/local/redis-2.4.14# vim /etc/rc.local

 

在最后加入下面一行代碼

 

./usr/local/redis-2.4.14/src/redis-server /usr/local/redis-2.4.14/redis.conf

 

重啟機器看看效果

 

根據我的測試,設置是成功的。

l

文章詳細參考:

http://www.iteye.com/topic/1124400

一堣而安 2014-07-30 12:13 發表評論
]]>
java request 獲取域名http://www.tkk7.com/tinguo002/archive/2014/07/23/416121.html一堣而安一堣而安Wed, 23 Jul 2014 03:44:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/07/23/416121.htmlhttp://www.tkk7.com/tinguo002/comments/416121.htmlhttp://www.tkk7.com/tinguo002/archive/2014/07/23/416121.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/416121.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/416121.html獲取域名,如:http://f0rb.iteye.com/


獲取帶部署環境上下文的域名,如: http://www.iteye.com/admin/

StringBuffer url = request.getRequestURL();  

String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();  

文章詳細參考:http://f0rb.iteye.com/blog/1253746



一堣而安 2014-07-23 11:44 發表評論
]]>
JAVA反射機制,把JavaBean屬性轉成字符串http://www.tkk7.com/tinguo002/archive/2014/07/22/416089.html一堣而安一堣而安Tue, 22 Jul 2014 07:14:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/07/22/416089.htmlhttp://www.tkk7.com/tinguo002/comments/416089.htmlhttp://www.tkk7.com/tinguo002/archive/2014/07/22/416089.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/416089.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/416089.htmlpackage com.jetsum.util;import java.io.StringReader;import java.lang.reflect.Field;impo...  閱讀全文

一堣而安 2014-07-22 15:14 發表評論
]]>
Java String轉Float精度不準確問題http://www.tkk7.com/tinguo002/archive/2014/07/21/416058.html一堣而安一堣而安Mon, 21 Jul 2014 11:39:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/07/21/416058.htmlhttp://www.tkk7.com/tinguo002/comments/416058.htmlhttp://www.tkk7.com/tinguo002/archive/2014/07/21/416058.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/416058.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/416058.htmlBigDecimal b1 = new BigDecimal(floatValStr );
BigDecimal b2 = new BigDecimal(100);
dqll = b1.multiply(b2).toString();    //4.5*100

有關BigDecimal  api參考:
http://blog.sina.com.cn/s/blog_6a0cd5e501011soa.html

一堣而安 2014-07-21 19:39 發表評論
]]>
java.net.SocketException: Connection reset 解決方法http://www.tkk7.com/tinguo002/archive/2014/06/27/415170.html一堣而安一堣而安Fri, 27 Jun 2014 03:43:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/06/27/415170.htmlhttp://www.tkk7.com/tinguo002/comments/415170.htmlhttp://www.tkk7.com/tinguo002/archive/2014/06/27/415170.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/415170.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/415170.htmlhttp://www.cnblogs.com/zmc/p/3295761.html

當數據庫連接池中的連接被創建而長時間不使用的情況下,該連接會自動回收并失效,但客戶端并不知道,在進行數據庫操作時仍然使用的是無效的數據庫連接,這樣,就導致客戶端程序報“ java.sql.SQLException: Io 異常: Connection reset” 或“java.sql.SQLException 關閉的連接”異常。


解決辦法:客戶端在使用一個無效的連接時會先對該連接進行測試,如果發現該連接已經無效,則重新從連接池獲取有效數據庫連接來使用。

在tomcat的context.xml里面設置數據源時候可參考:

 <Resource auth="Container"
  driverClassName="oracle.jdbc.OracleDriver"
  type="javax.sql.DataSource"
  url="jdbc:oracle:thin:@11.11.11.45:1521:orcl"
  name="jdbc/login"
  username="login"
  password="login"
  maxActive="15"
  maxIdle="10"
  maxWait="-1"
  minIdle="2"
  removeAbandonedTimeout="5"
  testOnBorrow="true"
  testWhileIdle="true"
  testOnReturn="true"
  removeAbandoned="true"
  logAbandoned="true"
  validationQuery="select 1 from dual"
 /> 
 
 
參考:http://www.cnblogs.com/younes/archive/2012/06/01/2529483.html




DBCP數據庫連接失效的解決方法(Io 異常:Connection reset)


網上很多評論說DBCP有很多BUG,但是都沒有指明是什么BUG,只有一部分人說數據庫如果因為某種原因斷掉后再DBCP取道的連接都是失效的連接,而沒有重新取。有的時候會報Io 異常:Connection reset。

解決方法:

spring中datasource的配置如下:
    <bean id="dispatchdataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:myserver" />
    <property name="username" value="user1" />
    <property name="password" value="pwd" />
    <property name="maxActive" value="10000" />
    <property name="maxIdle" value="30" />
     <property name="minIdle" value="2" />
    <property name="maxWait" value="600000" />
    <property name="testOnBorrow" value="true"/>
    <property name="testWhileIdle" value="true"/>
    <property name="validationQuery" value="select 1 from dual"/>
</bean>

 

分析:

DBCP使用apache的對象池ObjectPool作為連接池的實現,有以下主要的方法

Object borrowObject() throws Exception;從對象池取得一個有效對象

void returnObject(Object obj) throws Exception;使用完的對象放回對象池

void invalidateObject(Object obj) throws Exception;使對象失效

void addObject() throws Exception;生成一個新對象


ObjectPool的一個實現就是GenericObjectPool,這個類使用對象工廠PoolableObjectFactory實現對象的生成,失效檢查等等功能,以其實現數據庫連接工廠PoolableConnectionFactory做以說明,主要方法:

     Object makeObject() throws Exception; 使用ConnectionFactory生成新連接

     void destroyObject(Object obj) throws Exception;關閉連接

     boolean validateObject(Object obj); 驗證連接是否有效,如果_validationQuery不空,則使用該屬性作為驗證連接是否有效的sql語句,查詢數據庫

     void activateObject(Object obj) throws Exception;激活連接對象

     void passivateObject(Object obj) throws Exception; 關閉連接生成過的Statement和ResultSet,使連接處于非活動狀態

    而GenericObjectPool有幾個主要屬性

     _timeBetweenEvictionRunsMillis:失效檢查線程運行時間間隔,默認-1

     _maxIdle:對象池中對象最大個數

     _minIdle:對象池中對象最小個數

     _maxActive:可以從對象池中取出的對象最大個數,為0則表示沒有限制,默認為8

     在構造GenericObjectPool時,會生成一個內嵌類Evictor,實現自Runnable接口。如果 _timeBetweenEvictionRunsMillis大于0,每過_timeBetweenEvictionRunsMillis毫秒 Evictor會調用evict()方法,檢查對象的閑置時間是否大于 _minEvictableIdleTimeMillis毫秒(_minEvictableIdleTimeMillis小于等于0時則忽略,默認為30 分鐘),是則銷毀此對象,否則就激活并校驗對象,然后調用ensureMinIdle方法檢查確保池中對象個數不小于_minIdle。在調用 returnObject方法把對象放回對象池,首先檢查該對象是否有效,然后調用PoolableObjectFactory 的passivateObject方法使對象處于非活動狀態。再檢查對象池中對象個數是否小于_maxIdle,是則可以把此對象放回對象池,否則銷毀此對象。

     還有幾個很重要的屬性,_testOnBorrow、_testOnReturn、_testWhileIdle,這些屬性的意義是取得、返回對象和空閑時是否進行驗證,檢查對象是否有效,默認都為false即不驗證。所以當使用DBCP時,數據庫連接因為某種原因斷掉后,再從連接池中取得連接又不進行驗證,這時取得的連接實際已經時無效的數據庫連接了。網上很多說 DBCP的bug應該都是如此吧,只有把這些屬性設為true,再提供_validationQuery語句就可以保證數據庫連接始終有效了,oracle數據庫可以使用SELECT COUNT(*) FROM DUAL,不過DBCP要求_validationQuery語句查詢的記錄集必須不為空,可能這也可以算一個小小的BUG,其實只要_validationQuery語句執行通過就可以了。

參考:http://hi.baidu.com/dobodo/item/7d95e3384d181cc4392ffab5



Tomcat Resource可配置的屬性






一堣而安 2014-06-27 11:43 發表評論
]]>
web 打印http://www.tkk7.com/tinguo002/archive/2014/06/26/415154.html一堣而安一堣而安Thu, 26 Jun 2014 06:40:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/06/26/415154.htmlhttp://www.tkk7.com/tinguo002/comments/415154.htmlhttp://www.tkk7.com/tinguo002/archive/2014/06/26/415154.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/415154.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/415154.htmlhttp://www.jb51.net/article/21444.htm
http://www.downdiy.com/kfyy/php/20140323/9e7b9b20201d3a49bb835efc2edc23d3.html  保持線條被打印



一堣而安 2014-06-26 14:40 發表評論
]]>
時間比較http://www.tkk7.com/tinguo002/archive/2014/05/26/414127.html一堣而安一堣而安Mon, 26 May 2014 09:47:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/05/26/414127.htmlhttp://www.tkk7.com/tinguo002/comments/414127.htmlhttp://www.tkk7.com/tinguo002/archive/2014/05/26/414127.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/414127.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/414127.html

import java.util.Date;
import java.text.ParseException;搜索
import java.text.SimpleDateFormat;

public class TimeCompare {

public static int Hour(Date time){
SimpleDateFormat st=new SimpleDateFormat("yyyyMMddHH");
return Integer.parseInt(st.format(time));
}

public static Date StringToDate(String s){
Date time=new Date();
SimpleDateFormat sd=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try{
time=sd.parse(s);
}
catch (ParseException e) {
System.out.println("輸入的日期格式有誤!");
}
return time;
}

public static void main(String[] args) {
String a="2012/01/01 18:08:20";
String b="2012/01/01 18:01:20";
String c="2012/01/02 01:01:01";
if(Hour(StringToDate(a))<=Hour(StringToDate(b))&&Hour(StringToDate(a))<Hour(StringToDate(c)))
System.out.println("成功");
else
System.out.println("失敗");
}
}


一堣而安 2014-05-26 17:47 發表評論
]]>
iframe應用session丟失的問題 http://www.tkk7.com/tinguo002/archive/2014/05/22/413994.html一堣而安一堣而安Thu, 22 May 2014 15:07:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/05/22/413994.htmlhttp://www.tkk7.com/tinguo002/comments/413994.htmlhttp://www.tkk7.com/tinguo002/archive/2014/05/22/413994.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/413994.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/413994.htmlhttp://www.cnblogs.com/fengqingtao/archive/2011/03/16/1986174.html

iframe應用session丟失的問題

在網站群的建設中,各子站需要共享主站的footer等公共信息。同時主站的后臺管理也集成了各子站的管理,采取的方式是使用iframe嵌入各站的頁面。在本機開發環境中,沒有出現任何的問題。但是一放到測試環境中,便遇到session丟失的問題。
        環境:應用服務器采用tomcat6.0,各個站點單獨使用一個應用服務器,部署在一臺物理服務器上。外部訪問采用同一個IP,但是不同的端口。
       起初以為,IE它的安全策略默認是會把iframe中的頁面站點認為是不可信任的,它會阻止該站點傳過來的cookie(如果你在iframe中的URL跳轉是用的localhost,則不會被阻擋),所以因為沒法使用cookie了,session便失效了。解決的方法是在過濾器,或者被嵌入的頁面內加入屬性為P3P的header信息。java為:response.addHeader("P3P","CP=CAO PSA OUR");但是依然沒有成功。網上的解決方案都是這么說,況且自己以前還弄過,都成功過,這次怎么弄都不好。
        今天腦子安靜下來,仔細的分析這里面的原因。如果是IE的安全限制,但是火狐、google瀏覽器沒有這樣的限制,為什么這兩個瀏覽器也出現這樣的情況。這肯定不僅僅和跨域引起的P3P的安全問題有關。于是在本機測試,通過iframe引入測試環境中的鏈接,設置了P3P,發現一切正常。這就更說明了,測試環境中的問題絕對不是P3P的問題了。而且使用了同一個IP,也應該沒有跨域的說法。那原因到底是什么呢?
        慢慢的,我將視線注意到了端口上。這些網站的訪問方式都是:同一IP+不同端口,難道和端口有關系。上網搜,關于這方面的內容太少了,但是總算在零星的資源中,找到了里面的原因。IP相同的兩個session對應的cookie是一樣的,而不幸的是sessionID就保存在cookie中,這樣先訪問A,再訪問B的時候,B的sessionid會覆蓋A的sessionid。這個事情沒辦法解決,所以你不要搞兩個端口,最好是搞兩個IP。原來都是cookie惹的禍,它不會區分端口,造成這多個站點不斷的后來的覆蓋前面的,從而造成session的丟失。問題解決了,將相互有引用的應用架構在不同的虛擬主機中,或者映射不同的IP。



一堣而安 2014-05-22 23:07 發表評論
]]>
Java DES 加密和解密源碼http://www.tkk7.com/tinguo002/archive/2014/05/13/413610.html一堣而安一堣而安Tue, 13 May 2014 09:19:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/05/13/413610.htmlhttp://www.tkk7.com/tinguo002/comments/413610.htmlhttp://www.tkk7.com/tinguo002/archive/2014/05/13/413610.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/413610.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/413610.html文章參考:http://www.oschina.net/code/snippet_727646_18383

Java密碼學結構設計遵循兩個原則:

1) 算法的獨立性和可靠性。

2) 實現的獨立性和相互作用性。

算法的獨立性是通過定義密碼服務類來獲得。用戶只需了解密碼算法的概念,而不用去關心如何實現這些概念。實現的獨立性和相互作用性通過密碼服務提供器來實現。密碼服務提供器是實現一個或多個密碼服務的一個或多個程序包。軟件開發商根據一定接口,將各種算法實現后,打包成一個提供器,用戶可以安裝不同的提供器。安裝和配置提供器,可將包含提供器的ZIPJAR文件放在CLASSPATH,再編輯Java安全屬性文件來設置定義一個提供器。


DES算法及如何利用DES算法加密和解密類文件的步驟

DES算法簡介
DESData Encryption Standard)是發明最早的最廣泛使用的分組對稱加密算法。DES算法的入口參數有三個:KeyDataMode。其中Key8個字節共64位,是DES算法的工作密鑰;Data也為8個字節64位,是要被加密或被解密的數據;ModeDES的工作方式,有兩種:加密或解密。

package com.afreon.util;

import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DesUtil {

    
private final static String DES = "DES";

    
public static void main(String[] args) throws Exception {
        String data 
= "123 456";
        String key 
= "wang!@#$%";
        System.err.println(encrypt(data, key));
        System.err.println(decrypt(encrypt(data, key), key));

    }

    
    
/**
     * Description 根據鍵值進行加密
     * 
@param data 
     * 
@param key  加密鍵byte數組
     * 
@return
     * 
@throws Exception
     
*/

    
public static String encrypt(String data, String key) throws Exception {
        
byte[] bt = encrypt(data.getBytes(), key.getBytes());
        String strs 
= new BASE64Encoder().encode(bt);
        
return strs;
    }


    
/**
     * Description 根據鍵值進行解密
     * 
@param data
     * 
@param key  加密鍵byte數組
     * 
@return
     * 
@throws IOException
     * 
@throws Exception
     
*/

    
public static String decrypt(String data, String key) throws IOException,
            Exception 
{
        
if (data == null)
            
return null;
        BASE64Decoder decoder 
= new BASE64Decoder();
        
byte[] buf = decoder.decodeBuffer(data);
        
byte[] bt = decrypt(buf,key.getBytes());
        
return new String(bt);
    }


    
/**
     * Description 根據鍵值進行加密
     * 
@param data
     * 
@param key  加密鍵byte數組
     * 
@return
     * 
@throws Exception
     
*/

    
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        
// 生成一個可信任的隨機數源
        SecureRandom sr = new SecureRandom();

        
// 從原始密鑰數據創建DESKeySpec對象
        DESKeySpec dks = new DESKeySpec(key);

        
// 創建一個密鑰工廠,然后用它把DESKeySpec轉換成SecretKey對象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey 
= keyFactory.generateSecret(dks);

        
// Cipher對象實際完成加密操作
        Cipher cipher = Cipher.getInstance(DES);

        
// 用密鑰初始化Cipher對象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        
return cipher.doFinal(data);
    }

    
    
    
/**
     * Description 根據鍵值進行解密
     * 
@param data
     * 
@param key  加密鍵byte數組
     * 
@return
     * 
@throws Exception
     
*/

    
private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        
// 生成一個可信任的隨機數源
        SecureRandom sr = new SecureRandom();

        
// 從原始密鑰數據創建DESKeySpec對象
        DESKeySpec dks = new DESKeySpec(key);

        
// 創建一個密鑰工廠,然后用它把DESKeySpec轉換成SecretKey對象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey 
= keyFactory.generateSecret(dks);

        
// Cipher對象實際完成解密操作
        Cipher cipher = Cipher.getInstance(DES);

        
// 用密鑰初始化Cipher對象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        
return cipher.doFinal(data);
    }

}






一堣而安 2014-05-13 17:19 發表評論
]]>
java.lang.NoClassDefFoundError: Could not initialize class 的原因http://www.tkk7.com/tinguo002/archive/2014/04/24/412883.html一堣而安一堣而安Thu, 24 Apr 2014 06:22:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/04/24/412883.htmlhttp://www.tkk7.com/tinguo002/comments/412883.htmlhttp://www.tkk7.com/tinguo002/archive/2014/04/24/412883.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/412883.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/412883.html解決辦法:通過myeclipse的 clean清除現有的class文件,重新編譯。或者從以前的備份中找到此class文件替換。
原因2:引入的jar包沖突導致。
解決辦法:baidu找一下,包沖突的事例。

一堣而安 2014-04-24 14:22 發表評論
]]>
java生成uuid(轉載)http://www.tkk7.com/tinguo002/archive/2014/04/16/412497.html一堣而安一堣而安Wed, 16 Apr 2014 01:07:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/04/16/412497.htmlhttp://www.tkk7.com/tinguo002/comments/412497.htmlhttp://www.tkk7.com/tinguo002/archive/2014/04/16/412497.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/412497.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/412497.htmlpublic class UniqId {      private static char[...  閱讀全文

一堣而安 2014-04-16 09:07 發表評論
]]>
Map、JavaBean、JSON的相互轉換 http://www.tkk7.com/tinguo002/archive/2014/04/12/412355.html一堣而安一堣而安Sat, 12 Apr 2014 09:24:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/04/12/412355.htmlhttp://www.tkk7.com/tinguo002/comments/412355.htmlhttp://www.tkk7.com/tinguo002/archive/2014/04/12/412355.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/412355.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/412355.htmlpackage com.suning.crawler.util; import java.lang.reflect.Method; import java...  閱讀全文

一堣而安 2014-04-12 17:24 發表評論
]]>
JQuery AJAX提交中文亂碼的解決方案http://www.tkk7.com/tinguo002/archive/2014/04/11/412328.html一堣而安一堣而安Fri, 11 Apr 2014 11:35:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/04/11/412328.htmlhttp://www.tkk7.com/tinguo002/comments/412328.htmlhttp://www.tkk7.com/tinguo002/archive/2014/04/11/412328.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/412328.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/412328.html要解決這個中文亂碼問題,就必須給AJAX異步提交指定顯 示的charset!
jQuery(form).ajaxSubmit({ 
    url: "ajax.aspx?a=memberlogin", 
    type: "post", 
    dataType: "json", 
    contentType: "application/x-www-form-urlencoded; charset=utf-8", 
    success: showLoginResponse
});
詳細出處參考:http://www.jb51.net/article/24097.htm


解決辦法2:
java代碼中,將response.setCharacterEncoding("UTF-8")放在action方法的最前面。
詳細出處參考:http://bbs.csdn.net/topics/360098992?page=1

一堣而安 2014-04-11 19:35 發表評論
]]>
java FTP Linux系統下 文件上傳下載http://www.tkk7.com/tinguo002/archive/2014/04/10/412256.html一堣而安一堣而安Thu, 10 Apr 2014 10:42:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/04/10/412256.htmlhttp://www.tkk7.com/tinguo002/comments/412256.htmlhttp://www.tkk7.com/tinguo002/archive/2014/04/10/412256.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/412256.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/412256.htmlimport java.io.Fil...  閱讀全文

一堣而安 2014-04-10 18:42 發表評論
]]>
sun.net.ftp異常 PORT 192,168,0,80,9,205: 550 Permission denied.http://www.tkk7.com/tinguo002/archive/2014/04/10/412224.html一堣而安一堣而安Thu, 10 Apr 2014 06:19:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/04/10/412224.htmlhttp://www.tkk7.com/tinguo002/comments/412224.htmlhttp://www.tkk7.com/tinguo002/archive/2014/04/10/412224.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/412224.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/412224.html

我使用sun.net.ftp來連接linux的vsftp時,出現如下的異常(在windows下是沒有的)

 

 

java.io.FileNotFoundException: PORT 192,168,0,80,9,205: 550 Permission denied.

 

at sun.net.ftp.FtpClient.readReply(FtpClient.java:236)

at sun.net.ftp.FtpClient.issueCommand(FtpClient.java:193)

at sun.net.ftp.FtpClient.openDataConnection(FtpClient.java:434)

at sun.net.ftp.FtpClient.put(FtpClient.java:594)

at org.lab24.util.FtpTool.processfile(FtpTool.java:193)

at org.lab24.util.FtpTool.upload(FtpTool.java:116)

at org.lab24.spider.Spider.run(Spider.java:55)

at EDU.oswego.cs.dl.util.concurrent.PooledExecutor$Worker.run(PooledExecutor.java:743)

at java.lang.Thread.run(Thread.java:619)

exception e in ftp upload(): java.io.FileNotFoundException: PORT 192,168,0,80,9,205: 550 Permission denied.

 

后來查過網上的解決方案,才知道:

該類默認使用的是Port模式傳輸數據,但實際上Linux配的是Pasv模式,所以傳不過去,修改辦法:

 

ftpclient.sendServer("quote PASV");
設置一下傳輸模式就可以傳了。

一堣而安 2014-04-10 14:19 發表評論
]]>
避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”異常http://www.tkk7.com/tinguo002/archive/2014/04/09/412161.html一堣而安一堣而安Wed, 09 Apr 2014 09:34:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/04/09/412161.htmlhttp://www.tkk7.com/tinguo002/comments/412161.htmlhttp://www.tkk7.com/tinguo002/archive/2014/04/09/412161.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/412161.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/412161.html/**解決辦法**
* 1添加一個方法
* 2調用這個方法生成一個新的httpClient對象
**/



import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpUtils
{
    
private HttpClient httpClient;
    
public HttpUtils()
    
{
        httpClient 
= null;
    }


    
public void openConnection()
    
{
        httpClient 
= new DefaultHttpClient();
      
  httpClient = getSecuredHttpClient(httpClient
    });
        


    
    
/**
     * 避免HttpClient的”SSLPeerUnverifiedException: peer not authenticated”異常
     * 不用導入SSL證書
     * 
     * 
@author shipengzhi(shipengzhi@sogou-inc.com)
     * 
     
*/

    
private static DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) {
        
final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
        
try {
            SSLContext ctx 
= SSLContext.getInstance("TLS");
            X509TrustManager tm 
= new X509TrustManager() {
                @Override
                
public X509Certificate[] getAcceptedIssuers() {
                    
return _AcceptedIssuers;
                }


                @Override
                
public void checkServerTrusted(X509Certificate[] chain,
                        String authType) 
throws CertificateException {
                }


                @Override
                
public void checkClientTrusted(X509Certificate[] chain,
                        String authType) 
throws CertificateException {
                }

            }
;
            ctx.init(
nullnew TrustManager[] { tm }new SecureRandom());
            SSLSocketFactory ssf 
= new SSLSocketFactory(ctx,
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm 
= httpClient.getConnectionManager();
            SchemeRegistry sr 
= ccm.getSchemeRegistry();
            sr.register(
new Scheme("https"443, ssf));
            
return new DefaultHttpClient(ccm, httpClient.getParams());
        }
 catch (Exception e) {
            System.out.println(
"=====:=====");
            e.printStackTrace();
        }

        
return null;
    }

}



一堣而安 2014-04-09 17:34 發表評論
]]>
string類型轉為double 值變化了http://www.tkk7.com/tinguo002/archive/2014/04/04/411961.html一堣而安一堣而安Fri, 04 Apr 2014 06:39:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/04/04/411961.htmlhttp://www.tkk7.com/tinguo002/comments/411961.htmlhttp://www.tkk7.com/tinguo002/archive/2014/04/04/411961.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/411961.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/411961.htmlhttp://zhidao.baidu.com/link?url=NeIRa5raPCZw7sR2DR1hzNk8aewMuNdDCNJ83qRMMWWfXaPVct7rWqVNWZnfkQAroEzRvKn5XxK4rK1lWEl2-_

精度的問題!用基本類型的double類型進行運算可能會丟失精度。而且特別大的數又沒法處理。所以如果用BigDecimal這個類問題就解決了。這個類在java.Math包下。它可以處理任意精度的數據。對于樓主出現的問題,我從新寫了段代碼,供樓主參考。但是主要是還得查看API!代碼如下:

import java.math.*;

public class oopp

{

 public static void 搜索main(String[] args)

 {

  String a="1467000000";

  double aa=Double.parseDouble(a);

  BigDecimal beichushu=new BigDecimal(aa);

  BigDecimal chushu=new BigDecimal(100000000);

  BigDecimal result=beichushu.divide(chushu,new MathContext(4));//MathConText(4)表示結果精確4位!

  boolean isTrue=String.valueOf(result).equals("14.67");

  System.out.println("1467000000除以100000000="+result);

  System.out.println(result+"與14.67比較的結果是"+isTrue);

 }

}





一堣而安 2014-04-04 14:39 發表評論
]]>
Tomcat啟動時一閃而過,看不到錯誤信息http://www.tkk7.com/tinguo002/archive/2014/04/04/411957.html一堣而安一堣而安Fri, 04 Apr 2014 06:21:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/04/04/411957.htmlhttp://www.tkk7.com/tinguo002/comments/411957.htmlhttp://www.tkk7.com/tinguo002/archive/2014/04/04/411957.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/411957.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/411957.htmlhttp://blog.163.com/kangle0925@126/blog/static/277581982011926102830712/

有時Tomcat的啟動窗口一閃而過,根本就看不出啟動過程中發生了什么錯誤。這中間的原因有好多種,最常見的解決辦法就是使用run命令,打開startup.bat文件,找到下面這行:

call "%EXECUTABLE%" start %CMD_LINE_ARGS%

修改為:

call "%EXECUTABLE%" run %CMD_LINE_ARGS%

這樣,Tomcat啟動時就不會彈出新窗口,就可以從容不迫地觀察這的啟動錯誤了。

修改文件后:需要從DOS命令行窗口進入到%TOMCAT_HOME%\bin路徑下,然后啟動startup.bat文件。

 

 Tomcat啟動時一閃而過,看不多錯誤信息 - Sky - Sky的博客



一堣而安 2014-04-04 14:21 發表評論
]]>
java日期http://www.tkk7.com/tinguo002/archive/2014/03/18/411194.html一堣而安一堣而安Tue, 18 Mar 2014 13:01:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/03/18/411194.htmlhttp://www.tkk7.com/tinguo002/comments/411194.htmlhttp://www.tkk7.com/tinguo002/archive/2014/03/18/411194.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/411194.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/411194.htmlhttp://blog.csdn.net/liwenfeng1022/article/details/6534176

//字符串日期加1天
       String sgrq = "20140101";
       SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
       try {
         Date d = formatter.parse(sgrq);
         String qxrq = formatter.format(d.getTime() + (1 * 24 * 60 * 60 * 1000));
       } catch (ParseException e) {      
         e.printStackTrace();
       }


1.用java.util.Calender來實現

   Calendar calendar=Calendar.getInstance();  
   calendar.setTime(new Date());
   System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//今天的日期
   calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//讓日期加1  
   System.out.println(calendar.get(Calendar.DATE));//加1之后的日期Top
===============================================================================

2.用java.text.SimpleDateFormat和java.util.Date來實現
          
    Date d=new Date();  
   SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");  
   System.out.println("今天的日期:"+df.format(d));  
   System.out.println("兩天前的日期:" + df.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000)));  
   System.out.println("三天后的日期:" + df.format(new Date(d.getTime() + 3 * 24 * 60 * 60 * 1000)));

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

GregorianCalendar gc=new GregorianCalendar();
gc.setTime(new Date);
gc.add(field,value);
value為正則往后,為負則往前
field取1加1年,取2加半年,取3加一季度,取4加一周
取5加一天....

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

/*
*java中對日期的加減操作
*gc.add(1,-1)表示年份減一.
*gc.add(2,-1)表示月份減一.
*gc.add(3.-1)表示周減一.
*gc.add(5,-1)表示天減一.
*以此類推應該可以精確的毫秒吧.沒有再試.大家可以試試.
*GregorianCalendar類的add(int field,int amount)方法表示年月日加減.
*field參數表示年,月.日等.
*amount參數表示要加減的數量.
*
* UseDate.java 測試如下:
*/
package temp.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
public class UseDate {

Date d=new Date();
GregorianCalendar gc =new GregorianCalendar();
SimpleDateFormat sf  =new SimpleDateFormat("yyyy-MM-dd");

public String getYears()
{
gc.setTime(d);
gc.add(1,+1);
gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));

return sf.format(gc.getTime());
}

public String getHalfYear()
{
gc.setTime(d);
gc.add(2,+6);
gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));

return sf.format(gc.getTime());
}
public String getQuarters()
{
gc.setTime(d);
gc.add(2,+3);
gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));

return sf.format(gc.getTime());
}

public String getLocalDate()
{
return sf.format(d);
}


public static  void  main(String[] args)
{
UseDate ud= new UseDate();
System.out.println(ud.getLocalDate());
System.out.println(ud.getYears());
System.out.println(ud.getHalfYear());
System.out.println(ud.getQuarters());
}

}
    //當月第一天和最后一天

     SimpleDateFormat sf  =new SimpleDateFormat("yyyyMMdd");
     Calendar a=Calendar.getInstance();
     int MaxDate=a.get(Calendar.DATE);
     System.out.println("該月最大天數:"+MaxDate+","+sf.format(a.getTime()));
     a.set(Calendar.DATE, 1);//把日期設置為當月第一天 
     System.out.println("當月第一天:"+sf.format(a.getTime())); 
     a.roll(Calendar.DATE, -1);//日期回滾一天,也就是最后一天

     System.out.println("當月最后一天:"+sf.format(a.getTime())); 

4 ,

GregorianCalendar gc=new GregorianCalendar();
       
        try {
            gc.setTime( new SimpleDateFormat("yyyyMM").parse("200901"));
            gc.add(2, -Integer.parseInt("7"));
        } catch (ParseException e) {
            // TODO 自動生成された catch ブロック
            e.printStackTrace();
        }
        System.out.println(new SimpleDateFormat("yyyyMM").format(gc.getTime()));

運行結果:200806



一堣而安 2014-03-18 21:01 發表評論
]]>
JAVA身份證驗證http://www.tkk7.com/tinguo002/archive/2014/02/27/410374.html一堣而安一堣而安Thu, 27 Feb 2014 02:45:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/02/27/410374.htmlhttp://www.tkk7.com/tinguo002/comments/410374.htmlhttp://www.tkk7.com/tinguo002/archive/2014/02/27/410374.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/410374.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/410374.htmlpublic class IDCard {

      private String _codeError;

      //wi =2(n-1)(mod 11)
      final int[] wi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1};
      // verify digit
      final int[] vi = {1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2};
      private int[] ai = new int[18];
      private static String[] _areaCode={"11","12","13","14","15","21","22"
          ,"23","31","32","33","34","35","36","37","41","42","43","44"
          ,"45","46","50","51","52","53","54","61","62","63","64","65","71","81","82","91"};
      private static HashMap<String,Integer> dateMap;
      private static HashMap<String,String> areaCodeMap;
      static{
            dateMap=new HashMap<String,Integer>();
            dateMap.put("01",31);
            dateMap.put("02",null);
            dateMap.put("03",31);
            dateMap.put("04",30);
            dateMap.put("05",31);
            dateMap.put("06",30);
            dateMap.put("07",31);
            dateMap.put("08",31);
            dateMap.put("09",30);
            dateMap.put("10",31);
            dateMap.put("11",30);
            dateMap.put("12",31);
            areaCodeMap=new HashMap<String,String>();
            for(String code:_areaCode){
                  areaCodeMap.put(code,null);
            }
      }

      //驗證身份證位數,15位和18位身份證
      public boolean verifyLength(String code){
            int length=code.length();
            if(length==15 || length==18){
                  return true;
            }else{
                  _codeError="錯誤:輸入的身份證號不是15位和18位的";
                  return false;
            }
      }

      //判斷地區碼
      public boolean verifyAreaCode(String code){
            String areaCode=code.substring(0,2);
//            Element child=  _areaCodeElement.getChild("_"+areaCode);
            if(areaCodeMap.containsKey(areaCode)){
                  return true;
            }else{
                  _codeError="錯誤:輸入的身份證號的地區碼(1-2位)["+areaCode+"]不符合中國行政區劃分代碼規定(GB/T2260-1999)";
                  return false;
            }
      }

      //判斷月份和日期
      public boolean verifyBirthdayCode(String code){
            //驗證月份
            String month=code.substring(10,12);
            boolean isEighteenCode=(18==code.length());
            if(!dateMap.containsKey(month)){
                  _codeError="錯誤:輸入的身份證號"+(isEighteenCode?"(11-12位)":"(9-10位)")+"不存在["+month+"]月份,不符合要求(GB/T7408)";
                  return false;
            }
            //驗證日期
            String dayCode=code.substring(12,14);
            Integer day=dateMap.get(month);
            String yearCode=code.substring(6,10);
            Integer year=Integer.valueOf(yearCode);

            //非2月的情況
            if(day!=null){
                  if(Integer.valueOf(dayCode)>day || Integer.valueOf(dayCode)<1){
                        _codeError="錯誤:輸入的身份證號"+(isEighteenCode?"(13-14位)":"(11-13位)")+"["+dayCode+"]號不符合小月1-30天大月1-31天的規定(GB/T7408)";
                        return false;
                  }
            }
            //2月的情況
            else{
                  //閏月的情況
                  if((year%4==0&&year%100!=0)||(year%400==0)){
                        if(Integer.valueOf(dayCode)>29 || Integer.valueOf(dayCode)<1){
                              _codeError="錯誤:輸入的身份證號"+(isEighteenCode?"(13-14位)":"(11-13位)")+"["+dayCode+"]號在"+year+"閏年的情況下未符合1-29號的規定(GB/T7408)";
                              return false;
                        }
                  }
                  //非閏月的情況
                  else{
                        if (Integer.valueOf(dayCode) > 28 || Integer.valueOf(dayCode) < 1) {
                              _codeError="錯誤:輸入的身份證號"+(isEighteenCode?"(13-14位)":"(11-13位)")+"["+dayCode+"]號在"+year+"平年的情況下未符合1-28號的規定(GB/T7408)";
                              return false;
                        }
                  }
            }
            return true;
      }

      //驗證身份除了最后位其他的是否包含字母
      public boolean containsAllNumber(String code) {
            String str="";
            if(code.length()==15){
                  str=code.substring(0,15);
            }else if(code.length()==18){
                  str=code.substring(0,17);
            }
            char[] ch = str.toCharArray();
            for (int i = 0; i < ch.length; i++) {
                  if (! (ch[i] >= '0' && ch[i] <= '9')) {
                        _codeError="錯誤:輸入的身份證號第"+(i+1)+"位包含字母";
                        return false;
                  }
            }
            return true;
      }

      public String getCodeError(){
            return _codeError;
      }

      //驗證身份證
      public boolean verify(String idcard) {
            _codeError="";
            //驗證身份證位數,15位和18位身份證
            if(!verifyLength(idcard)){
                return false;
            }
            //驗證身份除了最后位其他的是否包含字母
            if(!containsAllNumber(idcard)){
                  return false;
            }

            //如果是15位的就轉成18位的身份證
            String eifhteencard="";
            if (idcard.length() == 15) {
                  eifhteencard = uptoeighteen(idcard);
            }else{
                  eifhteencard=idcard;
            }
            //驗證身份證的地區碼
            if(!verifyAreaCode(eifhteencard)){
                  return false;
            }
            //判斷月份和日期
            if(!verifyBirthdayCode(eifhteencard)){
                  return false;
            }
            //驗證18位校驗碼,校驗碼采用ISO 7064:1983,MOD 11-2 校驗碼系統
            if(!verifyMOD(eifhteencard)){
                  return false;
            }
            return true;
      }

      //驗證18位校驗碼,校驗碼采用ISO 7064:1983,MOD 11-2 校驗碼系統
      public boolean verifyMOD(String code){
            String verify = code.substring(17, 18);
            if("x".equals(verify)){
                  code=code.replaceAll("x","X");
                  verify="X";
            }
            String verifyIndex=getVerify(code);
            if (verify.equals(verifyIndex)) {
                  return true;
            }
//            int x=17;
//            if(code.length()==15){
//                  x=14;
//            }
            _codeError="錯誤:輸入的身份證號最末尾的數字驗證碼錯誤";
            return false;
      }

      //獲得校驗位
      public String getVerify(String eightcardid) {
            int remaining = 0;

            if (eightcardid.length() == 18) {
                  eightcardid = eightcardid.substring(0, 17);
            }

            if (eightcardid.length() == 17) {
                  int sum = 0;
                  for (int i = 0; i < 17; i++) {
                        String k = eightcardid.substring(i, i + 1);
                        ai[i] = Integer.parseInt(k);
                  }

                  for (int i = 0; i < 17; i++) {
                        sum = sum + wi[i] * ai[i];
                  }
                  remaining = sum % 11;
            }

            return remaining == 2 ? "X" : String.valueOf(vi[remaining]);
      }

      //15位轉18位身份證
      public String uptoeighteen(String fifteencardid) {
            String eightcardid = fifteencardid.substring(0, 6);
            eightcardid = eightcardid + "19";
            eightcardid = eightcardid + fifteencardid.substring(6, 15);
            eightcardid = eightcardid + getVerify(eightcardid);
            return eightcardid;
      }



調 用 new IDCard().verify(身份證id);
轉載:http://www.oschina.net/code/snippet_249203_24013


一堣而安 2014-02-27 10:45 發表評論
]]>
java獲取路徑http://www.tkk7.com/tinguo002/archive/2014/02/24/410231.html一堣而安一堣而安Mon, 24 Feb 2014 02:43:00 GMThttp://www.tkk7.com/tinguo002/archive/2014/02/24/410231.htmlhttp://www.tkk7.com/tinguo002/comments/410231.htmlhttp://www.tkk7.com/tinguo002/archive/2014/02/24/410231.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/410231.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/410231.html

getAbsolutePath() 得到絕對路徑、全路徑。
getpath 得到縮寫的路徑,根據當前目錄位置可以縮寫路徑。得到相對路徑
getCanonicalPath() 得到標準路徑,將統一平臺間的路徑寫法差異。
package util;

import java.io.File;

public class CurrentDirectory {
    
    
public static void print(Object o) {
        System.out.println(o);
    }


    
public static void main(String[] args) throws Exception {
        print(Thread.currentThread().getContextClassLoader().getResource(
""));
        print(CurrentDirectory.
class.getClassLoader().getResource(""));
        
//print(this.getClass().getResource("/").toString().replace("file:/", "")); //在非靜態方法中可以使用
        print(ClassLoader.getSystemResource(""));
        print(CurrentDirectory.
class.getResource(""));
        print(CurrentDirectory.
class.getResource("/"));
        print(
new File("").getAbsolutePath());
        print(System.getProperty(
"user.dir"));
    }

    
}




一堣而安 2014-02-24 10:43 發表評論
]]>
樹形全部展示代碼http://www.tkk7.com/tinguo002/archive/2013/12/30/408218.html一堣而安一堣而安Mon, 30 Dec 2013 11:16:00 GMThttp://www.tkk7.com/tinguo002/archive/2013/12/30/408218.htmlhttp://www.tkk7.com/tinguo002/comments/408218.htmlhttp://www.tkk7.com/tinguo002/archive/2013/12/30/408218.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/408218.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/408218.htmljsp:代碼

<script type="text/javascript">

  $(function(){
   //alert('${tip}');
   if('${tip}'!=''){
    $('#tip').css('display','inline-block');
   }
  });
 
  var zTreeObj;
  var allSelectedId="";
  var allSelectedName = "";
  var zNodes = ${data};
  var setting = {
   isSimpleData: true,
   treeNodeKey: "id",         //設置節點唯一標識屬性名稱
   treeNodeParentKey: "pId",  //設置節點的父節點唯一標識屬性名稱
   nameCol: "name",           //設置 zTree 顯示節點名稱的屬性名稱,此處默認為Name
   showLine: true,            //在樹型中是否顯示線條樣式
   
   check: {
    enable: true,
    chkStyle: "<%=type%>",
    chkboxType: <%=chkboxType%>,
    radioType: "all"
   },
   callback: {
    onClick: onClick
   },
   data: {
    simpleData: {
     enable: true
    }
   }
  };
   
  $(function(){
   $("#btnClose").bind("click",doClose);
   $("#btnConfirm").bind("click",doConfirm);
   zTreeObj = $("#tree").zTree(setting,zNodes);
  });
  
  //關閉窗口
  function doClose(){
   window.close();
  }
   
  function doConfirm(){
   var checkedNodes = zTreeObj.getCheckedNodes(true);
   alert(checkedNodes);
   for (i=0;i<checkedNodes.length;i++) {
   
    var treeNode = checkedNodes[i];
    alert(treeNode.id);
     if(!treeNode.open){
      allSelectedId += (allSelectedId == "" ? "" : ",") + treeNode.id;
      allSelectedName += (allSelectedName == "" ? "" : ",") + treeNode.name;      
     }
    }
   $('#hiddenId').val(allSelectedId);
   $('#hiddenName').val(allSelectedName);
  }
  
  function showMenu() {
   var deptname = $("#deptname");
   var offset = deptname.offset();
   $("#menu").width(deptname.width())
   .css({left:offset.left + "px", top:offset.top + deptname.outerHeight() + "px"})
   .slideDown("fast");
  }
  
  function hideMenu() {
   $("#menu").fadeOut("fast");
  }
  
  function onClick(e, treeId, treeNode) {
   alert(treeId);
   if(treeNode.checked){
    hideMenu();
   }else{
    zTreeObj.checkNode(treeNode, true, null, true);
   }
   return false;
  }
  
  function onCheck(e, treeId, treeNode){
   alert(treeNode.id);
   allSelectedId += (allSelectedId == "" ? "" : ",") + treeNode.pId+"|"+treeNode.id+"|"+treeNode.name;
  }
 </script>

java代碼:

public class CameraTreeAPI {
 private static Logger log = Logger.getLogger(CameraTreeAPI.class);
 
 /**
  *
  * 功能說明:獲取整個ztree攝像頭樹
  * @return  滿足ztree要求的json數據
  * String
  * @author chh
  * @Jun 14, 2012
  */
 public  String getZTree(String systemUnid,String selectUnid){
  selectUnid = ","+StrUtil.formatNull(selectUnid)+",";
  JSONArray array = new JSONArray();
  try{
   List<BusinessCamera> list = new BusinessCameraManager().doFindBySystemUnid(systemUnid);
   
   JSONObject top = new JSONObject();
   top.put("id","0");
   top.put("name","攝像頭列表");
   top.put("open",true);
   array.add(top);
   
   if(list!=null && list.size()>0){    
    for(Object object : list){
     BusinessCamera camera = (BusinessCamera)object;
     JSONObject json = new JSONObject();
     json.put("id",camera.getUnid());
     json.put("name",camera.getName());
     json.put("pId",camera.getPunid());
     json.put("checked", selectUnid.indexOf(camera.getUnid()) >= 0);
     if(hasChildren(list,camera)){
      json.put("open",true);
     }
     array.add(json);
    }
   }
  }catch(Exception e){
   e.printStackTrace();
   log.error(e.getMessage(),e);
  }
  return array.toString();
 }
 
 public boolean hasChildren(List<BusinessCamera> allData,BusinessCamera camera){
  if(allData == null || allData.isEmpty() || camera == null){
   return false;
  }
  for(BusinessCamera unit : allData){
   if(unit.getUnid().equalsIgnoreCase(camera.getUnid())){
    continue;
   }
   if(camera.getUnid().equalsIgnoreCase(unit.getPunid())){
    return true;
   }
  }
  return false;
 }
 
}




一堣而安 2013-12-30 19:16 發表評論
]]>
耦合度與設計模式 http://www.tkk7.com/tinguo002/archive/2013/10/09/404774.html一堣而安一堣而安Wed, 09 Oct 2013 01:16:00 GMThttp://www.tkk7.com/tinguo002/archive/2013/10/09/404774.htmlhttp://www.tkk7.com/tinguo002/comments/404774.htmlhttp://www.tkk7.com/tinguo002/archive/2013/10/09/404774.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/404774.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/404774.htmlhttp://socket.blog.163.com/blog/static/209873004201096210555/

高內聚,低耦合(High Cohesion、Low Coupling)
是一句近乎于“為實現四個現代化而努力”式的口號,耳熟并不一定能詳。這個口號是在軟件工程里第一次碰到的,它的定義估計是計算專業術語里最欠扁的定義,內聚:一個模塊內各個元素彼此結合的緊密程序。耦合:一個軟件結構內不同模塊之間互連程序的度量。這兩個定義,相當地“形而上學”“不知所云”。這是軟件工程中判斷設計好壞的標準,主要是面向對象設計,主要是看類的內聚性是否高,偶合度是否低。為什么要高內聚,使模塊之間的關系越緊密出錯就趙少,越緊密運行效率越高!低耦合,就是說,子程序之間的關系越簡單,越容易擴展和維護,越復雜就會產生出更多的意想不到的錯誤!不利于維護。

       
程序員天生都是內聚的高手,違反高內聚的反而是那些有一定水平的程序員,可能是誤用了設計模式,可能是考慮問題過分全面,把一個功能單一的類分割成多個類。這里重點說低耦合,耦合就是類之間的互相調用關系,如果耦合很強,互相牽扯調用很多,那么會牽一發而動全身,不利于維護和擴展。什么方法、數據、不加分析地往一個類里整,甚至時一個類的所有數據成員設成public,方便在其它類里直接修改數據。生活中很多“低耦合”的例子,如床與床單,如果是緊耦合的話,換床單時,也要換床。再如桌子與抽屜。


耦合度與設計模式 - share39 - 互聯的天空


      
圖中的上半部分中,把一個軟件模塊抽象成線條,軟件模塊互相依賴,這是一種面向過程的開發方式,如果軟件是不改變的,那么這種高耦合度的結構也無可厚非,有時象底層軟件如操作系統等,一切以執行效率優先,而且需求并不改變頻繁的情況下,是適用的。但在實際開發過程中,軟件需求的變化是導致這種模式被否定的真正原因。一旦有一個模塊改變,那么需要改動到其它好幾個模塊,而且更要命的時,被影響的模塊又會影響其它模塊,或者干脆又把影響力傳遞給當初最先改動的模塊。


       
下圖中的模塊結構通過梳理,使他們依附于一條粗線條,它是主邏輯模塊,是相對穩定的高層的、抽象的模塊。而其它通過一個小空心圓點(表示接口)與粗線條進行連接的小短線條代表次模塊,它被分成兩個部分,接口和實現接口的子類對象,它們通過接口與主邏輯模塊形成依賴。相對來說,次模塊變化較快,而主模塊變化較慢。剛才提到的生活例子中,床相對于床單來說是主要的,核心的,成本較高的,它的使用年限是10年,而床單使用年限是2年,就是說床的模塊變化速度慢于床單的變化速度,如果床2個月變一次,那么邏輯結構就混亂了。床為床單提供了一個尺寸接口,床單只要符合這個接口,就可以組合使用。那么這個接口就必須是相對穩定的。


      
設計模式做為軟件開發過程中一種創造性的總結思維,使軟件開發人員,在開發軟件產品時,有了更加明確的軟件解耦的思路,設計模式來源于生活,卻指導于軟件。事實上,短期來看,要求低耦合并沒有很明顯的好處,因為利用設計模式來解決問題是需要軟件開發的智力和時間成本的。況且引入了誤用設計模式的風險,所以短期內使用設計模式來解耦反而會影響系統的開發進度。低耦合的好處是長期回報的,體現在系統持續發展的過程中,系統具有更好的重用性,維護性,擴展性,持續的支持業務的發展,而不會成為業務發展的障礙。



一堣而安 2013-10-09 09:16 發表評論
]]>
ArrayList的toArray(轉)http://www.tkk7.com/tinguo002/archive/2013/07/04/401205.html一堣而安一堣而安Thu, 04 Jul 2013 03:52:00 GMThttp://www.tkk7.com/tinguo002/archive/2013/07/04/401205.htmlhttp://www.tkk7.com/tinguo002/comments/401205.htmlhttp://www.tkk7.com/tinguo002/archive/2013/07/04/401205.html#Feedback0http://www.tkk7.com/tinguo002/comments/commentRss/401205.htmlhttp://www.tkk7.com/tinguo002/services/trackbacks/401205.html
http://www.cnblogs.com/ihou/archive/2012/05/10/2494578.html

ArrayList提供了一個將List轉為數組的一個非常方便的方法toArray。toArray有兩個重載的方法:

1.list.toArray();

2.list.toArray(T[]  a);

對于第一個重載方法,是將list直接轉為Object[] 數組;

第二種方法是將list轉化為你所需要類型的數組,當然我們用的時候會轉化為與list內容相同的類型。

不明真像的同學喜歡用第一個,是這樣寫:

1
2
3
4
5
6
7
ArrayList<String> list=new ArrayList<String>();
        for (int i = 0; i < 10; i++) {
            list.add(""+i);
        }
       
        String[] array= (String[]) list.toArray();
      

結果一運行,報錯:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

原因一看就知道了,不能將Object[] 轉化為String[].轉化的話只能是取出每一個元素再轉化,像這樣:

1
2
3
4
5
Object[] arr = list.toArray();
        for (int i = 0; i < arr.length; i++) {
            String e = (String) arr[i];
            System.out.println(e);
        }

所以第一個重構方法就不是那么好使了。

實際上,將list世界轉化為array的時候,第二種重構方法更方便,用法如下:

1
2
String[] array =new String[list.size()];
        list.toArray(array);<br><br>另附,兩個重構方法的源碼:

1.
public Object[] toArray(); {
Object[] result = new Object[size];
System.arraycopy(elementData, 0, result, 0, size);;
return result;
}

2.

public Object[] toArray(Object a[]); {
if (a.length < size);
a = (Object[]);java.lang.reflect.Array.newInstance(
a.getClass();.getComponentType();, size);;
System.arraycopy(elementData, 0, a, 0, size);;

if (a.length > size);
a[size] = null;

return a;
}

1
<br><br>
1
2
<br>
  


一堣而安 2013-07-04 11:52 發表評論
]]>
主站蜘蛛池模板: 久久精品免费大片国产大片| 亚洲阿v天堂在线2017免费| 亚洲人色婷婷成人网站在线观看 | 亚洲老熟女五十路老熟女bbw| h视频在线观看免费网站| 亚洲黄色免费观看| 曰批全过程免费视频网址| 亚洲精品第一国产综合精品| 亚洲一级免费毛片| 亚洲一卡一卡二新区无人区| 免费毛片网站在线观看| 美女裸体无遮挡免费视频网站| 免费在线视频一区| 99视频在线观看免费| 久久青青草原亚洲AV无码麻豆 | 黄人成a动漫片免费网站| 亚洲日韩人妻第一页| 日本黄色动图免费在线观看| 亚洲精品视频在线观看视频| 成年大片免费视频| 免费无码午夜福利片| 最近中文字幕免费mv在线视频| 亚洲啪啪AV无码片| 国产AV旡码专区亚洲AV苍井空| 成人午夜性A级毛片免费| 日本亚洲高清乱码中文在线观看| 亚洲AV永久无码精品一区二区国产| 风间由美在线亚洲一区| 无码不卡亚洲成?人片| 国产一二三四区乱码免费| 亚洲AV无码日韩AV无码导航| 亚洲av无码av在线播放| 国产日本亚洲一区二区三区| 成年女人看片免费视频播放器| 亚洲精品色在线网站| 亚洲精品无码久久一线| 国产精品免费视频观看拍拍| 夜夜嘿视频免费看| 最新久久免费视频| 亚洲熟妇AV一区二区三区浪潮| 亚洲人成网站在线观看青青 |