0734w-月下竹音

0734是来自家乡的声音

常用链接

统计

最新评论

日常备忘1-50条

1.设置一个按钮为有用或不能用,
 <%
 if(index.intValue()%2==1)
  {
 %>
<input type="button" name="Update" class="kuButton" value='Update' disabled onclick="submitUpdate();return false;">
<input type="button" name="Delete" class="kuButton" value='Delete' disabled onclick="submitDel();return false;"></td>
<%
 }else{
 %>
<input type="button" name="Update" class="kuButton" value='Update' disabled onclick="submitUpdate();return false;">
<input type="button" name="Delete" class="kuButton" value='Delete' disabled onclick="submitDel();return false;"></td>
<%
}
%> 

2.让你一个按钮显示不显示
显示:document.formname.id.style.display="none"
不显示:document.formname.id.style.display="inline"

3.在一个链接中要用到动态的参数,要调用方法,但是传参数时容易出现问题,最好的方式是:
action='<%="artMaintAction.do?method="+ session.getAttribute("method")+"&firstlevel=3&secondlevel=1"%>'


4,当页面提交是为默为的utf-u编码,我们要转换成GB2312才能正确插入到数据库中:
在SEVLETK加上:request.seCharacterEncoding("gb2312")

5.传递表单参数:
String name = new String(request.getParameter("name"));


7.文件操作

~~将一个字符串写到一个指定的文件中,如果该文件不存在,则新建一个文件,并完成写入;如果存在,则用此字符串覆盖原文件的所有内容
import java.io.*;
String str = "print me";
//定义好打印的目标文件名

//取得当前主机存放WEB页面的绝对路径
String hostdir = System.getProperty("user.dir");
//取得当前主机所采用的路径分隔符
String fileBar = System.getProperty("file.separator");
//书写完整的目标文件存放路径
String nameOfFile=hostdir+fileBar+"test.html";

try
//实例化一个文件输出流对象
FileOutputStream afile = new FileOutputStream(nameOfFile);
//将文件输出流,创建一个打印输出流对象
PrintWriter pw = new PrintWriter(afile);
pw.println(str);
//clean up
pw.close();
{}
catch(IOException e)
out.println(e.getMessage());
{}

~~列出指定目录下的文件列表
import java.io.*;
String cdur = System.getProperty("user.dir");
String fileBar = System.getProperty("file.separator");
String mydir =cdur+fileBar+"doc"+fileBar+"jspsky";
File my = new File(mydir);
String d[] = my.list();
int i;
int l=d.length;
for(i=0;i out.print(d[i]);
{}

---文件更名:file 有一个属性就是renameTo更名
    File  file = new File("./");
    File file1 = new File("../");
    file.renameTo(file1);
    renameTo( )。它会把文件重命名成(或者说移动到)新的目录,也就是参数所给出的目录。
    而参数本身就是一个File对象。这个方法也适用于目录。

 

8.计数器
Integer count = null;
synchronized (application)
count =(Integer) application.getAttribute("d");
if (count ==null)
count =new Integer("0");
count = new Integer(count.intValue()+1);
application.setAttribute("d",count);
{}
out.println(count);
// 首先定义一个整形对象,并初始化为:NULL,
// 取回APPLICATION对像的属性D的值,并强制转化为整形对象,赋给COUNT
// 判断COUNT是否为空,为空时,将O赋给COUNT对象,
// 否则,通过COUNT。INTVALUE()方法,实现COUNT对象加1,并赋值给COUNT
// 最后,将COUNT对象保存在APPLICATION对象的D变量中。

9,在JAVA中
String a[] = { "a", "ab" };
String b[][] = { { "abc", "abcd" }, { "d" } };

10,不能把逻辑直接放在一个类里面方法外面,这是一个很低级的错误,而且会使你找不到错误在哪里。

11,在数组中
String a[] = { "a", "aa" ,"aaa"};
String c[] = { "c", "cc" };
如果a = c 即变成是a[]== { "c", "cc" };
    c = a 即变成是c[]=={ "a", "aa" ,"aaa"};它们不是一个一个的赋值。
   
11,数组能存放原始对象(primitive)和Object对象,容器只能存放Object对象,不过可以使用类将其转换,不过数组的效率比容器高很多。数组是不可变的
 
 
12,n = Math.abs(n)是返回N的决对值]

