Sun River
          Topics about Java SE, Servlet/JSP, JDBC, MultiThread, UML, Design Pattern, CSS, JavaScript, Maven, JBoss, Tomcat, ...
          posts - 78,comments - 0,trackbacks - 0

          Question How do you delete a Cookie within a JSP? (JSP)

          Answer

          Cookie mycook = new Cookie("name","value");

          response.addCookie(mycook);

          Cookie killmycook = new Cookie("mycook","value");

          killmycook.setMaxAge(0);

          killmycook.setPath("/");

          killmycook.addCookie(killmycook);

          Question How many types of protocol implementations does RMI have? (RMI)

          Answer RMI has at least three protocol implementations: Java

          Remote Method Protocol(JRMP), Internet Inter ORB Protocol(IIOP),

          and Jini Extensible Remote Invocation(JERI). These are alternatives,

          not part of the same thing, All three are indeed layer 6 protocols for

          those who are still speaking OSI reference model.

          Question What are the different identifier states of a Thread?

          (Core Java)

          Answer The different identifiers of a Thread are:

          R - Running or runnable thread

          S - Suspended thread

          CW - Thread waiting on a condition variable

          MW - Thread waiting on a monitor lock

          MS - Thread suspended waiting on a monitor lock


          Question What is the fastest type of JDBC driver? (JDBC)

          Answer JDBC driver performance will depend on a number of

          issues:

          (a) the quality of the driver code,

          (b) the size of the driver code,

          (c) the database server and its load,

          (d) network topology,

          (e) the number of times your request is translated to a different API.

          In general, all things being equal, you can assume that the more your

          request and response change hands, the slower it will be. This

          means that Type 1 and Type 3 drivers will be slower than Type 2

          drivers (the database calls are make at least three translations versus

          two), and Type 4 drivers are the fastest (only one translation).

          Question Request parameter How to find whether a parameter

          exists in the request object? (Servlets)

          Answer 1.boolean hasFoo = !(request.getParameter("foo") ==

          null || request.getParameter("foo").equals(""));

          2. boolean hasParameter =

          request.getParameterMap().contains(theParameter);

          (which works in Servlet 2.3+)


          Question How can I send user authentication information while

          makingURLConnection? (Servlets)

          Answer You’ll want to use

          HttpURLConnection.setRequestProperty and set all the appropriate

          headers to HTTP authorization.

          Question How do I convert a numeric IP address like 192.18.97.39

          into a hostname like java.sun.com? (Networking)

          Answer

          Question How many methods do u implement if implement the

          Serializable Interface? (Core Java)

          Answer The Serializable interface is just a "marker" interface,

          with no methods of its own to implement. Other ’marker’ interfaces

          are

          java.rmi.Remote

          java.util.EventListener

          String hostname =InetAddress.getByName("192.18.97.39").getHostName();

          posted @ 2010-10-25 17:08 Sun River| 編輯 收藏
          1.

          Question What is the query used to display all tables names in

          SQL Server (Query analyzer)? (JDBC)

          Answer select * from information_schema.tables

          Question What is Externalizable? (Core Java)

          Answer Externalizable is an Interface that extends Serializable

          Interface. And sends data into Streams in Compressed Format. It has

          two methods, writeExternal(ObjectOuput out) and

          readExternal(ObjectInput in).

          Question What modifiers are allowed for methods in an Interface?

          Answer Only public and abstract modifiers are allowed for

          methods in interfaces.

          Question How many types of JDBC Drivers are present and what

          are they? (JDBC)

          Answer There are 4 types of JDBC Drivers

          Type 1: JDBC-ODBC Bridge Driver

          Type 2: Native API Partly Java Driver

          Type 3: Network protocol Driver

          Type 4: JDBC Net pure Java Driver

          Question What is the difference between ServletContext and

          PageContext? (JSP)

          Answer ServletContext: Gives the information about the container

          PageContext: Gives the information about the Request.

          Question How to pass information from JSP to included JSP?

          Answer Using <%jsp:param> tag.

          posted @ 2010-10-25 16:07 Sun River| 編輯 收藏

           

          tomcat6配置雙向認證

          1
          、生成服務器端證書

          keytool -genkey -keyalg RSA -dname "cn=localhost,ou=sango,o=none,l=china,st=beijing,c=cn" -alias server -keypass password -keystore server.jks -storepass password -validity 3650


          2
          、生成客戶端證書

          keytool -genkey -keyalg RSA -dname "cn=sango,ou=sango,o=none,l=china,st=beijing,c=cn" -alias custom -storetype PKCS12 -keypass password -keystore custom.p12 -storepass password -validity 3650


          客戶端的CN可以是任意值。
          3
          、由于是雙向SSL認證,服務器必須要信任客戶端證書,因此,必須把客戶端證書添加為服務器的信任認證。由于不能直接將PKCS12格式的證書庫導入,我們必須先把客戶端證書導出為一個單獨的CER文件,使用如下命令,先把客戶端證書導出為一個單獨的cer文件:

          keytool -export -alias custom -file custom.cer -keystore custom.p12 -storepass password -storetype PKCS12 -rfc


          然后,添加客戶端證書到服務器中(將已簽名數字證書導入密鑰庫)

          keytool -import -v -alias custom -file custom.cer -keystore server.jks -storepass password


          4
          、查看證書內容

          keytool -list -v -keystore server.jks -storepass password


          5
          、配置tomcat service.xml文件

          <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
              maxThreads="150" scheme="https" secure="true"
              clientAuth="true" sslProtocol="TLS"
              keystoreFile="D:/server.jks" keystorePass="password"
              truststoreFile="D:/server.jks" truststorePass="password"
          />


          clientAuth="true"
          表示雙向認證
          6
          、導入客戶端證書到瀏覽器
          雙向認證需要強制驗證客戶端證書。雙擊“custom.p12”即可將證書導入至IE

          tomcat6
          配置單向認證

          1
          、生成服務器端證書

          keytool -genkey -keyalg RSA -dname "cn=localhost,ou=sango,o=none,l=china,st=beijing,c=cn" -alias server -keypass password -keystore server.jks -storepass password -validity 3650


          2
          、由于是單向認證,沒有必要生成客戶端的證書,直接進入配置tomcat service.xml文件

          <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
              maxThreads="150" scheme="https" secure="true"
              clientAuth="false" sslProtocol="TLS"
              keystoreFile="D:/server.jks" keystorePass="password"    
          />


          clientAuth="false"
          表示單向認證,同時去掉truststoreFile="D:/server.jks" truststorePass="password"2

          posted @ 2010-05-11 12:12 Sun River| 編輯 收藏
           

          ---The key thing to know is that IDs identify a specific element and therefore must be unique on the page – you can only use a specific ID once per document. Many browsers do not enforce this rule but it is a basic rule of HTML/XHTML and should be observed. Classes mark elements as members of a group and can be used multiple times, so if you want to define a style which will be applied to multiple elements you should use a class instead.

           Notice that an ID's CSS is an HTML element, followed by a "#", and finally ID's name. The end result looks something like "element#idname". Also, be sure to absorb the fact that when an ID is used in HTML, we must use "id=name" instead of "class=name" to reference it!

          Why Did They Choose Those Names??

                 ID = A person's Identification (ID) is unique to one person.

                 Class = There are many people in a class.

          ID for Layout and Uniqueness

          Standards specify that any given ID name can only be referenced once within a page or document. From our experience, IDs are most commonly used correctly in CSS layouts. This makes sense because there are usually only one menu per page, one banner, and usually only one content pane.

          In Tizag.com CSS Layout Examples we have used IDs for the unique items mentioned above. View the CSS Code for our first layout example. Below are the unique IDs in our code.

          *       Menu - div#menuPane

          *       Content - div#content

          Answer: Classes vs IDs

          Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.

          posted @ 2010-03-16 10:14 Sun River| 編輯 收藏
          --Spring的singleton是容器級的,我們一般說的singleton模式是JVM級的。所以singleton模式中,singleton的class在整個JVM中只有一個instance,Spring的Bean,你可以一個class配置多個Bean,這個class就有了多個instance。這個singleton是指在spring容器中,這個Bean是單實例的,是線程共享的。所以要求這些類都是線程安全的。也就是說,不能出現修改Bean屬性的方法,當然除了設值得那些setter。只要滿足線程安全,這些bean都可以用singleton。而且我們在絕大多數使用上,也是這樣用的,包括dao,service。
          Beanfactory是Spring初始以靜態方式載入的,Spring的單例IOC是基于容器級的,所以這你都不用擔心與考慮.

          --應用中對象有兩種,行為對象和數據對象,行為對象都要求是線程安全的!也就是允許單例的, 不管是dao 還是 service 對象,都是行為對象,行為對象不應該引用非線程安全的對象做成員量,同時在應用外部的資源(如文件,數據庫連接,session)時,要先保證對這些東西的訪問是做了并發控制的!
            對于spring來講,<bean scope="singleton"/>或<bean singleton="true"/>都是保證對同一sesionfactory bean是單例的,也就是所謂 sessionfactory 范圍的.

          --這是一個真實的案例,我們在項目中使用Spring和ACEGI,我之所以選擇ACEGI,除了它對權限的良好控制外,
          我還看好它的SecurityContextHolder,通過代碼
          代碼
          1. Authentication auth = SecurityContextHolder.getContext().getAuthentication();   
          <script>render_code();</script>
          我可以很容易在系統任意一層得到用戶的信息,而不用把用戶信息在參數里傳來傳去,(這也是struts的缺點之一)
          但是我在每一次要得到用戶信息的時候都寫上面的一段代碼,未免有些麻煩,所以我在BaseService, BaseDao里都提供了如下方法:
          代碼
          1.  /**  
          2.  * get current login user info  
          3.  * @return UserInfo  
          4.  */  
          5. protected UserInfo getUserInfo()   
          6. {   
          7.     return getUserContext().getUserInfo();   
          8. }   
          9.   
          10. /**  
          11.  * get current login user context  
          12.  * @return UserContext  
          13.  */  
          14. protected UserContext getUserContext()   
          15. {   
          16.     Authentication auth = SecurityContextHolder.getContext().getAuthentication();   
          17.     return (UserContext) auth.getPrincipal();   
          18. }   
          <script>render_code();</script>
          這樣在其他的Service和Dao類里可以通過
          代碼
          1. super.getUserContext(), super.getUserInfo()   
          <script>render_code();</script>
          來得到用戶的信息,這也為問題的產生提供了溫床。請看如下代碼:
          代碼
          1. public class SomeServece extends BaseService implements SomeInterFace     
          2. {   
          3.     private UserInfo user = super.getUserInfo();   
          4.        
          5.     public someMethod()   
          6.     {   
          7.        int userID = this.user.getUserID();   
          8.        String userName = this.user.getUserName();   
          9.        //bla bla do something user userID and userNaem   
          10.     }   
          11. }       
          <script>render_code();</script>

           

          這段代碼在單元測試的時候不會用任何問題,但是在多用戶測試的情況下,你會發現任何調用SomeService里someMethod()方法
          的userID和userName都是同一個人,也就是第一個登陸的人的信息。Why?

          其根本原因是Spring的Bean在默認情況下是Singleton的,Bean SomeServece的實例只會生成一份,也就是所SomeServece實例的user
          對象只會被初始化一次,就是第一次登陸人的信息,以后不會變了。所以BaseService想為開發提供方便,卻給開發帶來了風險

          正確的用法應該是這樣的

          代碼
          1. public class SomeServece extends BaseService implements SomeInterFace     
          2. {   
          3.        
          4.        
          5.     public someMethod()   
          6.     {   
          7.        int userID = super.getUserInfo().getUserID();   
          8.        String userName = super.getUserInfo().getUserName();   
          9.        //bla bla do something user userID and userNaem   
          10.     }   
          posted @ 2009-04-08 12:12 Sun River| 編輯 收藏

          Architect (Java) Interview Questions

          General and general terms questions

          Architect interview is slightly different from all other interview types. Interviewer is looking for ability of the candidate to think independently on top of pure technical knowledge. Most of the questions are open-ended, prompting the interviewee to discussion about different aspects of Java development. Other side of the interview is general questions about position of the architect within the organization. Some questions do not have clear, direct or single answer and require discussion with the interviewer. On top of questions mentioned here you may be asked generic OO questions (what is class, what is polymorphism etc.)
          1. What distinguishes "good architecture" from "bad architecture"?
            This is an open-ended question. There are few aspects of "good" architecture:
            1. Shall address functional product requirements
            2. Shall address non-functional product requirements, such as performance, scalability, reliability, fault tolerance, availability, maintainability, extensibility
            3. Shall be simple and comprehendible (to support maintainability and extensibility)
            4. Shall be well structured (support multiple tiers, parallel development etc.)
            5. Shall be detailed enough to share with different levels of organizational structure (marketing, sales, development, management)
            "Bad" architecture is basically opposite to "good" architecture.
          2. How much experience do you have with Enterprise applications? Another variant of this questions is: "Tell me about projects where you worked with J2EE?" Yet another version: "What, when and how made using EJB?"
            Interviewer is looking for your experience with designing J2EE applications and your experience with J2EE technologies and general terms. This is often start of the discussion and bridge to the technical section of the questions.
          3. What is scalability?
          4. What is high-availability? How is it different from scalability?
          5. What is the fault tolerance?
          6. What resources are used to keep up to date with J2EE technology?
            You may mention design pattern books, such as "Core EJB Patterns" and web sites, such as http://www.theserverside.com

          Specific technical questions

          1. What modeling tools you are familiar with? What version of TogetherJ (Rational Rose etc.) have you used?
          2. If stateless session bean more scalable than stateful session beans?
            This is very popular questions that leads to some confusion. According to the second edition of "Core J2EE Patterns" and contrary to popular belief, stateful session beans are not less scalable than stateless session bean. The reason for that is life cycle of either type is controlled by Application Server and control of life cycle is what defines the scalability of the application
          3. What's the difference between EJB 1.1 and EJB 2.0?
            There are many differences. Some key points you want to mention are:
            1. New CMP model
            2. EJB Query Language
            3. Local interfaces
            4. EJBHome methods
            5. Message Driven Beans (MDB) support
          4. What transaction isolation levels do you know?
            none, repeatable read, read committed, read uncommitted, serializable
          5. What transaction attributes do you know?
            requires new, required, supports, not supported, mandatory, never
          6. What is the difference between optimistic lock and pessimistic lock?
            Optimistic lock is an implicit lock that tries to make best assumption about locking strategy and minimize time spent in lock of resource. Optimistic lock is usually implemented with some kind of timestamp strategy. Pessimistic lock is an explicit lock that set by client.
          7. What are entity beans. Are there any issues with them?
            Typical reaction to this question is very expressive answer that entity beans should not be used. There are many performancy implications with entity beans if used incorrectly. One of the famous problems are "n+1 call problem" Inter-entity bean call is very expensive operation and should be avoided.
          8. What core design patterns do you know?
            Architect must know at least some basic design patters used in J2EE development, e.g. Business Delegate, Session Facade, VO, List Handler, DTO, Composite Entity, etc.
          9. Where business logic should reside?
            Typical answer is "in business tier" This usually opens series of questions like: What is business logic, how to determine business logic, how business logic is different from persistent logic etc.
          10. What is JDO?
            JDO is Java Data Object - persistent framework that is alternative to idea of entity beans
          11. What is the difference between JSP and servlet? When to use what?
            JSP is compiled into servlet. JSP are better suit to view of information, while servlets are better for controlling stuff.
          12. Does the J2EE platform support nested transactions?
            No.
          13. Can you use synchronization primitives in my enterprise beans?
            No.
          14. Why all major application server vendors provide custom class loaders in addition to system jvm class loader?
            System one does not support hot deployment.

          Performance questions

          1. What are performance problems in J2EE and how to solve them?
          2. What are Entity beans performance pitfalls?
          3. What performance pattern do you know?

          Design Pattern questions

          1. Can you use singleton in EJB?
            Yes, but should not (explain why)
          2. What is MVC pattern and why M, V and C need to be separated?
          3. Describe Business Delegate pattern (or any other pattern)
          4. How to prevent double submission of the form from JSP page? (or describe Synchronizer Token pattern)
          posted @ 2009-03-17 11:51 Sun River| 編輯 收藏

          Interview Questions on UML and Design Patterns

          Why to use design patterns?
          Give examples of design patterns?
          What is UML?
          What are advantages of using UML?
          What is the need for modelling?
          Is it requiste to use UML in software projects?
          What are use cases? How did you capture use cases in your project?
          Explain the different types of UML diagrams ? sequence diagram , colloboration diagram etc
          What is the sequence of UML diagrams in project?
          What tools did you use for UML in your project?
          What is the difference between activity and sequence diagrams?
          What are deployment diagrams?
          What are the different object relationships ?
          What is the difference between composition and aggregation?
          Wheel acting as a part of car ? Is this composition or aggregation?

          posted @ 2009-03-17 11:43 Sun River| 編輯 收藏
           

          spring與自動調度任務()

          面是自己自動調度的一些學習。
          這里只采用jdk自帶的timer進行的,準備在下篇文章中用Quartz調度器。
          首先建立你自己要運行的類。

          package com.duduli.li;

          public class Display {

              
          public void disp(){
                  System.out.println("
          自動控制測試");
              }
          }

          一個簡單的java bean,其中在這里你可以替換自己的任務。
          然后就是編寫調度程序,這里要繼承jdk中的TimerTask類,復寫他的run方法。

          package com.duduli.li;

          import java.util.TimerTask;

          public class AutoRan extends TimerTask {
              
          //set方法是springDI
              private Display display;
              
              
          public void setDisplay(Display display) {
                  
          this.display = display;
              }
              @Override
              
          public void run() {
                  display.disp();
              }
          }

          然后就是重要的一步,編寫applicationsContext.xml了。

          <?xml version="1.0" encoding="UTF-8"?>
          <beans
              
          xmlns="http://www.springframework.org/schema/beans"
              xmlns:xsi
          ="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation
          ="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
              
              
          <bean id="display"
                  class
          ="com.duduli.li.Display">
              
          </bean>
              
          <bean id="atuoRun"
                  class
          ="com.duduli.li.AutoRan">
                  
          <property name="display" ref="display"></property>
              
          </bean>
              
              
          <bean id="aR"
              class
          ="org.springframework.scheduling.timer.ScheduledTimerTask">
                  
          <property name="timerTask" ref="atuoRun"></property>
          <!--
          period
          多長時間運行一次,delay表示允許你當任務第一次運行前應該等待多久
          -->

                  
          <property name="period" value="5000"></property>
                  
          <property name="delay" value="2000"></property>    
              
          </bean>
              
              
          <bean id="test"
              class
          ="org.springframework.scheduling.timer.TimerFactoryBean">
                  
          <property name="scheduledTimerTasks">
                      
          <list>
          <!--
          這里使用list,可以調度多個bean
          -->

                          
          <ref bean="aR"/>
                      
          </list>
                  
          </property>
              
          </bean>
          </beans>


          再來就是客戶端調度了。

          package com.duduli.li;

          import org.springframework.beans.factory.BeanFactory;
          import org.springframework.context.support.ClassPathXmlApplicationContext;

          public class Client {

              
          public static void main(String[] args) {
                  BeanFactory factory = 
          new ClassPathXmlApplicationContext("applicationContext.xml");
                  factory.getBean("test");
              }
          }

          spring與自動調度任務()

          使用quartzspring自動調度。
          具體實現bean

          package com.duduli.li.quartz;

          import java.util.Date;

          public class Display {

              @SuppressWarnings("deprecation")
              
          public void disp(){
                  System.out.println(
          new Date().getSeconds());
                  System.out.println("
          自動控制測試");
              }
          }

          繼承quartzjobbean類:這個類和繼承Timer類類似

          package com.duduli.li.quartz;

          import org.quartz.JobExecutionContext;
          import org.quartz.JobExecutionException;
          import org.springframework.scheduling.quartz.QuartzJobBean;

          public class AutoRun extends QuartzJobBean{

              
          private Display  display;
              
              
          public void setDisplay(Display display) {
                  
          this.display = display;
              }

              @Override
              
          protected void executeInternal(JobExecutionContext arg0)
                      
          throws JobExecutionException {
                  display.disp();
              }
          }

          spring配置文件:

                              <!-- quartz進行自動調度 -->
          <!-- 具體實現類 -->
              
          <bean id="display2"    class="com.duduli.li.quartz.Display"></bean>
              
          <!-- springquartz的支持,Auto類實現quartzjob接口的類,jobDataAsMap是將實現類注入其中 -->
              
          <bean id="quartz" class="org.springframework.scheduling.quartz.JobDetailBean">
                  
          <property name="jobClass" value="com.duduli.li.quartz.AutoRun"/>
                  
          <property name="jobDataAsMap">
                      
          <map>
                          
          <entry key="display" value-ref="display2"></entry>
                      
          </map>
                  
          </property>
              
          </bean>
              
          <!-- springquartz的支持,對其值的設定 -->
              
          <bean id="simpleTask" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
                  
          <property name="jobDetail" ref="quartz"></property>
                  
          <property name="startDelay" value="2000"></property>
                  
          <property name="repeatInterval" value="2000"></property>
              
          </bean>
              
          <!-- 啟動自動調度 -->
              
          <bean id="quartzTest" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
                  
          <property name="triggers">
                      
          <list>
                          
          <ref bean="simpleTask"/>
                      
          </list>
                  
          </property>
              
          </bean>

          client調用:

          package com.duduli.li.quartz;


          import org.springframework.beans.factory.BeanFactory;
          import org.springframework.context.support.ClassPathXmlApplicationContext;

          public class Client {

              
          public static void main(String[] args) {
                      BeanFactory factory = 
          new ClassPathXmlApplicationContext("applicationContext.xml");
                      factory.getBean("quartzTest");
                  }
          }

          posted @ 2009-03-12 12:42 Sun River| 編輯 收藏

          Java implements a very efficient interprocess communication which reduces the CPU’s idle time to a very great extent. It is been implemented through wait ( ), notify ( ) and notifyAll ( ) methods. Since these methods are implemented as final methods they are present in all the classes.

          The basic functionality of each one of them is as under:


          wait( ) acts as a intimation to the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).

          notify( ) is used as intimator to wake up the first thread that called wait( ) on the same object.

          notifyAll( ) as the term states wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first.


          public class WaitNotifyAllExample {
           
          public static void main(String[] args) {
           
          try {
          Object o = new Object();
          Thread thread1 = new Thread(new MyOwnRunnable("A", o));
          Thread thread2 = new Thread(new MyOwnRunnable("B", o));
          Thread thread3 = new Thread(new MyOwnRunnable("C", o));
           
          // synchronized keyword acquires lock on the object.
          synchronized (o) {
          thread1.start();
          // wait till the first thread completes execution.
          // thread should acquire the lock on the object
          // before calling wait method on it. Otherwise it will
          // throw java.lang.IllegalMonitorStateException 
          o.wait();
          thread2.start();
          // wait till the second thread completes execution
          o.wait();
          thread3.start();
          }
           
          }
          catch (InterruptedException e) {
          e.printStackTrace();
          }
           
          }
          }
           
          class MyOwnRunnable implements Runnable {
           
          private String threadName;
           
          private Object o;
           
          public MyOwnRunnable(String name, Object o) {
          threadName = name;
          this.o = o;
          }
           
          public void run() {
           
           
          synchronized (o) {
          for (int i = 0; i < 1000; i++) {
          System.out.println("Thread " + threadName + " Count : " + i);
          }
          // notify all threads waiting for the object o.
          // thread should acquire the lock on the object
          // before calling notify or notifyAll method on it. 
          // Otherwise it will throw java.lang.IllegalMonitorStateException 
          o.notifyAll();
          }
          }
          }
          posted @ 2009-03-12 12:09 Sun River| 編輯 收藏
              只有注冊用戶登錄后才能閱讀該文。閱讀全文
          posted @ 2009-03-10 11:42 Sun River| 編輯 收藏

           What are JavaScript types? - Number, String, Boolean, Function, Object, Null, Undefined.

          1. How do you convert numbers between different bases in JavaScript? - Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16);
          2. What does isNaN function do? - Return true if the argument is not a number.
          3. What is negative infinity? - It’s a number in JavaScript, derived by dividing negative number by zero.

          4. What boolean operators does JavaScript support? - &&, || and !
          5. What does "1"+2+4 evaluate to? - Since 1 is a string, everything is a string, so the result is 124.
          6. How about 2+5+"8"? - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.
          7. What looping structures are there in JavaScript? - for, while, do-while loops, but no foreach.
          8. How do you create a new object in JavaScript? - var obj = new Object(); or var obj = {};
          9. How do you assign object properties? - obj["age"] = 17 or obj.age = 17.
          10. What’s a way to append a value to an array? - arr[arr.length] = value;
          11. What is this keyword? - It refers to the current object.
          posted @ 2009-03-10 11:37 Sun River| 編輯 收藏
               摘要:   閱讀全文
          posted @ 2009-03-10 11:36 Sun River| 編輯 收藏
           A SQL profile is sort of like gathering statistics on A QUERY - which involves many
          tables, columns and the like....
          In fact - it is just like gathering statistics for a query, it stores additional
          information in the dictionary which the optimizer uses at optimization time to determine
          the correct plan.  The SQL Profile is not "locking a plan in place", but rather giving
          the optimizer yet more bits of information it can use to get the right plan.
          posted @ 2009-01-28 11:14 Sun River| 編輯 收藏
          <SCRIPT LANGUAGE="JavaScript1.3">
          //Enter-listener
          if (document.layers)
            document.captureEvents(Event.KEYDOWN);
            document.onkeydown =
              function (evt) {
                var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
                if (keyCode == 13)   //13 = the code for pressing ENTER

                {
                   document.form.submit();
                }
              }
          </SCRIPT>
          posted @ 2008-04-23 12:11 Sun River| 編輯 收藏
           

          My top javascripts

          ---. ExpandCollapse

           Used for expanding and collapsing block elements. I use this one for hiding divs or expanding the divs for forms. Very useful.

           function expandCollapse() {
          for (var i=0; i<expandCollapse.arguments.length; i++) {
          var element = document.getElementById(expandCollapse.arguments[i]);
          element.style.display = (element.style.display == "none") ? "block" : "none";
           }
          }
           
          <p><em>Example:</em></p>
           <div id="on" style="border: 1px solid #90ee90;padding: 5px;">
             <a href="javascript: expandCollapse('expand', 'on');">Expand Layer</a>
           </div>
           <div id="expand" style="display: none;border: 1px solid #90ee90;padding: 5px;">
           <a href="javascript: expandCollapse('expand', 'on');">Collapse Layer</a>
           <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Quisque eu ligula.   Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Ut wisi. Curabitur odio. Sed ornare arcu id diam. Integer ultricies, mauris venenatis vulputate pulvinar</p>
          </div>

          --Timer Layer

          Used for hiding an element after ‘x’ of seconds. Great for hiding status messages after a person has submitted a form.

          var timerID;
           
          function ShowLayer(id)
          {
           document.getElementById().style.display = "block"; 
          }
           
          function HideTimedLayer(id)
              clearTimeout(timerID);
              document.getElementById(id). »
                   style.display = "none";
          }
           
          function timedLayer(id)
          {
           setTimeout("HideTimedLayer(""" + id + """)",»
            5000); //5000= 5 seconds
          }

          --Form Checker

          Probably one of the most useful scripts and there are several out there about form validation. This figures out what fields are required from the value in in a hidden input tag. Than it highlights the error areas.

          for (var j=0; j<myForm.elements.length; j++) {
          var myElement = myForm.elements[j];
          var isNull = false;
          if (myElement.name == field && myElement.»
          style.display != "none") {
          if (myElement.type == "select-one" || »
          myElement.type == "select-multiple") {
          if ((myElement.options[myElement.selectedIndex].
          »value == null || myElement.
          »options[myElement.
          »selectedIndex].value == '') 
          »&& errorString.indexOf(title) == -1) {
          isNull = true;
          }
          } else if ((myElement.value == null || 
          »myElement.value.search(/"w/)»
           == -1) && errorString.indexOf(title) == -1) {
          isNull = true;
          }
           
          if (isNull) {
          errorString += title + ", ";
          if (document.getElementById('label_'+myElement.name))»
           { document.getElementById('label_'+myElement.name)
           ».className="er"; }
          myElement.className="erInput";
          } else {
          if (document.getElementById('label_'+myElement.name)) {
          document.getElementById('label_'+myElement.name)
          ».className="s1";
          }
          myElement.className="s1";
          }
          }
          }
          }
          if (errorString != '') {
          errorString = errorString.slice(0,errorString.length-2);
          window.alert("Please fill in the following 
          »required fields before submitting this form:"n"n"+errorString)
          return false;
          }
          else {
          return true;
          }
          }

          ---今天練習了一下用javascript做文字自動匹配的功能,類似于Google Suggest,當然人家Google是連接后臺數據庫,在網上不方便做連接數據庫,所有功能在前臺實現。在javascript里定義了一個全局數組arrCities用來存儲一些城市的名字。然后當我們在文本輸入框里輸入某個城市名字的時候,每輸入完一個字,就會拿當前的文字到arrCities數組里去比對,看是否存在于arrCities的某個成員里。若存在,就把該成員添加到緊靠文本輸入框下面的組合列表框里,供我們選擇,這樣我們就不用完全輸入完整個城市的名字,只要
          從下面選擇一個就可以完成想要做的工作。看下面的例子:

          <html>
          <head>
          <title>Autosuggest Example</title>
          <script type="text/javascript">
          var arrCities=["
          北京","上海"];
          arrCities.sort();
          //
          控制是否顯示層div1,bFlagtrue則表示顯示div1,false則把div1從頁面流里移除
          function showDiv1(bFlag){
          var oDiv=document.getElementById("div1");
          if(bFlag){
          oDiv.style.display="block";
          }
          else{
          oDiv.style.display="none";
          }
          };
          //
          sel1添加option
          function addOption(oListbox,sText){
          var oOption=document.createElement("option");
          oOption.appendChild(document.createTextNode(sText));
          oListbox.appendChild(oOption);
          };
          //
          移除一個option
          function removeOption(oListbox,iIndex){
          oListbox.remove(iIndex);
          };
          //
          移除所有的option
          function clearOptions(oListbox){
          for(var i=oListbox.options.length-1;i>=0;i--){
          removeOption(oListbox,i);
          }
          };
          //
          設置select里的第一個option被選中
          function setFirstSelected(oListbox){
          if(oListbox.options.length>0){
          oListbox.options[0].selected=true;
          }
          }
          //
          獲取匹配的字段
          function getAutosuggestMatches(sText,arrValues){
          var arrResult=new Array;
          if(sText!=""){
          for(var i=0;i<arrValues.length;i++){
          if(arrValues[i].indexOf(sText)==0){
          arrResult.push(arrValues[i]);
          }
          }
          }
          else{
          showDiv1(false);
          }
          return arrResult;
          };
          //
          把匹配的字段添加到sel1
          function addSuggestOptions(oTextbox,arrValues,sListboxId,oEvent){
          var oListbox=document.getElementById(sListboxId);
          clearOptions(oListbox);
          var arrMatches=getAutosuggestMatches(oTextbox.value,arrValues);
          if(arrMatches.length>0){
          showDiv1(true);
          for(var i=0;i<arrMatches.length;i++){
          addOption(oListbox,arrMatches[i]);
          }
          setFirstSelected(oListbox);
          if(oEvent.keyCode==8){
          oTextbox.focus();
          }
          else{
          oListbox.focus();
          }
          }
          };
          //
          獲取select里的optiontextbox
          function getSuggestText(oListbox,sTextboxId){
          var oTextbox=document.getElementById(sTextboxId);
          if(oListbox.selectedIndex>-1){

          oTextbox.value=oListbox.options[oListbox.selectedIndex].text;
          }
          oTextbox.focus();
          showDiv1(false);
          }
          //
          通過Enter鍵確定選項
          function getSuggestText2(oListbox,sTextboxId,oEvent){
          if(oEvent.keyCode==13){
          getSuggestText(oListbox,sTextboxId);
          }
          }
          </script>
          </head>
          <body>
          <p>
          請輸入一個城市的名字:</p>
          <p>
          <input type="text" id="txt1" value="" size="27"
          onkeyup="addSuggestOptions(this,arrCities,'sel1',event)" /><br />
          <div id="div1" style="background-color:white;display:none;">
          <select id="sel1" style="width:202px" size="6"
          onclick="getSuggestText(this,'txt1')" onkeyup="getSuggestText2(this,'txt1',event)">
          </select>
          </div>
          </p>
          </body>
          </html>

          用到的東西都比較基礎,當然有很多細節性的東西需要注意。比如說用戶選擇完一個選項,要注意把組合列表框隱藏。所以這里把組合列表框放在了一個層上,隱藏和顯示控制起來就方便一點。

          --jsinnerHTMLinnerTextouterHTML的用法和區別

          用法:
          <div id="test">
          <span style="color:red">test1</span> test2
          </div><div id="test">
          <span style="color:red">test1</span> test2
          </div>

          JS中可以使用:

          test.innerHTML: 也就是從對象的起始位置到終止位置的全部內容,包括Html標簽。
          上例中的test.innerHTML的值也就是
          <span style="color:red">test1</span> test2<span style="color:red">test1</span> test2

          test.innerText: 從起始位置到終止位置的內容, 但它去除Html標簽
          上例中的text.innerTest的值也就是“test1 test2”, 其中span標簽去除了。

          test.outerHTML: 除了包含innerHTML的全部內容外, 還包含對象標簽本身。
          上例中的text.outerHTML的值也就是
          <div id="test"><span style="color:red">test1</span> test2</div><div id="test"><span style="color:red">test1</span> test2</div>

          完整示例:
          <div id="test">
          <span style="color:red">test1</span> test2
          </div>

          <a href="javascriptalert(test.innerHTML)">innerHTML內容</a>
          <a href="javascript
          alert(test.innerText)">inerHTML內容</a>
          <a href="javascript
          alert(test.outerHTML)">outerHTML內容</a><div id="test">
          <span style="color:red">test1</span> test2
          </div>

          <a href="javascriptalert(test.innerHTML)">innerHTML內容</a>
          <a href="javascript
          alert(test.innerText)">inerHTML內容</a>
          <a href="javascript
          alert(test.outerHTML)">outerHTML內容</a>

          特別說明:

          innerHTML是符合W3C標準的屬性,而innerText只適用于IE瀏覽器,因此,盡可能地去使用innerHTML,而少用innerText,如果要輸出不含HTML標簽的內容,可以使用innerHTML取得包含HTML標簽的內容后,再用正則表達式去除HTML標簽,下面是一個簡單的符合W3C標準的示例:
          <div id="test">
          <span style="color:red">test1</span> test2
          </div>
          <a href="javascript
          alert(document.getElementById('test').innerHTML.replace(/<.+?>/gim,''))">HTML,符合W3C標準</a>

           

          --Javascript長文章分頁

          本例中實現用Javascript 長文章分頁,Javascript 分頁

          <html>
          <head>
          <style type="text/css">
          <!--
          #jiax{
          width:80%;/*
          調整顯示區的寬*/
          height:200px;/*
          調整顯示區的高*/
          font-size:14px;
          line-height:180%;
          border:1px solid #000000;
          overflow-x:hidden;
          overflow-y:hidden;
          word-break:break-all;
          }
          a{
          font-size:12px;
          color:#000000;
          text-decoration:underline;
          }
          a:hover{
          font-size:12px;
          color:#CC0000;
          text-decoration:underline;
          }
          //-->
          </style>
          </head>
          <body>
          <div id="jiax">
          本屆都靈冬奧會,-------------------------------------------上屆冬奧會,他們依然以13金傲視群雄。

          </div>
          <P>
          <div id="pages" style="font-size:12px;"></div>
          <script language="javascript">
          <!--
          var obj = document.getElementById("jiax");
          var pages = document.getElementById("pages");
          window.onload = function(){
          var allpages = Math.ceil(parseInt(obj.scrollHeight)/parseInt(obj.offsetHeight));
          pages.innerHTML = "<b>
          "+allpages+"</b>";
          for (var i=1;i<=allpages;i++){
          pages.innerHTML += "<a href=""javascript
          showpart('"+i+"');"">"+i+"</a>&nbsp;";

          }
          }
          function showpart(x){
          obj.scrollTop=(x-1)*parseInt(obj.offsetHeight);
          }
          //-->
          </script>
          </body>
          </html>

          --js實現selectdiv的隱藏與顯示

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "http://www.w3.org/TR/html4/loose.dtd">
          <html>
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
          <title>
          無標題文檔</title>
          </head>

          <body>

          <script type="text/javascript">
          function change(a){
          var xxx = document.getElementById("xxx");
          var divArray = xxx.getElementsByTagName("div");
          for (var i=0;i<divArray.length;i++) {
          if (divArray[i].id == a) {
          divArray[i].style.display='';
          }else {
          divArray[i].style.display='none';
          }
          }
          }
          </script>

          <div id=xxx>


          <div id=aaa>
          <h1>aa</h1>
          aaaa
          </div>
          <div id=bbb style="display:none ">
          bbbb
          </div>
          <div id=ccc style="display:none ">
          cccc
          </div>

          </div>

          <select onChange="change(this.value)">
          <option value="aaa">aaa</option>
          <option value="bbb">bbb</option>
          <option value="ccc">ccc</option>
          </select>
          </body>
          </html>

          ---++日期減去天數等于第二個日期
          <script language=Javascript>
          function cc(dd,dadd)
          {
          //
          可以加上錯誤處理
          var a = new Date(dd)
          a = a.valueOf()
          a = a - dadd * 24 * 60 * 60 * 1000
          a = new Date(a)
          alert(a.getFullYear() + "
          " + (a.getMonth() + 1) + "" + a.getDate() + "")
          }
          cc("12/23/2002",2)
          </script>

          ++++檢查一段字符串是否全由數字組成
          <script language="Javascript"><!--
          function checkNum(str){return str.match(//D/)==null}
          alert(checkNum("1232142141"))
          alert(checkNum("123214214a1"))
          // --></script>

          +++++++++++++

          --js處理輸出分頁(完美版)

          head>
          <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
          <title>
          無標題文檔</title>
          <style type="text/css">
          <!--
          div{font-size:14px;}
          -->
          </style>
          </head>

          <body>
          <textarea name="" cols="" rows="" id="conpage" style="display:none;">
          <!--pages-->
          你好
          <!--pages-->
          我好
          <!--pages-->
          他也好
          <!--pages-->
          全都好
          <!--pages-->
          </textarea>
          <script language="javascript">
          var zhenze = /[^0-9]/;//
          創建正則,表明非數字字符串
          var thispage = document.getElementById("conpage").value;//
          取得內容
          var page_amount,x;
          page_amount = thispage.split('<!--pages-->').length;
          page_amount--;//
          內容里的pages個數
          var asarray = new Array();//
          數組
          var v=0;
          for(var t=0;t<page_amount;t++){
          asarray[t] = thispage.indexOf("<!--pages-->",v);//
          記錄每個pages的位置
          v=asarray[t];
          v++;
          };
          page_amount--;
          for(var s=0;s<page_amount;s++){
          //
          以下是分段寫出所有內容
          document.write('<div id="pg'+(s+1)+'" style="block">');
          document.write(thispage.substring(asarray[s],asarray[s+1]));
          document.write('</div>');
          alert(s+1);
          };


          var obj,objt;
          var s_a_d = 1;//
          記錄當前顯示的頁數id,默認為第1頁顯示,當設用showpage時,此變量用于記錄上次所顯示的頁碼,
          function hidpage(hidt){//
          此函數用于隱藏頁數
          obj=eval("document.getElementById('pg"+hidt+"')");
          obj.style.display = "none";
          };

          function showpage(sow){//
          此函數用于顯示頁數
          obj = eval("document.getElementById('pg"+sow+"')");
          objt = eval("document.getElementById('pg"+(s_a_d)+"')");//
          此句是取得上次顯示的頁碼
          objt.style.display = "none";//
          先隱藏上次顯示的頁碼
          obj.style.display = "block";//
          再顯示當前用戶需要顯示的頁碼
          s_a_d = sow;
          document.getElementById("pageamo").value = sow;
          alert("
          當前顯示第"+s_a_d+"");
          };

          var tts;
          function goto(){ //
          頁面轉向函數,作用是用戶在文本框里輸入頁碼然后轉向
          tts = document.getElementById("inputpage").value;
          if(!tts.match(zhenze)==""){
          alert("
          錯誤,你輸入了非數字類型字符");
          return;
          };
          if(tts>page_amount || tts < 1){
          alert("
          無此頁");//非法輸入全部檢驗完畢
          }else{
          showpage(tts);//
          合法的執行轉向
          };
          };


          document.write('<div>');
          document.write('
          你現在在第<input type="button" id="pageamo" value="'+s_a_d+'" style="font-size:12px;height:18px;background-color:#FFFFFF; color:red;font-weight:bold;border:#FFFFFF 0px solid;"> ');//標示當前頁碼
          document.write('
          共有'+page_amount+'');//總頁數
          for(var k=0;k<page_amount;k++){
          document.write(' <a href="javascript
          showpage('+(k+1)+')" style="text-decoration:none;">');
          document.write(" ["+(k+1)+"] ");
          document.write('</a> ');
          hidpage(k+1);//
          隱藏所有頁數
          };//for
          寫出頁碼 : 1 2 3 4 5 ....
          showpage(1);//
          首先顯示第一頁內容
          document.write('
          轉到第 <input type="text" id="inputpage" style="width:20px;font-size:12px;height:18px;" value=""> ');//轉向表單
          document.write('<input type="button" value=" Go " onclick="goto()" style="height:20px;">');
          document.write('</div>');
          </script>
          </body>
          </html>

          posted @ 2008-02-22 22:13 Sun River| 編輯 收藏
           

          Javascript Table filter

          This is a simple but powerful javascript to filter a standard html table. The user enters a term in a text field and just the table entries which contain it will be shown.

          function filter (term, _id, cellNr){
                         var suche = term.value.toLowerCase();
                         var table = document.getElementById(_id);
                         var ele;
                         for (var r = 1; r < table.rows.length; r++){
                                         ele = table.rows[r].cells[cellNr].innerHTML.replace(/<[^>]+>/g,"");
                                         if (ele.toLowerCase().indexOf(suche)>=0 )
                                                        table.rows[r].style.display = '';
                                         else table.rows[r].style.display = 'none';
                         }
          }

          This function searches in the table with the id defined by _id in every row in the cell defined by cellNr. The search is case insensitive.
          The usage is straightforward:

          <form>
                         <input name="filter" onkeyup="filter(this, 'sf', 1)" type="text">
          </form>

          It should work with all modern browsers, e.g. IE5, Firefox 1.0, Opera 7 and Mozilla 1.0.

          Since many people have asked for another version of the script which

          • searches in every cell of a row
          • searches for more than one keyword (using AND)

          I have made another version of the script:

          function filter2 (phrase, _id){
                         var words = phrase.value.toLowerCase().split(" ");
                         var table = document.getElementById(_id);
                         var ele;
                         for (var r = 1; r < table.rows.length; r++){
                                         ele = table.rows[r].innerHTML.replace(/<[^>]+>/g,"");
                                 var displayStyle = 'none';
                                 for (var i = 0; i < words.length; i++) {
                                             if (ele.toLowerCase().indexOf(words[i])>=0)
                                                        displayStyle = '';
                                            else {
                                                        displayStyle = 'none';
                                                        break;
                                             }
                                 }
                                         table.rows[r].style.display = displayStyle;
                         }
          }

          Web designers must always keep usability in mind when designing web sites. A site must allow quick and easy access to information during the very short time that a site first holds a visitor's interest. Any confusion that ensues about where things are, and that person's business is gone. Providing a way to precisely search for what they need is an excellent way to provide that usability. What Chris Root explains in this article is a way for your visitors to find and select items contained in long lists. He will also suggest ways to expand this to searching within HTML or XML documents.

          Auto-Complete

          Many desktop applications have user interface controls that allow a user to find matches for things as they type. This feature can be very useful for long lists of items such as states, countries, streets or product categories. Many web browsers implement this sort of functionality in their address bars. As you type, web site address matches that are part of a list of recently visited sites appear in a menu below the address bar. This reduces the amount of time it takes to access information.

          Another place this is implemented is in HTML select menus. Unfortunately this only works with the first letter typed, it is not implemented in all browsers on all platforms and it doesn't shorten the list of choices to only matches.

          The script described in this article will allow a user to begin typing what they are looking for in a text box while a select menu updates itself with matches. In the example the list comes from the contents of the select menu but it can also come from other sources.

          The HTML

          The HTML for this project is pretty simple. You could however use this script several places in a large form with multiple lists of information with no trouble. This example uses a list of city streets.

          <body onLoad="fillit(sel,entry)">
          <div>Enter the first three letters of a street and select a match from the menu.</div>
          <form><label>
          Street
          <input type="text" name="Street" id="entry" onKeyUp="findIt(sel,this)"><br>
            <select id="sel">
                  <option value="s0001">Adams</option>
                  <option value="s0002">Alder</option>
                  <option value="s0003">Banner</option>
                  <option value="s0004">Birchtree</option>
                  <option value="s0005">Brook</option>
                  <option value="s0007">Cooper</option>
          <!--and so on and so forth-->
            </select></label>
          </form>
          </body>
          </html>

          When the text box registers a keyUp event, the find() function calls and passes two parameters, the id of the select menu and a reference to the text field.

          For something like state information, allow the user the choice of using the auto-complete script or just selecting something from the menu, especially if they know the item they wish to select is at the top of the list. If someone lives in Alabama for instance, there is no need to have them enter the first three letters of their state when the item they want is at the top of the list of states. Fill the select menu (a list box can be used as well) with all the values and text labels that you want your user to choose from in the HTML code to start with.

          Alternatively, depending on the information in the list, the choice may not be as obvious. In this case you could store it in an array only and the user would always need to select a match. If there was only one match, and that match was the correct one, they could leave the menu alone. Otherwise they would need to select from the available matches displayed in the menu.

          The longer the list the more useful our script becomes. It has been tested with a list over 1000 city streets and had an acceptable performance, even on a not so modern machine. There is a minimum of two characters before a search will start. this helps reduce the number of matches shown after any given keystroke. This limit can be adjusted easily.

          When the page loads, a function called fillit() is called.

          //initialize some global variables
          var list = null;;
          function fillit(sel,fld)
          {
                  var field = document.getElementByid(fld);
                  var selobj = document.getElementById(sel);
                  if(!list)
                  {
                          ar len = selobj.options.length;
                          field.value = "";
                          list = new Array();
                          for(var i = 0;i < len;i++)
                          {
                                  list[i] = new Object();
                                  list[i]["text"] = selobj.options[i].text;
                                  list[i]["value"] = selobj.options[i].value;
                          }
                  }
                  else
                  {
                      var op = document.createElement("option");
                      var tmp = null;
                      for(var i = 0;i < list.length;i++)
                     {
                          tmp = op.cloneNode(true);
                          tmp.appendChild(document.createTextNode(list[i]["text"]));
                          tmp.setAttribute("value",list[i]["value"]);
                          selobj.appendChild(tmp)/*;*/
                     }
                  }
          }

          A global variable is initialized to null. This will hold an array that in turn holds two custom objects to hold our data. We then get a reference to our select menu and text field objects. If our array does not exist yet (the page has just loaded so it’s still null), then we get the number of options in our select menu, set the contents of the text field to empty and begin looping through the menu contents.

          As we run through each menu option, an object is created that will hold both what is in the value attribute and the text of the option tag.

          If however our list array already exists, we are calling the function in order to refill the menu with all the original data. An option element is created and a temporary container is initialized.

          In the loop the select menu is reconstructed using DOM methods.

          Finding a Match

          The findIt() function does the searching. It accepts two arguments. The first is the name of the select menu, the second is the name of the text field.

          function findit(sel,field)
          {
                  var selobj = document.getElementById(sel);
                  var d = document.getElementById("display");
                  var len = list.length;
                  if(field.value.length > 2)
                  {
                          if(!list)
                          {
                                  fillit(sel,field);
                          }
                          var op = document.createElement("option");
                          selobj.options.length = 1
                          var reg = new RegExp(field.value,"i");
                          var tmp = null;
                          var count = 0;
                          var msg = "";
                          for(var i = 0;i < len;i++)
                          {
                                  if(reg.test(list[i].text))
                                  {
                                          d.childNodes[0].nodeValue = msg;
                                          tmp = op.cloneNode(true);
                                          tmp.setAttribute("value",list[i].value);
                                          tmp.appendChild(document.createTextNode(list[i].text));
                                          selobj.appendChild(tmp);
                                  }
                          } 
                  }
                  else if(list && len > selobj.options.length)
                  {
                          selobj.selectedIndex = 0;
                          fillit(sel,field);
                  }
          }

          The first step is to get references to the select menu and the text field. We also need the length of the list array.

          If the number of characters in the text field is greater than 2 and the list array exists. Then the menu is cleared of it's content to prepare it for display of any matches. The number of options is set to one rather than 0 to allow for an option that is always there such as a “Select a Street” option.

          A regular expression object is then created that will be used to look for a match at the beginning of a given string. Using this object to create a regular expression allows the use of a string from whatever source we wish to be used along with any regular expression characters. The first parameter in the object constructor is the regular expression the second is any flags such as "i" for making the search case insensitive. If you were searching something other than one or two word street names, state names or country names you would want to match the beginning of word boundaries using ""b" instead of "^".

          A few utility variables are initialized and we then loop through each of the list items contained in the arrays. If there is a match, the values are used to fill a new copy of the option element we created before the loop started. One thing to note about setting the properties of option elements is that the text label of an option is not an attribute. You must use the optionelement.text syntax rather than setAttribute to set the text label for each option.

          If the length of the text in the field is less than 2 characters then we need to determine if the list needs to be refilled with all the values. By doing this, you allow the user to give up on their search before typing more than two characters and manually select something from the menu if they wish. If the user selects the text in the field and clears it to start a new search this will trigger that action. The fillit function is called and the select menu is refilled.

          Possible Mods

          To make this script and user interface more like the auto-complete widget in a browser address bar, you could use a DHTML menu and provide keyboard control for selecting a match and updating the content in the text box with the selected match.

          This script would allow searching in any array of information and with a little modification any HTML collection. Searchable FAQ's, API documentation or help systems could be achieved by searching content contained in a hidden IFrame, the main HTML document itself or an XML document loaded in the background using the HTTPRequest object.

          Conclusion

          As you can see using auto-complete widgets on a web site can allow a visitor quick access to information. Always be on the lookout for ways to improve the user experience for your visitors and they will continue to come back for more.

          posted @ 2008-02-22 22:12 Sun River| 編輯 收藏
               摘要:   9 Javascript(s) you better not miss !! ...  閱讀全文
          posted @ 2008-02-22 22:10 Sun River| 編輯 收藏
          http://www.dojoforum.com/taxonomy/term/8
          http://www.dojoforum.com/
          posted @ 2008-02-19 13:50 Sun River| 編輯 收藏
          from : http://www.demay-fr.net:8080/Wicket-start/app

          package wicket.contrib.dojo.examples;

          import java.util.ArrayList;
          import java.util.Iterator;

          import wicket.PageParameters;
          import wicket.contrib.dojo.html.list.lazy.DojoLazyLoadingListContainer;
          import wicket.contrib.dojo.html.list.lazy.DojoLazyLoadingRefreshingView;
          import wicket.extensions.markup.html.repeater.refreshing.Item;
          import wicket.markup.html.WebPage;
          import wicket.markup.html.basic.Label;

          public class LazyTableSample extends WebPage {

          public LazyTableSample(PageParameters parameters){
          DojoLazyLoadingListContainer container = new DojoLazyLoadingListContainer(this, "container", 3000)
          DojoLazyLoadingRefreshingView list = new DojoLazyLoadingRefreshingView(container, "table"){

          @Override
          public Iterator iterator(int first, int count) {
          ArrayList<String> list = new ArrayList<String>();
          int i = 0;
          while(i < count){
          list.add("foo" + (first + i++));
          }

          //fake a busy and slow machine
          int j = 0;
          while (j < 1000000000){j++;}

          return list.iterator();
          }

          @Override
          protected void populateItem(Item item) {
          new Label(item, "label",item.getModel());
          }

          };
          }
          }

          posted @ 2008-02-19 13:45 Sun River| 編輯 收藏
               摘要:   Dojo API略解續 dojo.lang.string dojo.string.substituteParams 類似C#中的String.Format函數 %{name}要保...  閱讀全文
          posted @ 2008-02-19 11:30 Sun River| 編輯 收藏
           

          1. How someone can define that a method should be execute inside read-only transaction semantics?

            A

          It is not possible

            B

          No special action should be taken, default transaction semantics is read-only

            C

          It is possible using the following snippet:
          <tx:methodname="some-method"semantics="read-only"/>

          D

          It is possible using the following snippet:
          <tx:methodname="some-method"read-only="true"/>  

          explanation

          Default semantics in Spring is read/write, and someone should use read-only attribute to define read-only semantics for the method.

          2.      What is the correct way to execute some code inside transaction using programmatic transaction management?

           A

          Extend TransactionTemplate class and put all the code inside execute() method.

            B

          Implement class containing business code inside the method. Inject this class into TransactionManager.

          C

          Extend TransactionCallback class. Put all the code inside doInTransaction() method. Pass the object of created class as parameter to transactionTemplate.execute() method. 

            D

          Extend TransactionCallback class. Put all the code inside doInTransaction() method. Create the instance of TransactionCallback, call transactionCallback.doInTransaction method and pass TransactionManager as a parameter.

          3. Select all statements that are correct.

          Spring provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.

          The Spring Framework supports declarative transaction management.

          Spring provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.

          The transaction management integrates very well with Spring's various data access abstractions.

          4. Does this method guarantee that all of its invocations will process data with ISOLATION_SERIALIZABLE?
          Assume
          txManager to be valid and only existing PlatformTransactionManager .
          publicvoid query(){
                 DefaultTransactionDefinition txDef =newDefaultTransactionDefinition();
                 txDef.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
                 txDef.setReadOnly(true);
                 txDef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                 TransactionStatus txStat = txManager.getTransaction(txDef);
                 // ...
                 txManager.commit(txStat);
          }

          explanation

          If this method executes within an existing transaction context, it's isolation level will reflect the existing isolation level. For example JDBC does not specify what happens when one tries to change isolation level during existing transaction. PROPAGATION_REQUIRES_NEW will assure that transaction isolation is set to serializable.

          5. You would like to implement class with programmatic transaction management.
          How can you get TransactionTemplate instance?

          It is necessary to implement a certain interface in this class and then use getTransactionTemplate() call.

           

          It is possible to declare TransactionTemplate object in configuration file and inject it in this class.

          It is possible to declare PlatformTransactionManager object in configuration file, inject the manager in this class and then create TransactionTemplate like
          TransactionTemplate transactionTemplate =newTransactionTemplate(platformTransactionManager);

          It's possible to inject either PlatformTransactionManager or TransactionTemplate in this class.
          Option one is obviously wrong.

          6. Check the correct default values for the @Transactional annotation.

          PROPAGATION_REQUIRED

          The isolation level defaults to the default level of the underlying transaction system.

          readOnly="true"

           

          Only the Runtime Exceptions will trigger rollback.

          The transaction timeout defaults to the default timeout of the underlying transaction system, or none if timeouts are not supported.

          7. To make a method transactional in a concrete class it's enough to use @Transactional annotation before the method name (in Java >=5.0).

          correct answer

          FALSE

          explanation

          No, @Transactional annotation only marks a method as transactional. To make it transactional it is necessary to include the <tx:annotation-driven/> element in XML configuration file.

          8. The JtaTransactionManager allows us to use distributed transactions. (t)
          posted @ 2007-12-01 15:20 Sun River| 編輯 收藏
          現在JDK1.4里終于有了自己的正則表達式API包,JAVA程序員可以免去找第三方提供的正則表達式庫的周折了,我們現在就馬上來了解一下這個SUN提供的遲來恩物- -對我來說確實如此。
          1.簡介:
          java.util.regex是一個用正則表達式所訂制的模式來對字符串進行匹配工作的類庫包。

          它包括兩個類:Pattern和Matcher Pattern 一個Pattern是一個正則表達式經編譯后的表現模式。
          Matcher 一個Matcher對象是一個狀態機器,它依據Pattern對象做為匹配模式對字符串展開匹配檢查。


          首先一個Pattern實例訂制了一個所用語法與PERL的類似的正則表達式經編譯后的模式,然后一個Matcher實例在這個給定的Pattern實例的模式控制下進行字符串的匹配工作。

          以下我們就分別來看看這兩個類:

          2.Pattern類:
          Pattern的方法如下: static Pattern compile(String regex)
          將給定的正則表達式編譯并賦予給Pattern類
          static Pattern compile(String regex, int flags)
          同上,但增加flag參數的指定,可選的flag參數包括:CASE INSENSITIVE,MULTILINE,DOTALL,UNICODE CASE, CANON EQ
          int flags()
          返回當前Pattern的匹配flag參數.
          Matcher matcher(CharSequence input)
          生成一個給定命名的Matcher對象
          static boolean matches(String regex, CharSequence input)
          編譯給定的正則表達式并且對輸入的字串以該正則表達式為模開展匹配,該方法適合于該正則表達式只會使用一次的情況,也就是只進行一次匹配工作,因為這種情況下并不需要生成一個Matcher實例。
          String pattern()
          返回該Patter對象所編譯的正則表達式。
          String[] split(CharSequence input)
          將目標字符串按照Pattern里所包含的正則表達式為模進行分割。
          String[] split(CharSequence input, int limit)
          作用同上,增加參數limit目的在于要指定分割的段數,如將limi設為2,那么目標字符串將根據正則表達式分為割為兩段。


          一個正則表達式,也就是一串有特定意義的字符,必須首先要編譯成為一個Pattern類的實例,這個Pattern對象將會使用matcher()方法來 生成一個Matcher實例,接著便可以使用該 Matcher實例以編譯的正則表達式為基礎對目標字符串進行匹配工作,多個Matcher是可以共用一個Pattern對象的。

          現在我們先來看一個簡單的例子,再通過分析它來了解怎樣生成一個Pattern對象并且編譯一個正則表達式,最后根據這個正則表達式將目標字符串進行分割:
          import java.util.regex.*;
          public class Replacement{
          public static void main(String[] args) throws Exception {
          // 生成一個Pattern,同時編譯一個正則表達式
          Pattern p = Pattern.compile("[/]+");
          //用Pattern的split()方法把字符串按"/"分割
          String[] result = p.split(
          "Kevin has seen《LEON》seveal times,because it is a good film."
          +"/ 凱文已經看過《這個殺手不太冷》幾次了,因為它是一部"
          +"好電影。/名詞:凱文。");
          for (int i=0; i
          System.out.println(result[i]);
          }
          }



          輸出結果為:

          Kevin has seen《LEON》seveal times,because it is a good film.
          凱文已經看過《這個殺手不太冷》幾次了,因為它是一部好電影。
          名詞:凱文。

          很明顯,該程序將字符串按"/"進行了分段,我們以下再使用 split(CharSequence input, int limit)方法來指定分段的段數,程序改動為:
          tring[] result = p.split("Kevin has seen《LEON》seveal times,because it is a good film./ 凱文已經看過《這個殺手不太冷》幾次了,因為它是一部好電影。/名詞:凱文。",2);

          這里面的參數"2"表明將目標語句分為兩段。

          輸出結果則為:

          Kevin has seen《LEON》seveal times,because it is a good film.
          凱文已經看過《這個殺手不太冷》幾次了,因為它是一部好電影。/名詞:凱文。

          由上面的例子,我們可以比較出java.util.regex包在構造Pattern對象以及編譯指定的正則表達式的實現手法與我們在上一篇中所介紹的 Jakarta-ORO 包在完成同樣工作時的差別,Jakarta-ORO 包要先構造一個PatternCompiler類對象接著生成一個Pattern對象,再將正則表達式用該PatternCompiler類的 compile()方法來將所需的正則表達式編譯賦予Pattern類:

          PatternCompiler orocom=new Perl5Compiler();

          Pattern pattern=orocom.compile("REGULAR EXPRESSIONS");

          PatternMatcher matcher=new Perl5Matcher();

          但是在java.util.regex包里,我們僅需生成一個Pattern類,直接使用它的compile()方法就可以達到同樣的效果:
          Pattern p = Pattern.compile("[/]+");

          因此似乎java.util.regex的構造法比Jakarta-ORO更為簡潔并容易理解。

          3.Matcher類:
          Matcher方法如下: Matcher appendReplacement(StringBuffer sb, String replacement)
          將當前匹配子串替換為指定字符串,并且將替換后的子串以及其之前到上次匹配子串之后的字符串段添加到一個StringBuffer對象里。
          StringBuffer appendTail(StringBuffer sb)
          將最后一次匹配工作后剩余的字符串添加到一個StringBuffer對象里。
          int end()
          返回當前匹配的子串的最后一個字符在原目標字符串中的索引位置 。
          int end(int group)
          返回與匹配模式里指定的組相匹配的子串最后一個字符的位置。
          boolean find()
          嘗試在目標字符串里查找下一個匹配子串。
          boolean find(int start)
          重設Matcher對象,并且嘗試在目標字符串里從指定的位置開始查找下一個匹配的子串。
          String group()
          返回當前查找而獲得的與組匹配的所有子串內容
          String group(int group)
          返回當前查找而獲得的與指定的組匹配的子串內容
          int groupCount()
          返回當前查找所獲得的匹配組的數量。
          boolean lookingAt()
          檢測目標字符串是否以匹配的子串起始。
          boolean matches()
          嘗試對整個目標字符展開匹配檢測,也就是只有整個目標字符串完全匹配時才返回真值。
          Pattern pattern()
          返回該Matcher對象的現有匹配模式,也就是對應的Pattern 對象。
          String replaceAll(String replacement)
          將目標字符串里與既有模式相匹配的子串全部替換為指定的字符串。
          String replaceFirst(String replacement)
          將目標字符串里第一個與既有模式相匹配的子串替換為指定的字符串。
          Matcher reset()
          重設該Matcher對象。
          Matcher reset(CharSequence input)
          重設該Matcher對象并且指定一個新的目標字符串。
          int start()
          返回當前查找所獲子串的開始字符在原目標字符串中的位置。
          int start(int group)
          返回當前查找所獲得的和指定組匹配的子串的第一個字符在原目標字符串中的位置。


          (光看方法的解釋是不是很不好理解?不要急,待會結合例子就比較容易明白了)

          一個Matcher實例是被用來對目標字符串進行基于既有模式(也就是一個給定的Pattern所編譯的正則表達式)進行匹配查找的,所有往 Matcher的輸入都是通過CharSequence接口提供的,這樣做的目的在于可以支持對從多元化的數據源所提供的數據進行匹配工作。

          我們分別來看看各方法的使用:

          ★matches()/lookingAt ()/find():
          一個Matcher對象是由一個Pattern對象調用其matcher()方法而生成的,一旦該Matcher對象生成,它就可以進行三種不同的匹配查找操作:

          matches()方法嘗試對整個目標字符展開匹配檢測,也就是只有整個目標字符串完全匹配時才返回真值。
          lookingAt ()方法將檢測目標字符串是否以匹配的子串起始。
          find()方法嘗試在目標字符串里查找下一個匹配子串。

          以上三個方法都將返回一個布爾值來表明成功與否。

          ★replaceAll ()/appendReplacement()/appendTail():
          Matcher類同時提供了四個將匹配子串替換成指定字符串的方法:

          replaceAll()
          replaceFirst()
          appendReplacement()
          appendTail()

          replaceAll()與replaceFirst()的用法都比較簡單,請看上面方法的解釋。我們主要重點了解一下appendReplacement()和appendTail()方法。

          appendReplacement(StringBuffer sb, String replacement) 將當前匹配子串替換為指定字符串,并且將替換后的子串以及其之前到上次匹配子串之后的字符串段添加到一個StringBuffer對象里,而 appendTail(StringBuffer sb) 方法則將最后一次匹配工作后剩余的字符串添加到一個StringBuffer對象里。

          例如,有字符串fatcatfatcatfat,假設既有正則表達式模式為"cat",第一次匹配后調用appendReplacement(sb, "dog"),那么這時StringBuffer sb的內容為fatdog,也就是fatcat中的cat被替換為dog并且與匹配子串前的內容加到sb里,而第二次匹配后調用 appendReplacement(sb,"dog"),那么sb的內容就變為fatdogfatdog,如果最后再調用一次appendTail (sb),那么sb最終的內容將是fatdogfatdogfat。

          還是有點模糊?那么我們來看個簡單的程序:
          //該例將把句子里的"Kelvin"改為"Kevin"
          import java.util.regex.*;
          public class MatcherTest{
          public static void main(String[] args)
          throws Exception {
          //生成Pattern對象并且編譯一個簡單的正則表達式"Kelvin"
          Pattern p = Pattern.compile("Kevin");
          //用Pattern類的matcher()方法生成一個Matcher對象
          Matcher m = p.matcher("Kelvin Li and Kelvin Chan are both working in Kelvin Chens KelvinSoftShop company");
          StringBuffer sb = new StringBuffer();
          int i=0;
          //使用find()方法查找第一個匹配的對象
          boolean result = m.find();
          //使用循環將句子里所有的kelvin找出并替換再將內容加到sb里
          while(result) {
          i++;
          m.appendReplacement(sb, "Kevin");
          System.out.println("第"+i+"次匹配后sb的內容是:"+sb);
          //繼續查找下一個匹配對象
          result = m.find();
          }
          //最后調用appendTail()方法將最后一次匹配后的剩余字符串加到sb里;
          m.appendTail(sb);
          System.out.println("調用m.appendTail(sb)后sb的最終內容是:"+ sb.toString());
          }
          }


          最終輸出結果為:
          第1次匹配后sb的內容是:Kevin
          第2次匹配后sb的內容是:Kevin Li and Kevin
          第3次匹配后sb的內容是:Kevin Li and Kevin Chan are both working in Kevin
          第4次匹配后sb的內容是:Kevin Li and Kevin Chan are both working in Kevin Chens Kevin
          調用m.appendTail(sb)后sb的最終內容是:Kevin Li and Kevin Chan are both working in Kevin Chens KevinSoftShop company.

          看了上面這個例程是否對appendReplacement(),appendTail()兩個方法的使用更清楚呢,如果還是不太肯定最好自己動手寫幾行代碼測試一下。

          ★group()/group(int group)/groupCount():
          該系列方法與我們在上篇介紹的Jakarta-ORO中的MatchResult .group()方法類似(有關Jakarta-ORO請參考上篇的內容),都是要返回與組匹配的子串內容,下面代碼將很好解釋其用法:
          import java.util.regex.*;

          public class GroupTest{
          public static void main(String[] args)
          throws Exception {
          Pattern p = Pattern.compile("(ca)(t)");
          Matcher m = p.matcher("one cat,two cats in the yard");
          StringBuffer sb = new StringBuffer();
          boolean result = m.find();
          System.out.println("該次查找獲得匹配組的數量為:"+m.groupCount());
          for(int i=1;i<=m
          }
          }


          輸出為:
          該次查找獲得匹配組的數量為:2
          第1組的子串內容為:ca
          第2組的子串內容為:t

          Matcher對象的其他方法因比較好理解且由于篇幅有限,請讀者自己編程驗證。

          4.一個檢驗Email地址的小程序:
          最后我們來看一個檢驗Email地址的例程,該程序是用來檢驗一個輸入的EMAIL地址里所包含的字符是否合法,雖然這不是一個完整的EMAIL地址檢驗程序,它不能檢驗所有可能出現的情況,但在必要時您可以在其基礎上增加所需功能。
          import java.util.regex.*;
          public class Email {
          public static void main(String[] args) throws Exception {
          String input = args[0];
          //檢測輸入的EMAIL地址是否以 非法符號"."或"@"作為起始字符
          Pattern p = Pattern.compile("^.|^@");
          Matcher m = p.matcher(input);
          if (m
          //檢測是否以"www."為起始
          p = Pattern.compile("^www.");
          m = p.matcher(input);
          if (m
          //檢測是否包含非法字符
          p = Pattern.compile("[^A-Za-z0-9.@_-~#]+");
          m = p.matcher(input);
          StringBuffer sb = new StringBuffer();
          boolean result = m.find();
          boolean deletedIllegalChars = false;
          while(result) {
          //如果找到了非法字符那么就設下標記
          deletedIllegalChars = true;
          //如果里面包含非法字符如冒號雙引號等,那么就把他們消去,加到SB里面
          m.appendReplacement(sb, "");
          result = m.find();
          }
          m.appendTail(sb);
          input = sb.toString();
          if (deletedIllegalChars) {
          System.out.println("輸入的EMAIL地址里包含有冒號、逗號等非法字符,請修改");
          System.out.println("您現在的輸入為: "+args[0]);
          System.out.println("修改后合法的地址應類似: "+input);
          }
          }
          }


          例如,我們在命令行輸入:java Email www.kevin@163.net

          那么輸出結果將會是:EMAIL地址不能以www.起始

          如果輸入的EMAIL為@kevin@163.net

          則輸出為:EMAIL地址不能以.或@作為起始字符

          當輸入為:cgjmail#$%@163.net

          那么輸出就是:

          輸入的EMAIL地址里包含有冒號、逗號等非法字符,請修改
          您現在的輸入為: cgjmail#$%@163.net
          修改后合法的地址應類似: cgjmail@163.net

          5.總結:
          本文介紹了jdk1.4.0-beta3里正則表達式庫--java.util.regex中的類以及其方法,如果結合與上一篇中所介紹的Jakarta -ORO API作比較,讀者會更容易掌握該API的使用,當然該庫的性能將在未來的日子里不斷擴展,希望獲得最新信息的讀者最好到及時到SUN的網站去了解。

          6.結束語:
          本來計劃再多寫一篇介紹一下需付費的正則表達式庫中較具代表性的作品,但覺得既然有了免費且優秀的正則表達式庫可以使用,何必還要去找需付費的呢,相信很 多讀者也是這么想的:,所以有興趣了解更多其他的第三方正則表達式庫的朋友可以自己到網上查找或者到我在參考資料里提供的網址去看看。
          posted @ 2007-08-09 12:43 Sun River| 編輯 收藏
          POI
          Example One:創建XLS

          群眾:笑死人了,這還要你教么,別丟人現眼了,用FileOutputStream就可以了,寫個文件,擴展名為xls就可以了,哈哈,都懶得看你的,估計又是個水貨上來瞎喊,下去,喲貨~~

          小筆:無聊的人一邊去,懶得教你,都沒試過,還雞叫雞叫,&^%&**(()&%$#$#@#@


              HSSFWorkbook wb = new HSSFWorkbook();//構建新的XLS文檔對象
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);//注意,參數是文件輸出流對象
              fileOut.close();



          Example Two:創建Sheet

          群眾:有點責任心好吧,什么是Sheet?欺負我們啊?

          小筆:花300塊去參加Office 培訓班去,我不負責教預科


             HSSFWorkbook wb = new HSSFWorkbook();//創建文檔對象
              HSSFSheet sheet1 = wb.createSheet("new sheet");//創建Sheet對象,參數為Sheet的標題
              HSSFSheet sheet2 = wb.createSheet("second sheet");//同上,注意,同是wb對象,是一個XLS的兩個Sheet
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();


          Example Three:創建小表格,并為之填上數據

          群眾:什么是小表格啊?

          小筆:你用過Excel嗎?人家E哥天天都穿的是網格襯衫~~~~


                            HSSFWorkbook document = new HSSFWorkbook();//創建XLS文檔

          HSSFSheet salary = document.createSheet("薪水");//創建Sheet

          HSSFRow titleRow = salary.createRow(0);//創建本Sheet的第一行



          titleRow.createCell((short) 0).setCellValue("工號");//設置第一行第一列的值
          titleRow.createCell((short) 1).setCellValue("薪水");//......
          titleRow.createCell((short) 2).setCellValue("金額");//設置第一行第二列的值


          File filePath = new File(baseDir+"excel/example/");

          if(!filePath.exists())
          filePath.mkdirs();

          FileOutputStream fileSystem = new FileOutputStream(filePath.getAbsolutePath()+"/Three.xls");

          document.write(fileSystem);

          fileSystem.close();

           

          Example Four :帶自定義樣式的數據(eg:Date)

          群眾:Date!么搞錯,我昨天已經插入成功了~

          小筆:是么?那我如果要你5/7/06 4:23這樣輸出你咋搞?

          群眾:無聊么?能寫進去就行了!

          小筆:一邊涼快去~


                            HSSFWorkbook document = new HSSFWorkbook();

          HSSFSheet sheet = document.createSheet("日期格式");

          HSSFRow row = sheet.createRow(0);


          HSSFCell secondCell = row.createCell((short) 0);

          /**
           * 創建表格樣式對象
           */
          HSSFCellStyle style = document.createCellStyle();

          /**
           * 定義數據顯示格式
           */
          style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

          /**
           * setter
           */
          secondCell.setCellValue(new Date());

          /**
           * 設置樣式
           */
          secondCell.setCellStyle(style);



          File filePath = new File(baseDir+"excel/example/");

          if(!filePath.exists())
          filePath.mkdirs();

          FileOutputStream fileSystem = new FileOutputStream(filePath.getAbsolutePath()+"/Four.xls");

          document.write(fileSystem);

          fileSystem.close();

          Example Five:讀取XLS文檔


          File filePath = new File(baseDir+"excel/example/");

          if(!filePath.exists())
          throw new Exception("沒有該文件");
          /**
           * 創建對XLS進行讀取的流對象
           */
          POIFSFileSystem reader = new POIFSFileSystem(new FileInputStream(filePath.getAbsolutePath()+"/Three.xls"));
          /**
           * 從流對象中分離出文檔對象
           */
          HSSFWorkbook document = new HSSFWorkbook(reader);
          /**
           * 通過文檔對象獲取Sheet
           */
          HSSFSheet sheet = document.getSheetAt(0);
          /**
           * 通過Sheet獲取指定行對象
           */
          HSSFRow row = sheet.getRow(0);
          /**
           * 通過行、列定位Cell
           */
          HSSFCell cell = row.getCell((short) 0);

          /**
           * 輸出表格數據
           */
          log.info(cell.getStringCellValue());


          至此,使用POI操作Excel的介紹告一段落,POI是一個仍然在不斷改善的項目,有很多問題,比如說中文問題,大數據量內存溢出問題等等,但這個Pure Java的庫的性能仍然是不容質疑的,是居家旅行必備良品。

          而且開源軟件有那么一大點好處是,可以根據自己的需要自己去定制。如果大家有中文、性能等問題沒解決的,可以跟我索要我已經改好的庫。當然,你要自己看原代碼,我也不攔你。


          posted @ 2007-08-09 12:37 Sun River| 編輯 收藏
               摘要:   如何將JSP中將查詢結果導出為Excel,其實可以利用jakarta提供的POI接口將查詢結果導出到excel。POI接口是jakarta組織的一個子項目,它包括POIFS,HSSF,HWSF,HPSF,HSLF,目前比較成熟的是HSSF,它是一組操作微軟的excel文檔的API,現在到達3.0版本,已經能夠支持將圖片插入到excel里面。java 代碼 import ...  閱讀全文
          posted @ 2007-08-09 12:26 Sun River| 編輯 收藏
          主站蜘蛛池模板: 扶沟县| 唐河县| 武清区| 郸城县| 庐江县| 乐山市| 上林县| 类乌齐县| 呼玛县| 临泉县| 黑河市| 蒙城县| 乌兰浩特市| 东平县| 正镶白旗| 宽甸| 新建县| 江源县| 八宿县| 阳城县| 长沙县| 抚宁县| 定南县| 奉节县| 贵定县| 西乌| 克什克腾旗| 卢氏县| 雷州市| 治多县| 共和县| 陕西省| 萨迦县| 平南县| 雅安市| 东安县| 马山县| 满洲里市| 和平区| 新兴县| 盖州市|