13,http://java.sun.com/docs/books/tutorial/index.html    THE Java Tutorial

14,Array中Arrays.fill(a9, 1, 3, "World");是把a9中的第二个字符和第三个字符填上world

15,java.util.array类是一组用于数组操作的static方法它有四个基本方法:
Arrays.fill(object, values) , Arrays.sort(), Arrays.equals() , Arrays.binarySearch()[用天排列数组查找对象]
System.arraycopy(fromobject,startnum,toobject,startnum,length)用于数组之间的拷贝
 Arrays.equals(objecta,objectb);返回一个boolen值,这里相等一定指长度相同,而且第一个元素相同
 Arrays.sort(a); 对对象a进行排序,a是数字以小数字放前面,a是字母以A开头a第二,以此类推
int location = Arrays.binarySearch(a, 20);查找a中为20(必须为20不能多不能少)的位置,在查找之前必须用Arrays.sort(a);排序

16.在JAVA数组中:
String[] s1 = { "Hi", "Hi", "Hi", "Hi", "Hi" };
String[] s2 = { "Hi", "Hi", "Hi", "Hi", "Hi" };
String[] s3 = { "Hi", "Hi", "Hi", "11", "" };
Arrays.equals(s1,s2)成立,Arrays.equals(s3,s2)不成立,它是基本内容的比较,相当与s1-s2(中间为减号),返回的是一个大于小于或等于O的数
s2.equals(s3),s2==s3它们是基于对象的比较(内存中比较)


17,返回一个1-100的整数:
static Random r = new Random();
Math.abs(r.nextInt()) % 100;

18,在其它类里面调用静态方法:new testT.TConstraction1(5);只会调用静态类的确定的构造函数,不会调用其它代码:
class testT {
 testT() {System.out.println("TConstraction(..)");}
 public static class TConstraction1 {
  public void atest() {
   System.out.println(" 会执行所有的Constaction代代码");
  }
  public TConstraction1(int i) {
   System.out.println("-static void TConstraction1 i==" + i);
  };
 }
}

19,s.toLowerCase()将s中所有字母转换成小写字母

20,容器分为:collection map
collection分为set ,list.
set里面的值不能重复,ArrayList,hashSet    添加为a.add("test") set会进行排序
MAP是一个链接保存一对对象,也可以转换成Collection     添加为:a.put("test","test2"):

21,list中也能用Collections.fill()静态方法来填充字符,但是必须要在原来里面有值的时候才能填
List list = new ArrayList();
for (int i = 0; i < 10; i++) {
 list.add("");
}
Collections.fill(list, "Hello");

 

21,ArrayList其实就是一个可变长的数组,它方法也较简单:用add("a")加,用get(i)得到第i个对象

22.collection(list and set)包含以下功能:
exp: collection c= new Arraylist(); collection b= new Arraylist(); String c ="1";
c.add(object c);
c.addAll(collection b);
c.clear();
c.contains(object b);
c.containsAll(collection b);
c.isEmpty();
Iterator iteratora = a.iterator(); while(iteratora.hasNest())
c.remove(object c);
c.removeAll(collection b);
c.size();容器大小
没有get(i)随机取值
LinkedList有addFirst() removeFirst() addLast() removeLast();


23.map有两个方法可以分别打印key and values
System.out.println(mapt1.values());
System.out.println(mapt1.keySet());
也可以直接打印System.out.println(mapt1);
map使用Iterator 必须使用keySet 或values如:Iterator it =map1.keySet.iterator();
map1中可以使用map1.get(object key);
containsKey()包含一个key对象;
containsValues()包含一个值对象;

24,Math.random() * 20
返回一个1-20之间的一个应意随机数,返回的是一个doubel型的,如果想产生在1-20整数使用:
Integer r = new Integer( (int) (Math.random() * 20));

25,SortedMap 比HASHMAP多了几个属性:
map1.firstKey();第一个
map1.lastKey();最后一个
map1.subMap(fromKey,toKey);返回值中包括前者不包括后者
map1.headMap(toKey);返回的值都小于fromKey
map1.tailMap(fromKey);返回的值都大于fromKey

26。HashMap 要用equals()不能判断查询的键是不是与表里面的其它键相等。
equals()具有五个属性:反身,对称,传递,一致,非空

27.取得当前主机的名称:
//取得当前主机存放WEB页面的绝对路径
  String hostdir = System.getProperty("user.dir");
//取得当前主机所采用的路径分隔符
  String fileBar = System.getProperty("file.separator");
//书写完整的目标文件存放路径
  String nameOfFile=hostdir+fileBar+"test.html"; 
 
28.在页面上显示日期
(1)在JS中定义:
  var today = new Date();
  function showday(){
 var year = today.getYear();
   var month = today.getMonth() + 1;
   var date = today.getDate();  //日期
   var day = today.getDay();  //星期
   var week =new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
        var dayValue = "";
   dayValue += year + "-";
   dayValue += ((month < 10) ? "0" : "") + month + "-";
   dayValue += date + "  ";
   dayValue += (week[day]);
   document.write(dayValue);
  }
(2)在JSP中只要:
<script>showday()</script>
 
29,从配置文件里面读数据:
第一步:web.xml中定义如下, 如果配置文件为:config.properties
  <servlet>
    <servlet-name>InitServlet</servlet-name>
    <servlet-class>com.cpic.adapter.adapterapp.util.InitServlet</servlet-class>
 <init-param>
  <param-name>config</param-name>
  <param-value>/WEB-INF/config.properties</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
  </servlet>
 
第二步:定义InitServlet

package com.cpic.adapter.adapterapp.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.PropertyResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;


import com.cpic.adapter.adapterapp.constant.Constants;

/**
 * <p>Title:InitServlet.java</p>
 * <p>Description:当应用起动时加载要读取的数据放入context中</p>
 * <p>Copyright:Copyright (c) 2005 chenhua,Inc</p>
 * <p>Company:chenhua,Inc</p>
 * @author spark 2005-12-26
 * @version 1.0
 */
public class InitServlet extends HttpServlet {
 private Logger logger;

 public void init() throws ServletException{
  super.init();
  ServletContext context = getServletContext();
  context.setAttribute(Constants.ADAPTER_INIT_STATUS,Boolean.FALSE);  
  //initialize proxy configuration
  initAdapter();
  context.setAttribute(Constants.ADAPTER_INIT_STATUS,Boolean.TRUE);
  logger.info("initAdapter initialized successfully");
 }

 
 /**
  * <p>Description:加载和设置数据</p>
  *  @throws ServletException
  *  spark 2005-12-26
  */
 private void initAdapter() throws ServletException{
  ServletContext context = getServletContext();
  String configFile = getInitParameter("config");
  if (configFile == null) {
   String errMsg="Initialize Adapter configuration  config file is not set in web.xml.";
   logger.error(errMsg);
   ServletException e = new ServletException(errMsg);
   throw e;   
  }
  
  InputStream in;
  PropertyResourceBundle configBundle;
  try {
   in = this.getServletContext().getResourceAsStream(configFile);
   configBundle = new PropertyResourceBundle(in);
   context.setAttribute(Constants.ADAPTER_FILE_SEND,configBundle.getString(Constants.ADAPTER_FILE_SEND));
   context.setAttribute(Constants.ADAPTER_FILE_RECEIVE,configBundle.getString(Constants.ADAPTER_FILE_RECEIVE));

  } catch (IOException e) {
   String errMsg = "Initialize adapter config.properties failed.";
   logger.error(errMsg);
   ServletException e1 = new ServletException(errMsg);
   throw e1;   
  }
   catch (Exception e) {
   String errMsg = "Initialize adapter config.properties failed.";
   logger.error(errMsg);
   ServletException e1 = new ServletException(errMsg);
   throw e1;   
  }
  
 }
 
}

第三步,在应用利用:
在servlet中如下:
ServletContext context = getServletContext();
( String) context.getAttribute(Constants.PARTNER_NAME)
在STRUTS的ACTION中如下:
ServletContext context = request.getSession().getServletContext();
(String) context.getAttribute(Constants.PARTNER_NAME);


30.现在要提取所有儿子的名字中有 "中" 或 "华"   的父亲。  这个sql语句  。  最好怎么写?
select f.no,f.name from father f,son s where f.no=s.f.no and s.name like '[中华]' 

31.输出错误的详细信息用ex.printStackTrace();
 try{
     System.out.println(" the app end....");
   }catch(JRException ex){
   out.print("Jasper Output Error:"+ex.getMessage());
   ex.printStackTrace();
  }

34.JAVA环境变量设置
JAVA_HOME=C:\JDK 
PATH=%JAVA_HOME%\bin
set CLASSPATH=%JAVA_HOME%\lib\Tools.jar;%JAVA_HOME%\lib\dt.jar;

35,用MD5加密,每次加密的数据是一样的,修改hexDigits前面数据加密的密文会变,修改hexDigits后面密文不变???:
import java.security.MessageDigest;
public class EncryptUtils {  
    /**
     * 采用MD5算法加密字符串
     * @param s
     * @return
     */
    public final static String MD5(String s){
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            if( s == null){
                return null;
            }
         byte[] strTemp = s.getBytes();
         MessageDigest mdTemp = MessageDigest.getInstance("MD5");
         mdTemp.update(strTemp);
         byte[] md = mdTemp.digest();
         int j = md.length;
         char str[] = new char[j * 2];
         int k = 0;
         for (int i = 0; i < j; i++) {
          byte byte0 = md[i];
          str[k++] = hexDigits[byte0 >>> 4 & 0xf];
          str[k++] = hexDigits[byte0 & 0xf];
         }
          return new String(str);
        }catch (Exception e){
         return null;
     }
    }
    /**
     * 使用MD5算法加密密码,返回前面16位
     * @param pwd
     * @return
     */
    public final static String EncryptPwd(String password){
        if( password!=null){
            return  EncryptUtils.MD5(password).substring(0,16);
        }
        return null;
    }
    public static void main(String[] args){
       System.out.print(EncryptUtils.EncryptPwd("111111"));  
    }
}

36.输入和输出
InputStream的任务就是代表那些能从各种输入源获取数据的类。这些源包括:
1.byte数组
2.String对象
3.文件
4.类似流水线的"管道(pipe)"。把东西从一头放进去,让它从另一头出来。
5.一个"流的序列(A sequence of other streams)",可以将它们组装成一个单独的流。
6.其它源,比如Internet的连接。(这部分内容在Thinking in Enterprise Java中讨论。)

37,油漆工模式
Decorator模式常用于如下的情形:如果用继承来解决各种需求的话,类的数量会多到不切实际的地步。Java的I/O类库需要提供很多功能的组合,于是decorator模式就有了用武之地。[62] 但是decorator有个缺点,在提高编程的灵活性的同时(因为你能很容易地混合和匹配属性),也使代码变得更复杂了。Java的I/O类库之所以会这么怪,就是因为它"必须为一个I/O对象创建很多类",也就是为一个"核心"I/O类加上很多decorator。


38.虽然InputStream和OutputStream的某些功能已经淘汰了(如果你继续使用,编译器就会发警告),但它们仍然提供了很多很有价值的,面向byte的I/O功能,而Reader和Writer则提供了Unicode兼容的,面向字符的I/O功能

39, BufferedReader in = new BufferedReader(new FileReader("IOStreamDemo.java"));
        String s, s2 = new String();
        BufferedReader inst = new BufferedReader(new InputStreamReader(
                System.in));
        System.out.print("Enter a line:");
        System.out.println(inst.readLine());
为什么 inst.readLine()返回的是一个数字??????????,不是读取一行信息吗?

40.文件操作首先要建立一个流BufferedReader
        BufferedReader in = new BufferedReader(new FileReader(
                "IOStreamDemo.java"));
        String s, s2 = new String();
        while ((s = in.readLine()) != null)
            s2 += s + "\n";
        in.close();
       
41. 读取文件
先创建一个FileWriter。BufferedWriter总是免不掉的。(试试把BufferedWriter去掉,
你就能看到它对性能的影响了—— 缓冲能大幅提高I/O的性能)。然后再让PrintWriter去排版
            PrintWriter out1 = new PrintWriter(
                    new BufferedWriter(
                            new FileWriter("spark.out")
比读文件多了一个排版用的FileWriter,其它只将Reader换成Writer就OK了
这里的while ((s = in4.readLine()) != null)这里只能用while
                out1.println(outnum++ + ": " + s);
               
42.从键盘上输入数据然后打印出来,用readLine( )一行一行地读取输入,因此要把System.in包装成
BufferedReader。但在这之前还得先用InputSteamReader把System.in转换成Reader
import java.io.*;
public class Echo {
    public static void main(String[] args) throws IOException {
       //以然用BufferedReader作缓冲
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String s;
        while ((s = in.readLine()).length() != 0)
            System.out.println(s);
        // An empty line terminates the program
    }
} ///:~

43.对象序列化
Java的"对象序列化"能让你将一个实现了Serializable接口的对象转换成一组byte,这样日后
要用这个对象时候,你就能把这些byte数据恢复出来,并据此重新构建那个对象了
实现两个重要的功能。
(1)Java的远程方法调用(Remote Method Invocation简称RMI)能让你像调用自己机器上的对象那样去
调用其它机器上的对象。当你向远程对象传递消息的时候,就需通过对象序列化来传送参数和返回值了。
(2).Bean的状态信息通常是在设计时配置的。这些状态信息必须保存起来,供程序启动的时候用;
对象序列化就负责这个工作。

44.使用Externalizable对象序列化时,
使用Externalizable对象序列化时恢复对象时会调用的默认构造函数(一定要是public的)。这一点同恢复Serializable对象不同,后者不调用任何构造函数,
完全根据存储的数据来重建对象。对于Externalizable对象,内部方法要在默认的构造行为会发生之后
(包括在定义数据成员时进行的初始化)才启动。只有知道这一切——特别是默认的构造过程肯定会发生——你才能
正确地使用Externalizable对象。

45,Externalizable对象不保存任何字段,因此transient只能用于Serializable对象。

46.使用正则表达式,如匹配所有有字母的
(1)import java.util.regex.*;
public class TestRegularExpression {
    public static void main(String[] args) {
        String patern1 = "asdfsdfgsgdsdgsdfgsdfgsdg";
        Pattern p = Pattern.compile("\\w");
        Matcher m = p.matcher(patern1);
        while (m.find()) {
            System.out.println("Match \"" + m.group() + "\" at positions "
                    + m.start() + "-" + (m.end() - 1));
        }
    }
} ///:~
(2)m.group()表示相匹配的字,"\\w+"的意思是"一个或多个单词字符",因此它会将字符串直接分解成单词。find( )像一个迭代器,从头到尾
扫描一遍字符串。第二个find( )是带int参数的,正如你所看到的,它会告诉方法从哪里开始找——即从参数位置开始查找。
    Matcher m = Pattern.compile("\\w+").matcher(
                "Evening is full of the linnet's wings");
        while (m.find())
            System.out.println(m.group());
        int i = 0;
        System.out.println("---------------");
        while (m.find(i)) {
            System.out.println(m.group() + "## ");
            i++;
        } }
lookingAt( )和matches( ),只有在字符串与正则表达式一开始就相匹配的情况下才能返回true。matches( )成功的前提是正则表达式
与字符串完全匹配,而lookingAt( )[67]成功的前提是,字符串的开始部分与正则表达式相匹配

47.利用split将有相同字符串的分解。
String input = "This!!unusual use!!of exclamation!!points";
System.out.println(Arrays.asList(Pattern.compile("!!").split(input)));
// Only do the first three:只要替换前面三个
System.out.println(Arrays.asList(Pattern.compile("!!").split(input, 3)));
结果为:
[This, unusual use, of exclamation, points]
[This, unusual use, of exclamation!!points]只替换了前面三个

48,读取文本文件用
  String s = TextFile.read("TheReplacements.java");
  String input2= input.replaceAll("e","u");是把所有的e替换成u
 
49.Thread的run( )里面总是会有循环,这些循环会一直运行下去,直到线程结束。所以你必须设定条件打破循环
(或者像上面那样,直接在run( )里面return)。通常run( )是个无限循环,也就是说,刨开那些会让run( )
停下来的意外情况,线程会一直运行下去(

50.yield( )会把一些运行很久的线程停下来,让其它线程运行,但是yield( )只会在很少的情况下起作用,
而且不能用来进行很严肃的调校。

 

 


                           

 

 

 

 

 

 

 


 

posted on 2006-02-28 20:55 sparkwu 阅读(264) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: