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| 编辑 收藏

Populating Value Objects from ActionForms

Problem

You don't want to have to write numerous getters and setters to pass data from your action forms to your business objects.

Solution

Use the introspection utilities provided by the Jakarta Commons BeanUtils package in your Action.execute( ) method:

import org.apache.commons.beanutils.*;
// other imports omitted
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
BusinessBean businessBean = new BusinessBean( );
BeanUtils.copyProperties(businessBean, form);
// ... rest of the Action

Discussion

A significant portion of the development effort for a web application is spent moving data to and from the different system tiers. Along the way, the data may be transformed in one way or another, yet many of these transformations are required because the tier to which the data is moving requires the information to be represented in a different way.

Data sent in the HTTP request is represented as simple text. For some data types, the value can be represented as a String object throughout the application. However, many data types should be represented in a different format in the business layer than on the view. Date fields provide the classic example. A date field is retrieved from a form's input field as a String. Then it must be converted to a java.util.Date in the model. Furthermore, when the value is persisted, it's usually transformed again, this time to a java.sql.Timestamp. Numeric fields require similar transformations.

The Jakarta Commons BeanUtils package supplied with the Struts distribution provides some great utilities automating the movement and conversion of data between objects. These utilities use JavaBean property names to match the source property to the destination property for data transfer. To leverage these utilities, ensure you give your properties consistent, meaningful names. For example, to represent an employee ID number, you may decide to use the property name employeeId. In all classes that contain an employee ID, you should use that name. Using empId in one class and employeeIdentifier in another will only lead to confusion among your developers and will render the BeanUtils facilities useless.

The entire conversion and copying of properties from ActionForm to business object can be performed with one static method call:

BeanUtils.copyProperties(
businessBean
, 
form
);

This copyProperties( ) method attempts to copy each JavaBean property in form to the property with the same name in businessBean. If a property in form doesn't have a matching property in businessBean, that property is silently ignored. If the data types of the matched properties are different, BeanUtils will attempt to convert the value to the type expected. BeanUtils provides converters from Strings to the following types:

  • java.lang.BigDecimal

  • java.lang.BigInteger

  • boolean and java.lang.Boolean

  • byte and java.lang.Byte

  • char and java.lang.Character

  • java.lang.Class

  • double and java.lang.Double

  • float and java.lang.Float

  • int and java.lang.Integer

  • long and java.lang.Long

  • short and java.lang.Short

  • java.lang.String

  • java.sql.Date

  • java.sql.Time

  • java.sql.Timestamp

While the conversions to character-based and numeric types should cover most of your needs, date type fields (as shown in Recipe 3-13) can be problematic. A good solution suggested by Ted Husted is to implement transformation getter and setter methods in the business object that convert from the native type (e.g. java.util.Date) to a String and back again.

Because BeanUtils knows how to handle DynaBeans and the DynaActionForm implements DynaBean, the Solution will work unchanged for DynaActionForms and normal ActionForms.


As an example, suppose you want to collect information about an employee for a human resources application. Data to be gathered includes the employee ID, name, salary, marital status, and hire date. Example 5-9 shows the Employee business object. Most of the methods of this class are getters and setters; for the hireDate property, however, helper methods are provided that get and set the value from a String.

Example 5-9. Employee business object
package com.oreilly.strutsckbk.ch05;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Employee {
private String employeeId;
private String firstName;
private String lastName;
private Date hireDate;
private boolean married;
private BigDecimal salary;
public BigDecimal getSalary( ) {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getEmployeeId( ) {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getFirstName( ) {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName( ) {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isMarried( ) {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
public Date getHireDate( ) {
return hireDate;
}
public void setHireDate(Date HireDate) {
this.hireDate = HireDate;
}
public String getHireDateDisplay( ) {
if (hireDate == null)
return "";
else
return dateFormatter.format(hireDate);
}
public void setHireDateDisplay(String hireDateDisplay) {
if (hireDateDisplay == null)
hireDate = null;
else {
try {
hireDate = dateFormatter.parse(hireDateDisplay);
} catch (ParseException e) {
e.printStackTrace( );
}
}
}
private DateFormat dateFormatter = new SimpleDateFormat("mm/DD/yy");
}

Example 5-10 shows the corresponding ActionForm that will retrieve the data from the HTML form. The hire date is represented in the ActionForm as a String property, hireDateDisplay. The salary property is a java.lang.String, not a java.math.BigDecimal, as in the Employee object of Example 5-9.

Example 5-10. Employee ActionForm
package com.oreilly.strutsckbk.ch05;
import java.math.BigDecimal;
import org.apache.struts.action.ActionForm;
public class EmployeeForm extends ActionForm {
private String firstName;
private String lastName;
private String hireDateDisplay;
private String salary;
private boolean married;
public String getEmployeeId( ) {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getFirstName( ) {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName( ) {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isMarried( ) {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
public String getHireDateDisplay( ) {
return hireDateDisplay;
}
public void setHireDateDisplay(String hireDate) {
this.hireDateDisplay = hireDate;
}
public String getSalary( ) {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
}

If you wanted to use a DynaActionForm, you would configure it identically as the EmployeeForm class. The form-bean declarations from the struts-config.xml file show the declarations for the EmployeeForm and a functionally identical DynaActionForm:

<form-bean name="EmployeeForm"
type="com.oreilly.strutsckbk.ch05.EmployeeForm"/>
<form-bean name="EmployeeDynaForm"
type="org.apache.struts.action.DynaActionForm">
<form-property name="employeeId" type="java.lang.String"/>
<form-property name="firstName" type="java.lang.String"/>
<form-property name="lastName" type="java.lang.String"/>
<form-property name="salary" type="java.lang.String"/>
<form-property name="married" type="java.lang.Boolean"/>
<form-property name="hireDateDisplay" type="java.lang.String"/>
</form-bean>

The following is the action mapping that processes the form. In this case, the name attribute refers to the handcoded EmployeeForm. You could, however, change this to use the EmployeeDynaForm without requiring any modifications to the SaveEmployeeAction or the view_emp.jsp JSP page:

<action    path="/SaveEmployee"
name="EmployeeForm"
scope="request"
type="com.oreilly.strutsckbk.ch05.SaveEmployeeAction">
<forward name="success" path="/view_emp.jsp"/>
</action>

The data is converted and copied from the form to the business object in the SaveEmployeeAction shown in Example 5-11.

Example 5-11. Action to save employee data
package com.oreilly.strutsckbk.ch05;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class SaveEmployeeAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
Employee emp = new Employee( );
// Copy to business object from ActionForm
BeanUtils.copyProperties( emp, form );
request.setAttribute("employee", emp);
return mapping.findForward("success");
}
}

Finally, two JSP pages complete the example. The JSP of Example 5-12 (edit_emp.jsp) renders the HTML form to retrieve the data.

Example 5-12. Form for editing employee data
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix=
"bean" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix=
"html" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<title>Struts Cookbook - Chapter 5 : Add Employee</title>
</head>
<body>
<h2>Edit Employee</h2>
<html:form action="/SaveEmployee">
Employee ID: <html:text property="employeeId"/><br />
First Name: <html:text property="firstName"/><br />
Last Name: <html:text property="lastName"/><br />
Married? <html:checkbox property="married"/><br />
Hired on Date: <html:text property="hireDateDisplay"/><br />
Salary: <html:text property="salary"/><br />
<html:submit/>
</html:form>
</body>
</html>

The JSP in Example 5-13 (view_emp.jsp) displays the results. This page is rendering data from the business object, and not an ActionForm. This is acceptable since the data on this page is for display purposes only. This approach allows for the formatting of data, (salary and hireDate) to be different than the format in which the values were entered.

Example 5-13. View of submitted employee data
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix=
"bean" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<title>Struts Cookbook - Chapter 5 : View Employee</title>
</head>
<body>
<h2>View Employee</h2>
Employee ID: <bean:write name="employee" property="employeeId"/><br />
First Name: <bean:write name="employee" property="firstName"/><br />
Last Name: <bean:write name="employee" property="lastName"/><br />
Married? <bean:write name="employee" property="married"/><br />
Hired on Date: <bean:write name="employee" property="hireDate"
format="MMMMM dd, yyyy"/><br />
Salary: <bean:write name="employee" property="salary" format="$##0.00"/
><br />
</body>
</html>

When you work with this example, swap out the handcoded form for the DyanActionForm to see how cleanly BeanUtils works. When you consider how many files need to be changed for one additional form input, the use of BeanUtils in conjunction with DynaActionForms becomes obvious.

posted @ 2007-08-07 18:28 Sun River| 编辑 收藏
 

2NF and 3NF

The 2NF and 3NF are very similar--the 2NF deals with composite primary keys and the 3NF deals with single primary keys. In general, if you do an ER diagram, convert many-to-many relationships to entities, and then convert all entities to tables, then your tables will already be in 3NF form.

Second normal form is violated when a non-key field is a fact about a subset of a key. It is only relevant when the key is composite, i.e., consists of several fields. Consider the following inventory record:

---------------------------------------------------
| PART | WAREHOUSE | QUANTITY | WAREHOUSE-ADDRESS |
====================-------------------------------

The key here consists of the PART and WAREHOUSE fields together, but WAREHOUSE-ADDRESS is a fact about the WAREHOUSE alone. The basic problems with this design are:

  • The warehouse address is repeated in every record that refers to a part stored in that warehouse.
  • If the address of the warehouse changes, every record referring to a part stored in that warehouse must be updated. Because of the redundancy, the data might become inconsistent, with different records showing different addresses for the same warehouse.
  • If at some point in time there are no parts stored in the warehouse, there may be no record in which to keep the warehouse's address.

To satisfy second normal form, the record shown above should be decomposed into (replaced by) the two records:

------------------------------- --------------------------------- 
| PART | WAREHOUSE | QUANTITY | | WAREHOUSE | WAREHOUSE-ADDRESS |
====================----------- =============--------------------
 

The 3NF differs from the 2NF in that all non-key attributes in 3NF are required to be directly dependent on the primary key of the relation. The 3NF therefore insists that all facts in the relation are about the key (or the thing that the key identifies), the whole key and nothing but the key.

Third normal form is violated when a non-key field is a fact about another non-key field, as in

------------------------------------
| EMPLOYEE | DEPARTMENT | LOCATION |
============------------------------

The EMPLOYEE field is the key. If each department is located in one place, then the LOCATION field is a fact about the DEPARTMENT -- in addition to being a fact about the EMPLOYEE. The problems with this design are the same as those caused by violations of second normal form:

  • The department's location is repeated in the record of every employee assigned to that department.
  • If the location of the department changes, every such record must be updated.
  • Because of the redundancy, the data might become inconsistent, with different records showing different locations for the same department.
  • If a department has no employees, there may be no record in which to keep the department's location.

To satisfy third normal form, the record shown above should be decomposed into the two records:

------------------------- -------------------------
| EMPLOYEE | DEPARTMENT | | DEPARTMENT | LOCATION |
============-------------  ==============-----------
 
To summarize, a record is in second and third normal forms if every field is either part of the key or provides a (single-valued) fact about exactly the whole key and nothing else.

 

posted @ 2007-07-20 00:51 Sun River| 编辑 收藏
---How do you submit a form using Javascript?
Use document.forms[0].submit();
(0 refers to the index of the form – if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on).
--

How do we get JavaScript onto a web page?
You can use several different methods of placing javascript in you pages.
You can directly add a script element inside the body of page.
1. For example, to add the "last updated line" to your pages, In your page text, add the following:
<p>blah, blah, blah, blah, blah.</p>
<script type="text/javascript" >
<!-- Hiding from old browsers
document.write("Last Updated:" +
document.lastModified);
document.close();
// -->
</script>
<p>yada, yada, yada.</p>

Security Tip

Use Firefox instead of Internet Explorer and PREVENT Spyware !

Firefox is free and is considered the best free, safe web browser available today
 
Get Firefox with Google Toolbar for better browsing

(Note: the first comment, "<--" hides the content of the script from browsers that don't understand javascript. The "// -->" finishes the comment. The "//" tells javascript that this is a comment so javascript doesn't try to interpret the "-->". If your audience has much older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
2. Javascript can be placed inside the <head> element
Functions and global variables typically reside inside the <head> element.
<head>
<title>Default Test Page</title>
<script language="JavaScript" type="text/javascript">
var myVar = "";
function timer(){setTimeout('restart()',10);}
document.onload=timer();
</script>
</head>

Javascript can be referenced from a separate file
Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don't use the shorthand ending "<script ... />). These are typically placed in the <head> element.
<script type="text/javascript" SRC="myStuff.js"></script>

How to read and write a file using javascript?
I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script.

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

---

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);

How to create arrays in JavaScript?
We can declare an array like this
var scripts = new Array();
We can add elements to this array like this

scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

Now our array scrips has 4 elements inside it and we can print or access them by using their index number. Note that index number starts from 0. To get the third element of the array we have to use the index number 2 . Here is the way to get the third element of an array.
document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);

How do you target a specific frame from a hyperlink?
Include the name of the frame in the target attribute of the hyperlink. <a href=”mypage.htm” target=”myframe”>>My Page</a>

What is a fixed-width table and its advantages?

Security Issue

Get Norton Security Scan and Spyware Doctor free for your Computer from Google.

The Pack contains nearly 14 plus software . Pick the one which is suited for you Make your PC more useful. Get the free Google Pack.

Fixed width tables are rendered by the browser based on the widths of the columns in the first row, resulting in a faster display in case of large tables. Use the CSS style table-layout:fixed to specify a fixed width table.
If the table is not specified to be of fixed width, the browser has to wait till all data is downloaded and then infer the best width for each of the columns. This process can be very slow for large tables.

Example of using Regular Expressions for syntax checking in JavaScript


...
var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");
var text = myWidget.value;
var OK = re.test(text);
if( ! OK ) {
alert("The extra parameters need some work.\r\n Should be something like: \"&a=1&c=4\"");
}


---

How to add Buttons in JavaScript?
The most basic and ancient use of buttons are the "submit" and "clear", which appear slightly before the Pleistocene period. Notice when the "GO!" button is pressed it submits itself to itself and appends the name in the URL.
<form action="" name="buttonsGalore" method="get">
Your Name: <input type="text" name="mytext" />
<br />
<input type="submit" value="GO!" />
<input type="reset" value="Clear All" />
</form>

Another useful approach is to set the "type" to "button" and use the "onclick" event.
<script type="text/javascript">
function displayHero(button) {
alert("Your hero is \""+button.value+"\".");
}
</script>

<form action="" name="buttonsGalore" method="get">
<fieldset style="margin: 1em; text-align: center;">
<legend>Select a Hero</legend>
<input type="button" value="Agamemnon" onclick="displayHero(this)" />
<input type="button" value="Achilles" onclick="displayHero(this)" />
<input type="button" value="Hector" onclick="displayHero(this)" />
<div style="height: 1em;" />
</fieldset>
</form>

What can javascript programs do?
Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling

How to set a HTML document's background color?
document.bgcolor property can be set to any appropriate color.
---

How to get the contents of an input box using Javascript?
Use the "value" property.
var myValue = window.document.getElementById("MyTextBox").value;

How to determine the state of a checkbox using Javascript?
var checkedP = window.document.getElementById("myCheckBox").checked;

How to set the focus in an element using Javascript?
<script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>

How to access an external javascript file that is stored externally and not embedded?
This can be achieved by using the following tag between head tags or between body tags.
<script src="abc.js"></script>How to access an external javascript file that is stored externally and not embedded? where abc.js is the external javscript file to be accessed.

What is the difference between an alert box and a confirmation box?
An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.

What is a prompt box?
A prompt box allows the user to enter input by providing a text box.

Can javascript code be broken in different lines?
Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.
that is ,
document.write("Hello \ world");
is possible but not document.write \
("hello world");

Taking a developer’s perspective, do you think that that JavaScript is easy to learn and use?
One of the reasons JavaScript has the word "script" in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn't care if it's holding a string, a number, or a reference to an object; the same variable can even change what type of data it holds while a script runs.
The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the objects you script are pre-defined for the author, and they largely represent physical things you can see on a page: a text box, an image, and so on. It's easier to say, "OK, these are the things I'm working with and I'll use scripting to make them do such and such," instead of having to dream up the user interface, conceive of and code objects, and handle the interaction between objects and users. With scripting, you tend to write a _lot_ less code.

What Web sites do you feel use JavaScript most effectively (i.e., best-in-class examples)? The worst?
The best sites are the ones that use JavaScript so transparently, that I'm not aware that there is any scripting on the page. The worst sites are those that try to impress me with how much scripting is on the page.

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.

What is the difference between SessionState and ViewState?
ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.

What does the EnableViewStateMac setting in an aspx page do?
Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP.NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error - Validation of viewstate MAC failed.
Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.


---
posted @ 2007-07-13 05:52 Sun River| 编辑 收藏
--What is the difference between Session bean and Entity bean ?
The Session bean and Entity bean are two main parts of EJB container.
Session Bean
--represents a workflow on behalf of a client
--one-to-one logical mapping to a client.
--created and destroyed by a client
--not permanent objects
--lives its EJB container(generally) does not survive system shut down
--two types: stateless and stateful beans
Entity Bean
--represents persistent data and behavior of this data
--can be shared among multiple clients
--persists across multiple invocations
--findable permanent objects
--outlives its EJB container, survives system shutdown
--two types: container managed persistence(CMP) and bean managed persistence(BMP)

--What is reentrant entity bean ?
An entity bean that can handle multiple simultaneous, interleaved, or nested invocations that will not interfere with each other.
--What is JMS session ?
A single-threaded context for sending and receiving JMS messages. A JMS session can be nontransacted, locally transacted, or participating in a distributed transaction.
---Can you make use of a ServletOutputStream object from within a JSP page?
No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients.
A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not.

---What are the core JMS-related objects required for each JMS-enabled application?
Each JMS-enabled client must establish the following:
* A connection object provided by the JMS server (the message broker)
* Within a connection, one or more sessions, which provide a context for message sending and receiving
* Within a session, either a queue or topic object representing the destination (the message staging area) within the message broker
* Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively). Within a session, a message object (to send or to receive)

How does the Application server handle the JMS Connection?
1. App server creates the server session and stores them in a pool.
2. Connection consumer uses the server session to put messages in the session of the JMS.
3. Server session is the one that spawns the JMS session.
4. Applications written by Application programmers creates the message listener.

What is Stream Message ?
Stream messages are a group of java primitives. It contains some convenient methods for reading the data. However Stream Message prevents reading a long value as short. This is so because the Stream Message also writes the type information along with the value of the primitive type and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another.
--

Why do the JMS dbms_aqadm.add_subscriber and dbms_aqadm.remove_subscriber calls sometimes hang when there are concurrent enqueues or dequeues happening on the same queue to which these calls are issued?
Add_subscriber and remove_subscriber are administrative operations on a queue. Though AQ does not prevent applications from issuing administrative and operational calls concurrently, they are executed serially. Both add_subscriber and remove_subscriber will block until pending transactions that have enqueued or dequeued messages commit and release the resources they hold. It is expected that adding and removing subscribers will not be a frequent event. It will mostly be part of the setup for the application. The behavior you observe will be acceptable in most cases. The solution is to try to isolate the calls to add_subscriber and remove_subscriber at the setup or cleanup phase when there are no other operations happening on the queue. That will make sure that they will not stay blocked waiting for operational calls to release resources.

Why do the TopicSession.createDurableSubscriber and TopicSession.unubscribe calls raise JMSException with the message "ORA - 4020 - deadlock detected while trying to lock object"?
CreateDurableSubscriber and unsubscribe calls require exclusive access to the Topics. If there are pending JMS operations (send/publish/receive) on the same Topic before these calls are issued, the ORA - 4020 exception is raised.
There are two solutions to the problem:
1. Try to isolate the calls to createDurableSubscriber and unsubscribe at the setup or cleanup phase when there are no other JMS operations happening on the Topic. That will make sure that the required resources are not held by other JMS operational calls. Hence the error ORA - 4020 will not be raised.
2. Issue a TopicSession.commit call before calling createDurableSubscriber and unsubscribe call.

Why doesn't AQ_ADMINISTRATOR_ROLE or AQ_USER_ROLE always work for AQ applications using Java/JMS API?
In addition to granting the roles, you would also need to grant execute to the user on the following packages:
* grant execute on sys.dbms_aqin to <userid>
* grant execute on sys.dbms_aqjms to <userid>

Why do I get java.security.AccessControlException when using JMS MessageListeners from Java stored procedures inside Oracle8i JServer?
To use MessageListeners inside Oracle8i JServer, you can do one for the following
1. GRANT JAVASYSPRIV to <userid>

Call dbms_java.grant_permission ('JAVASYSPRIV', 'SYS:java.net.SocketPermission', '*', 'accept,connect,listen,resolve');

What is the use of ObjectMessage?
ObjectMessage contains a Serializable java object as it's payload. Thus it allows exchange of Java objects between applications. This in itself mandates that both the applications be Java applications. The consumer of the message must typecast the object received to it's appropriate type. Thus the consumer should before hand know the actual type of the object sent by the sender. Wrong type casting would result in ClassCastException. Moreover the class definition of the object set in the payload should be available on both the machine, the sender as well as the consumer. If the class definition is not available in the consumer machine, an attempt to type cast would result in ClassNotFoundException. Some of the MOMs might support dynamic loading of the desired class over the network, but the JMS specification does not mandate this behavior and would be a value added service if provided by your vendor. And relying on any such vendor specific functionality would hamper the portability of your application. Most of the time the class need to be put in the classpath of both, the sender and the consumer, manually by the developer.

What is the use of MapMessage?
A MapMessage carries name-value pair as it's payload. Thus it's payload is similar to the java.util.Properties object of Java. The values can be Java primitives or their wrappers.

What is the difference between BytesMessage and StreamMessage?
BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.

What is object message ?
Object message contains a group of serializeable java object. So it allows exchange of Java objects between applications. sot both the applications must be Java applications.

What is text message?
Text messages contains String messages (since being widely used, a separate messaging Type has been supported) . It is useful for exchanging textual data and complex character data like XML.

What is Map message?
map message contains name value Pairs. The values can be of type primitives and its wrappers. The name is a string.


---Does JMS specification define transactions? Queue
JMS specification defines a transaction mechanisms allowing clients to send and receive groups of logically bounded messages as a single unit of information. A Session may be marked as transacted. It means that all messages sent in a session are considered as parts of a transaction. A set of messages can be committed (commit() method) or rolled back (rollback() method). If a provider supports distributed transactions, it's recommended to use XAResource API.
---

Does JMS specification define transactions? Queue
JMS specification defines a transaction mechanisms allowing clients to send and receive groups of logically bounded messages as a single unit of information. A Session may be marked as transacted. It means that all messages sent in a session are considered as parts of a transaction. A set of messages can be committed (commit() method) or rolled back (rollback() method). If a provider supports distributed transactions, it's recommended to use XAResource API.

posted @ 2007-07-13 04:48 Sun River| 编辑 收藏
--How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
--Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
--How can we make a class Singleton ?
A) If the class is Serializable
class Singleton implements Serializable
{
private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}

/**
If the singleton implements Serializable, then this method must be supplied.
*/
protected Object readResolve() {
return instance;
}

/**
This method avoids the object fro being cloned
*/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}
}

B) If the class is NOT Serializable

class Singleton
{
private static Singleton instance;
private Singleton() { }

public static synchronized Singleton getInstance()
{
if (instance == null)
instance = new Singleton();
return instance;
}

/**
This method avoids the object from being cloned**/
public Object clone() {
throws CloneNotSupportedException ;
//return instance;
}
}
 --

What is covariant return type?
A covariant return type lets you override a superclass method with a return type that subtypes the superclass method's return type. So we can use covariant return types to minimize upcasting and downcasting.
class Parent {
Parent foo () {
System.out.println ("Parent foo() called");
return this;
}
}

class Child extends Parent {
Child foo () {
System.out.println ("Child foo() called");
return this;
}
}

class Covariant {
public static void main(String[] args) {
Child c = new Child();
Child c2 = c.foo(); // c2 is Child
Parent c3 = c.foo(); // c3 points to Child
}
}

--What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
--What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
--What is autoboxing ?
Automatic conversion between reference and primitive types.

--How can I investigate the physical structure of a database?
The JDBC view of a database internal structure can be seen in the image below.

* Several database objects (tables, views, procedures etc.) are contained within a Schema.
* Several schema (user namespaces) are contained within a catalog.
* Several catalogs (database partitions; databases) are contained within a DB server (such as Oracle, MS SQL

The DatabaseMetaData interface has methods for discovering all the Catalogs, Schemas, Tables and Stored Procedures in the database server. The methods are pretty intuitive, returning a ResultSet with a single String column; use them as indicated in the code below:

public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");

// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();

// Get all Catalogs
System.out.println("\nCatalogs are called '" + dbmd.getCatalogTerm()
+ "' in this RDBMS.");
processResultSet(dbmd.getCatalogTerm(), dbmd.getCatalogs());

// Get all Schemas
System.out.println("\nSchemas are called '" + dbmd.getSchemaTerm()
+ "' in this RDBMS.");
processResultSet(dbmd.getSchemaTerm(), dbmd.getSchemas());

// Get all Table-like types
System.out.println("\nAll table types supported in this RDBMS:");
processResultSet("Table type", dbmd.getTableTypes());

// Close the Connection
conn.close();
}
public static void processResultSet(String preamble, ResultSet rs)
throws SQLException
{
// Printout table data
while(rs.next())
{
// Printout
System.out.println(preamble + ": " + rs.getString(1));
}

// Close database resources
rs.close();
}
---How do I find all database stored procedures in a database?
Use the getProcedures method of interface java.sql.DatabaseMetaData to probe the database for stored procedures. The exact usage is described in the code below.

public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");

// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();

// Get all procedures.
System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
ResultSet rs = dbmd.getProcedures(null, null, "%");

// Printout table data
while(rs.next())
{
// Get procedure metadata
String dbProcedureCatalog = rs.getString(1);
String dbProcedureSchema = rs.getString(2);
String dbProcedureName = rs.getString(3);
String dbProcedureRemarks = rs.getString(7);
short dbProcedureType = rs.getShort(8);

// Make result readable for humans
String procReturn = (dbProcedureType == DatabaseMetaData.procedureNoResult ? "No Result" : "Result");

// Printout
System.out.println("Procedure: " + dbProcedureName + ", returns: " + procReturn);
System.out.println(" [Catalog | Schema]: [" + dbProcedureCatalog + " | " + dbProcedureSchema + "]");
System.out.println(" Comments: " + dbProcedureRemarks);
}

// Close database resources
rs.close();
conn.close();
}

---

How can I investigate the parameters to send into and receive from a database stored procedure?
Use the method getProcedureColumns in interface DatabaseMetaData to probe a stored procedure for metadata. The exact usage is described in the code below.

NOTE! This method can only discover parameter values. For databases where a returning ResultSet is created simply by executing a SELECT statement within a stored procedure (thus not sending the return ResultSet to the java application via a declared parameter), the real return value of the stored procedure cannot be detected. This is a weakness for the JDBC metadata mining which is especially present when handling Transact-SQL databases such as those produced by SyBase and Microsoft.

public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
;
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");

// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();

// Get all column definitions for procedure "getFoodsEaten" in
// schema "testlogin" and catalog "dbo".
System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
ResultSet rs = dbmd.getProcedureColumns("test", "dbo", "getFoodsEaten", "%");

// Printout table data
while(rs.next())
{
// Get procedure metadata
String dbProcedureCatalog = rs.getString(1);
String dbProcedureSchema = rs.getString(2);
String dbProcedureName = rs.getString(3);
String dbColumnName = rs.getString(4);
short dbColumnReturn = rs.getShort(5);
String dbColumnReturnTypeName = rs.getString(7);
int dbColumnPrecision = rs.getInt(8);
int dbColumnByteLength = rs.getInt(9);
short dbColumnScale = rs.getShort(10);
short dbColumnRadix = rs.getShort(11);
String dbColumnRemarks = rs.getString(13);


// Interpret the return type (readable for humans)
String procReturn = null;

switch(dbColumnReturn)
{
case DatabaseMetaData.procedureColumnIn:
procReturn = "In";
break;
case DatabaseMetaData.procedureColumnOut:
procReturn = "Out";
break;
case DatabaseMetaData.procedureColumnInOut:
procReturn = "In/Out";
break;
case DatabaseMetaData.procedureColumnReturn:
procReturn = "return value";
break;
case DatabaseMetaData.procedureColumnResult:
procReturn = "return ResultSet";
default:
procReturn = "Unknown";
}

// Printout
System.out.println("Procedure: " + dbProcedureCatalog + "." + dbProcedureSchema
+ "." + dbProcedureName);
System.out.println(" ColumnName [ColumnType(ColumnPrecision)]: " + dbColumnName
+ " [" + dbColumnReturnTypeName + "(" + dbColumnPrecision + ")]");
System.out.println(" ColumnReturns: " + procReturn + "(" + dbColumnReturnTypeName + ")");
System.out.println(" Radix: " + dbColumnRadix + ", Scale: " + dbColumnScale);
System.out.println(" Remarks: " + dbColumnRemarks);
}

// Close database resources
rs.close();
conn.close();
}

How do I check what table-like database objects (table, view, temporary table, alias) are present in a particular database?
Use java.sql.DatabaseMetaData to probe the database for metadata. Use the getTables method to retrieve information about all database objects (i.e. tables, views, system tables, temporary global or local tables or aliases). The exact usage is described in the code below.

NOTE! Certain JDBC drivers throw IllegalCursorStateExceptions when you try to access fields in the ResultSet in the wrong order (i.e. not consecutively). Thus, you should not change the order in which you retrieve the metadata from the ResultSet.

public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");

// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();

// Get all dbObjects. Replace the last argument in the getTables
// method with objectCategories below to obtain only database
// tables. (Sending in null retrievs all dbObjects).
String[] objectCategories = {"TABLE"};
ResultSet rs = dbmd.getTables(null, null, "%", null);

// Printout table data
while(rs.next())
{
// Get dbObject metadata
String dbObjectCatalog = rs.getString(1);
String dbObjectSchema = rs.getString(2);
String dbObjectName = rs.getString(3);
String dbObjectType = rs.getString(4);

// Printout
System.out.println("" + dbObjectType + ": " + dbObjectName);
System.out.println(" Catalog: " + dbObjectCatalog);
System.out.println(" Schema: " + dbObjectSchema);
}

// Close database resources
rs.close();
conn.close();
}

--How do I extract SQL table column type information?
Use the getColumns method of the java.sql.DatabaseMetaData interface to investigate the column type information of a particular table. Note that most arguments to the getColumns method (pinpointing the column in question) may be null, to broaden the search criteria. A code sample can be seen below:

public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]",
"[login]", "[passwd]");

// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();

// Get all column types for the table "sysforeignkeys", in schema
// "dbo" and catalog "test".
ResultSet rs = dbmd.getColumns("test", "dbo", "sysforeignkeys", "%");

// Printout table data
while(rs.next())
{
// Get dbObject metadata
String dbObjectCatalog = rs.getString(1);
String dbObjectSchema = rs.getString(2);
String dbObjectName = rs.getString(3);
String dbColumnName = rs.getString(4);
String dbColumnTypeName = rs.getString(6);
int dbColumnSize = rs.getInt(7);
int dbDecimalDigits = rs.getInt(9);
String dbColumnDefault = rs.getString(13);
int dbOrdinalPosition = rs.getInt(17);
String dbColumnIsNullable = rs.getString(18);

// Printout
System.out.println("Col(" + dbOrdinalPosition + "): " + dbColumnName
+ " (" + dbColumnTypeName +")");
System.out.println(" Nullable: " + dbColumnIsNullable +
", Size: " + dbColumnSize);
System.out.println(" Position in table: " + dbOrdinalPosition
+ ", Decimal digits: " + dbDecimalDigits);
}

// Free database resources
rs.close();
conn.close();
}
---How do I insert an image file (or other raw data) into a database?
All raw data types (including binary documents or images) should be read and uploaded to the database as an array of bytes, byte[]. Originating from a binary file,
1. Read all data from the file using a FileInputStream.
2. Create a byte array from the read data.
3. Use method setBytes(int index, byte[] data); of java.sql.PreparedStatement to upload the data.

--How can I connect from an applet to a database on the server?
There are two ways of connecting to a database on the server side.
1. The hard way. Untrusted applets cannot touch the hard disk of a computer. Thus, your applet cannot use native or other local files (such as JDBC database drivers) on your hard drive. The first alternative solution is to create a digitally signed applet which may use locally installed JDBC drivers, able to connect directly to the database on the server side.
2. The easy way. Untrusted applets may only open a network connection to the server from which they were downloaded. Thus, you must place a database listener (either the database itself, or a middleware server) on the server node from which the applet was downloaded. The applet would open a socket connection to the middleware server, located on the same computer node as the webserver from which the applet was downloaded. The middleware server is used as a mediator, connecting to and extract data from the database.
---Many connections from an Oracle8i pooled connection returns statement closed. I am using import oracle.jdbc.pool.* with thin driver. If I test with many simultaneous connections, I get an SQLException that the statement is closed.
ere is an example of concurrent operation of pooled connections from the OracleConnectionPoolDataSource. There is an executable for kicking off threads, a DataSource, and the workerThread.

The Executable Member
package package6;

/**
* package6.executableTester
*/
public class executableTester {
protected static myConnectionPoolDataSource dataSource = null;
static int i = 0;

/**
* Constructor
*/
public executableTester() throws java.sql.SQLException
{
}

/**
* main
* @param args
*/
public static void main(String[] args) {

try{
dataSource = new myConnectionPoolDataSource();
}
catch ( Exception ex ){
ex.printStackTrace();
}

while ( i++ < 10 ) {
try{
workerClass worker = new workerClass();
worker.setThreadNumber( i );
worker.setConnectionPoolDataSource( dataSource.getConnectionPoolDataSource() );
worker.start();
System.out.println( "Started Thread#"+i );
}
catch ( Exception ex ){
ex.printStackTrace();
}
}
}

}

The DataSource Member

package package6;
import oracle.jdbc.pool.*;

/**
* package6.myConnectionPoolDataSource.
*
*/
public class myConnectionPoolDataSource extends Object {
protected OracleConnectionPoolDataSource ocpds = null;

/**
* Constructor
*/
public myConnectionPoolDataSource() throws java.sql.SQLException {
// Create a OracleConnectionPoolDataSource instance
ocpds = new OracleConnectionPoolDataSource();

// Set connection parameters
ocpds.setURL("jdbc:oracle:oci8:@mydb");
ocpds.setUser("scott");
ocpds.setPassword("tiger");

}

public OracleConnectionPoolDataSource getConnectionPoolDataSource() {
return ocpds;
}

}

The Worker Thread Member

package package6;
import oracle.jdbc.pool.*;
import java.sql.*;
import javax.sql.*;

/**
* package6.workerClass .
*
*/
public class workerClass extends Thread {
protected OracleConnectionPoolDataSource ocpds = null;
protected PooledConnection pc = null;

protected Connection conn = null;

protected int threadNumber = 0;
/**
* Constructor
*/

public workerClass() {
}

public void doWork( ) throws SQLException {

// Create a pooled connection
pc = ocpds.getPooledConnection();

// Get a Logical connection
conn = pc.getConnection();

// Create a Statement
Statement stmt = conn.createStatement ();

// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("select ename from emp");

// Iterate through the result and print the employee names
while (rset.next ())
// System.out.println (rset.getString (1));
;

// Close the RseultSet
rset.close();
rset = null;

// Close the Statement
stmt.close();
stmt = null;

// Close the logical connection
conn.close();
conn = null;

// Close the pooled connection
pc.close();
pc = null;

System.out.println( "workerClass.thread#"+threadNumber+" completed..");

}

public void setThreadNumber( int assignment ){
threadNumber = assignment;
}

public void setConnectionPoolDataSource(OracleConnectionPoolDataSource x){
ocpds = x;
}

public void run() {
try{
doWork();
}
catch ( Exception ex ){
ex.printStackTrace();
}
}

}

The OutPut Produced

Started Thread#1
Started Thread#2
Started Thread#3
Started Thread#4
Started Thread#5
Started Thread#6
Started Thread#7
Started Thread#8
Started Thread#9
Started Thread#10
workerClass.thread# 1 completed..
workerClass.thread# 10 completed..
workerClass.thread# 3 completed..
workerClass.thread# 8 completed..
workerClass.thread# 2 completed..
workerClass.thread# 9 completed..
workerClass.thread# 5 completed..
workerClass.thread# 7 completed..
workerClass.thread# 6 completed..
workerClass.thread# 4 completed..

The oracle.jdbc.pool.OracleConnectionCacheImpl class is another subclass of the oracle.jdbc.pool.OracleDataSource which should also be looked over, that is what you really what to use. Here is a similar example that uses the oracle.jdbc.pool.OracleConnectionCacheImpl. The general construct is the same as the first example but note the differences in workerClass1 where some statements have been commented ( basically a clone of workerClass from previous example ).
The Executable Member

package package6;
import java.sql.*;
import javax.sql.*;
import oracle.jdbc.pool.*;

/**
* package6.executableTester2
*
*/
public class executableTester2 {
static int i = 0;
protected static myOracleConnectCache
connectionCache = null;

/**
* Constructor
*/
public executableTester2() throws SQLException
{
}

/**
* main
* @param args
*/
public static void main(String[] args) {
OracleConnectionPoolDataSource dataSource = null;

try{

dataSource = new OracleConnectionPoolDataSource() ;
connectionCache = new myOracleConnectCache( dataSource );

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

while ( i++ < 10 ) {
try{
workerClass1 worker = new workerClass1();
worker.setThreadNumber( i );
worker.setConnection( connectionCache.getConnection() );
worker.start();
System.out.println( "Started Thread#"+i );
}
catch ( Exception ex ){
ex.printStackTrace();
}
}
}
protected void finalize(){
try{
connectionCache.close();
} catch ( SQLException x) {
x.printStackTrace();
}
this.finalize();
}

}

The ConnectCacheImpl Member

package package6;
import javax.sql.ConnectionPoolDataSource;
import oracle.jdbc.pool.*;
import oracle.jdbc.driver.*;
import java.sql.*;
import java.sql.SQLException;

/**
* package6.myOracleConnectCache
*
*/
public class myOracleConnectCache extends
OracleConnectionCacheImpl {

/**
* Constructor
*/
public myOracleConnectCache( ConnectionPoolDataSource x)
throws SQLException {
initialize();
}

public void initialize() throws SQLException {
setURL("jdbc:oracle:oci8:@myDB");
setUser("scott");
setPassword("tiger");
//
// prefab 2 connection and only grow to 4 , setting these
// to various values will demo the behavior
//clearly, if it is not
// obvious already
//
setMinLimit(2);
setMaxLimit(4);

}

}

The Worker Thread Member

package package6;
import oracle.jdbc.pool.*;
import java.sql.*;
import javax.sql.*;

/**
* package6.workerClass1
*
*/
public class workerClass1 extends Thread {
// protected OracleConnectionPoolDataSource
ocpds = null;
// protected PooledConnection pc = null;

protected Connection conn = null;

protected int threadNumber = 0;
/**
* Constructor
*/

public workerClass1() {
}

public void doWork( ) throws SQLException {

// Create a pooled connection
// pc = ocpds.getPooledConnection();

// Get a Logical connection
// conn = pc.getConnection();

// Create a Statement
Statement stmt = conn.createStatement ();

// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery
("select ename from EMP");

// Iterate through the result
// and print the employee names
while (rset.next ())
// System.out.println (rset.getString (1));
;

// Close the RseultSet
rset.close();
rset = null;

// Close the Statement
stmt.close();
stmt = null;

// Close the logical connection
conn.close();
conn = null;

// Close the pooled connection
// pc.close();
// pc = null;

System.out.println( "workerClass1.thread#
"+threadNumber+" completed..");

}

public void setThreadNumber( int assignment ){
threadNumber = assignment;
}

// public void setConnectionPoolDataSource
(OracleConnectionPoolDataSource x){
// ocpds = x;
// }

public void setConnection( Connection assignment ){
conn = assignment;
}

public void run() {
try{
doWork();
}
catch ( Exception ex ){
ex.printStackTrace();
}
}

}

The OutPut Produced

Started Thread#1
Started Thread#2
workerClass1.thread# 1 completed..
workerClass1.thread# 2 completed..
Started Thread#3
Started Thread#4
Started Thread#5
workerClass1.thread# 5 completed..
workerClass1.thread# 4 completed..
workerClass1.thread# 3 completed..
Started Thread#6
Started Thread#7
Started Thread#8
Started Thread#9
workerClass1.thread# 8 completed..
workerClass1.thread# 9 completed..
workerClass1.thread# 6 completed..
workerClass1.thread# 7 completed..
Started Thread#10
workerClass1.thread# 10 completed..

posted @ 2007-07-13 01:46 Sun River| 编辑 收藏
--What is WSDL?

The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack.
In a nutshell, WSDL is an XML grammar for specifying a public interface for a Web service. This public interface can include the following:
Information on all publicly available functions.
Data type information for all XML messages.
Binding information about the specific transport protocol to be used.
Address information for locating the specified service.
--

posted @ 2007-07-12 23:45 Sun River| 编辑 收藏

--Explain about stored procedures
--I/O Filter
--Two types of multi-tasking
--Explain lazy activation
--How can a dead thread be started
--What is meant by flickering
--How do you load an Image in a Servlet ?
--What is meant by class loader ? How many types are there? When will we use them ?
---Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
--Write a program on RMI and JDBC using StoredProcedure ?
--Have you used threads in Servelet ?
--How do you invoke a Servelt?
--How will you pass parameters in RMI ?
--

--

posted @ 2007-07-12 15:26 Sun River| 编辑 收藏

--Question: What is similarities/difference between an Abstract class and Interface?
Answer:  Differences are as follows:

  • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  • Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 

Similarities:

  • Neither Abstract classes or Interface can be instantiated.

 --Question: What do you understand by Synchronization?
Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
     // Appropriate method-related code. 
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
    synchronized (this) { 
            // Synchronized code here.
         }
}
  
--Question: What is Collection API?
Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. 
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
  --

Question: Describe the principles of OOPS.
Answer: There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.  
 

Question: Explain the Encapsulation principle.
Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.  
 

Question: Explain the Inheritance principle.
Answer: Inheritance is the process by which one object acquires the properties of another object.  
 

Question: Explain the Polymorphism principle.
Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".   

Question: Explain the different forms of Polymorphism.
Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface

--Question: What do you understand by final value?
Answer: FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived.
--Question: How to convert String to Number in java program?
Answer: The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String strId = "10"; int id=Integer.valueOf(strId);

posted @ 2007-07-12 03:00 Sun River| 编辑 收藏
     摘要:     ---Which of the following methods can be called to change the state of the CMP entity bean from pooled to the ready state? ejbStore()   ejbCreate() ejbActivate() ejbFind...  阅读全文
posted @ 2007-07-09 16:36 Sun River| 编辑 收藏
  A message-driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. It acts as a JMS message listener, which is similar to an event listener except that it receives messages instead of events.
   Message-driven beans currently process only JMS messages, but in the future they may be used to process other kinds of messages.
  The most visible difference between message-driven beans and session and entity beans is that clients do not access message-driven beans through interfaces.

  When a message arrives, the container calls the message-driven bean's onMessage method to process the message. The onMessage method normally casts the message to one of the five JMS message types and handles it in accordance with the application's business logic. The onMessage method may call helper methods, or it may invoke a session or entity bean to process the information in the message or to store it in a database.

  A message may be delivered to a message-driven bean within a transaction context, so that all operations within the onMessage method are part of a single transaction. If message processing is rolled back, the message will be redelivered.
  Session beans and entity beans allow you to send JMS messages and to receive them synchronously, but not asynchronously. To avoid tying up server resources, you may prefer not to use blocking synchronous receives in a server-side component. To receive messages asynchronously, use a message-driven bean.

posted @ 2007-07-09 14:35 Sun River| 编辑 收藏
--Inner Join

Definition: An inner join is a join that selects only those records from both database tables that have matching values. Records with values in the joined field that do not appear in both of the database tables will be excluded from the query. One or more fields can serve as the join fields.
---Outer Join

Definition: An outer join selects all of the records from one database table and only those records in the second table that have matching values in the joined field. In a left outer join, the selected records will include all of the records in the first database table. In a right outer join, the selected records will include all records of the second database table. One or more fields can serve as the join fields.

posted @ 2007-07-09 13:58 Sun River| 编辑 收藏
A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods. An Enterprise JavaBean is not a single class but an entire component model (again, EJB 3 reduces the complexity of Enterprise JavaBeans).
posted @ 2007-07-06 22:27 Sun River| 编辑 收藏
SOA
---SOA:
   A service-oriented architecture is essentially a collection of services. These services communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity. Some means of connecting services to each other is needed.
---Service:
   A service is a function that is well-defined, self-contained, and does not depend on the context or state of other services.A service is the endpoint of a connection.
---Web Services refers to the technologies that allow for making connections.
---Questions:
   Are you familiar with SOA? 
   What is SOA? 
   What is a Web Service? 
   What is the difference between SOA and Web Services? 
   What is the difference between Web Services and SOAP? 
   What is the difference between SOAP and SOA?
---Most services are built on tools that provide the following components:
       Application and Service Components: Workflow, Business Process Execution, Orchestration

       Service Buses: Connectors, Caching, Policies, Scripting, Messaging
       Infrastructure Components: SOAP bindings, XML parsers, Message service bindings, clustering, replication and high availability
--ESB:
   An enterprise service bus (ESB) is a pattern of middleware that unifies and connects services, applications and resources within a business. it's a new way of looking at how to integrate applications, coordinate resources and manipulate information,
the ESB pattern enables the connection of software running in parallel on different platforms, written in different programming languages and using different programming models.

posted @ 2007-07-03 13:09 Sun River| 编辑 收藏
---How do you call a state of an entity object that is never persisted and not associated with any Session?
 A: transient
---Transient instances may be made persistent by calling which of the Session method (Choose all that apply)?
 A: Save, Update, Persist, Write, SaveOrUpdate.
  Transient instances may be made persistent by calling save, persist or saveOrUpdate. There is no such method like write and update - updates the persistent instance with the identifier of the given detached instance not transient.
---Is there a difference between
Pet pet = (Pet) session.get(Pet.class, petId);
and
Pet pet = (Pet) session.load(Pet.class, petId);
?
A:  There is a difference - if session.load can't find the object in the cache or database it throws an exception, while session.get just returns null. 
---Which of the following LockMode always increments version for versioned entities.
 

 

READ

 

WRITE

 +

FORCE

 

UPGRADE

 

INCREMENT


--- What kind of hibernate inheritance mapping strategies represents the hibernate mapping file (Person.hbm.xml)?

<hibernate-mapping>
   
<class
       name
="Person"
       table
="PERSON"
   
>
       
<id
           name
="id"
           column
="id"
           type
="long"
       
>
           
<generator class="increment"/>
       
</id>

       
<property name="name" column="name"/>
       
       
<joined-subclass
           name
="Worker"
           table
="WORKER"
       
>
           
<key column="id"/>
           
<property name="salary" column="salary"/>
       
</joined-subclass>
       
       
<joined-subclass
            name
="Student"
            table
="STUDENT"
       
>
           
<key column="id"/>
           
<property name="grade" column="salary"/>
       
</joined-subclass>
   
</class>
</hibernate-mapping>

 

+

Table per subclass

 

Table per class hierarchy

 

Table per concrete class

 

implicit polymorphism


---Assume that you want to see what SQL queries are used by Hibernate during the execution of the HQL commands. Fill the gap in order to enable the underlaying SQL commands logging.
<property name="__show_sql ___">true</property>
--- Given:
@Entity
public class Foo {
   @Id
   
private int id;
   ....
}

Choose correct statement.

+

It's a valid example of the @Id annotation usage.

 

It's not valid as @Id should be associated with a getter method (getId()) not a field.

 

It's not valid as @Id should be associated with both a field and a getter (getId()) method.

 

It's not valid as @Id should be associated with both a field and a setter (setId()) method.

---Hibernate provides <native> inheritance strategy indicating that we want to use native SQL inheritance mechanism. (F) 

SQL does not provide inheritance - that is one of the Object/Relation mismatches.
---Object Relational Mapping of hibernate is used to select, insert, update and delete the records form the underlying table. (T)
---Consider the following snippet:

<set name="foos" ______="joinPoint">
  
<key column="keyCol" />
  
<many-to-many class="Foo" />
</set>

Fill the gap in order to make the snippet above valid.
A: table

Many-to-many relationships requires setting the name of the table used to perform the join.

---Hibernate doesn't provide its own connection pooling facility i.e. you have to use some third parties pooling implementation like DBCP.(F)
   EX: Hibernate provides its own internal connection pooling facility. However the latter is intended to be used during a development phase - third party solutions are recommended to be used in the production.
---Collection can be used as a key type for a Hibernate map.(F)
Ex: Keys of Hibernate maps can be of any type (including composite type) except the collection types.
---Hibernate provides its own connection pooling facility. The latter is recommended to be used in the production instead of the third parties pooling implementation like DBCP.
The last sentence is true. (F)
Hibernate provides its own internal connection pooling facility. However the latter is intended to be used during a development phase - third party solutions are recommended to be used in the production.
---How many table(s) in a database represents the hibernate mapping file (Person.hbm.xml)?

<hibernate-mapping>
   
<class name="Person">
       
<id name="id">
          
<generator class="increment"/>
       
</id>
       
<discriminator column="PERSON_TYPE" type="string"/>
       
<property name="name"/>

       
<subclass name="Worker">
          
<property name="salary" column="SALARY"/>
       
</subclass>

       
<subclass name="Student">
          
<property name="grade" column="GRADE"/>
       
</subclass>
   
</class>
</hibernate-mapping> 
 

One table (PERSON) (T)

Three tables (PERSON, WORKER, STUDENT)

The quantity of tables depends of the type of database to which hibernate is connected


Ex:The mapping file represents the table per class hierarchy inheritance strategy and there is only one table for class hierarchy.

---Is it possible using annotations to declare readable name of a foreign key constraint in joined inheritance type ? (T)
---Consider the following code:

Session session;
// initialize the Session object properly
// for example using sessionFactory.openSession()
// ...
PersistedEntity entity = session.get(PersistedEntity.class, new Integer(1));

entity
.setValue("New Value");

session
.saveOrUpdate(entity);
session
.close();

If there is record in database for class PersistedEntity with ID of 1, the changes to the property 'value' will be correctly saved in the database. (F)
  Ex: The Hibernate framework has already associated the id 1 with the entity. When you try to saveOrUpdate it, it will complain that the object already exist in the session by throwing an HibernateException.
---Which of the following scopes of identity are defined in Hibernate? (all true)
 

No identity scope(def) : a database row can be represented as two java objects ..this is not supported as two objects can modify a record...         

Transacion scoped identity:In the context of a transaction a single object instance that represents a database row.
Allows some caching to be done at transaction level.

process scoped identity :one instance per row in whole jvm.


---Select all valid Hibernate queries.
select emp from Employee emp
select emp.id from Employee emp where exists ( from Education where name like 'Foo' and emp.id = employee.id )
select emp.id from Employee emp where exists ( from Education edu where edu.name like 'Foo' and emp.id = employee.id )
  select * from Employee as emp where exists ( from Education as edu where edu.name like 'Foo' and emp.id = employee.id )
from Employee as emp where exists ( from Education where name like 'Foo' and emp.id = employee.id )

explanation
The use of select * is not allowed in HQL. As an alternative you can leave out select * or use (in this case) select emp .

---In Hibernate which of the following properties of persistent class mapping have to be added (separately) to enable optimistic locking? (Choose all that apply) 
 

+

<timestamp>

 

<lock>

 

<optimistic-locking>

+

<version>

Ex::Optimistic locking is enabled when you add a <version> or a <timestamp> property to a persistent class mapping.
---Select the right lock levels that may be acquired by Hibernate.  

+

LockMode.WRITE

+

LockMode.READ

 

LockMode.READ_WRITE

+

LockMode.UPGRADE

+

LockMode.UPGRADE_NOWAIT

+

LockMode.NONE

There is no LockMode.READ_WRITE.
---By default, Hibernate works in the autocommit mode i.e. starts and commits the transaction after each operation like load or save. (F)
Ex:You have to flush the session or commit the transaction explicitly.
---One of the Hibernate supported inheritance mapping strategies is table per class hierarchy (An entire class hierarchy can be mapped to a single table).
Disadvantage of the strategy is that columns for properties declared by subclasses must be declared to be nullable. (T)
---What's the state of a newly created object?  

+

Transient.

 

Persistent.

 

Detached.

Ex: Objects created with a new operator are transient (are not associated with a database).
---Which is default cache service in Hibernate 3?  

+

EHCache

 

OSCache

 

TreeCache

 

SwarmCache

Default cache service in Hibernate 3 is EHCache
---Assume, that U have two persistent classes with the same unqualified name, for example com.jbb.JBB
and org.jbb.JBB
.Hibernate will throw an exception if you attempt to assign two classes to the same unqualified name when   auto-import
attribute set to "false".
(F)
If you have two persistent classes with the same (unqualified) name, you should set auto-import="false". Hibernate will throw an exception if you attempt to assign two classes to the same "imported" name
posted @ 2007-06-15 15:11 Sun River| 编辑 收藏
Here are some XML processing examples in Javascript. If you've got some XML data with XMLHttpRequest (there is actually no XMLHttpRequest in the examples - we create the XML object from a string - can be handy too) you need to read/convert etc. it to some other format and do something with it. Traversing a DOM/XML tree can be tricky, so have a look at these examples:
Example #1:
Using getElementsByTagName, we iterate thru the XML tree and read the numerous children/sibling.
<html>
<body>
<script>
var xmlstring = '<?xml version=\"1.0\"?>\
<shoppingcart date="14-10-2005" total="123.45">\
<item code="12345">\
<name>Widget</name>\
<quantity>1</quantity>\
</item>\
<item code="54321">\
<name>Another Widget</name>\
<quantity>2</quantity>\
</item>\
</shoppingcart>';
// convert the string to an XML object
var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
// get the XML root item
var root = xmlobject.getElementsByTagName('shoppingcart')[0];
var date = root.getAttribute("date");
alert("shoppingcart date=" + date);
var items = root.getElementsByTagName("item");
for (var i = 0 ; i < items.length ; i++) {
// get one item after another
var item = items[i];
// now we have the item object, time to get the contents
// get the name of the item
var name = item.getElementsByTagName("name")[0].firstChild.nodeValue;
// get the quantity
var quantity = item.getElementsByTagName("quantity")[0].firstChild.nodeValue;
alert("item #" + i + ": name=" + name + " quantity=" + quantity);
}
</script>
</body>
</html>
Example #2:
Here is a more universal example with the method "childNodes".
<html>
<body>
<script>
var xmlstring = '<?xml version="1.0"?>\
<root>\
<data>\
<row>\
<cell>Admiral</cell>\
<cell>Melon</cell>\
<cell>Carrot</cell>\
</row>\
<row>\
<cell>Captain</cell>\
<cell>Banana</cell>\
<cell>Zucchini</cell>\
</row>\
</data>\
<data>\
<row>\
<cell>Midshipman</cell>\
<cell>Orange</cell>\
<cell>Potatoe</cell>\
</row>\
</data>\
</root>';
// convert the string to an XML object
var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
// get the XML root item
var root = xmlobject.getElementsByTagName('root')[0];
for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
var node = root.childNodes.item(iNode);
for (i = 0; i < node.childNodes.length; i++) {
var sibling = node.childNodes.item(i);
for (x = 0; x < sibling.childNodes.length; x++) {
var sibling2 = sibling.childNodes.item(x);
if (sibling2.childNodes.length > 0) {
var sibling3 = sibling2.childNodes.item(0);
alert(sibling3.data);
}
}
}
}
</script>
</body>
</html>
posted @ 2007-06-14 06:40 Sun River| 编辑 收藏

---Is there any way that an AJAX object can get back a record set?

Answer

You could build an XML document out of your recordset and send that back to the server, say you had a redord set for a "user" with the following details (name, surname, age, email), you could build an xml document like this:

Code:
<recordset>
     <user>
         <name>Byron</name>
         <surname>Tymvios</surname>
         <age>25</age>
         <email>email@address.com</email>
     </user>
     <user>
         <name>User</name>
         <surname>Someone</surname>
         <age>39</age>
         <email>myAddy@address.com</email>
     </user>
</recordset>

You can add as many records as you have in your recordset, then once the client has received it you can use javascript to iterate over the <user>'s in the xml.


---Is it possible to set session variables from javascript?
It's not possible to set any session variables directly from javascript as it is purely a client side technology. You can use AJAX though to asyncronously send a request to a servlet running on the server and then add the data to the session from within the servlet. So you wouldn't be using javascript to do the actual setting of session variables but it would look like it is.
  I've been developing a sliding navigational menu. Here is how I save the state across pages:

var saveState = true;
if(saveState)
{
// This AJAX call will save the Navigator's state to session.
// We don't need a callback function because nothing happens
// once said state is saved.
var url = "AJAX_Servlet.aspx?function=saveNavigatorState&control=" + id + "&class=" + section.className + "";
req = new ActiveXObject("Microsoft.XMLHTTP");
req.open("POST", url, true);
req.send();
}


Note that id is set to the Id of the submenu table (which is hidden / shown by other code which sets the className of the table. My stylesheet has css for each class.) earlier in the overal function.
Here is the codebehind for my AJAX_Servlet.aspx, which could easily be a web service:

private void Page_Load(object sender, System.EventArgs e)
{
if(Request.QueryString["function"] != null)
{
if(Request.QueryString["function"] == "saveNavigatorState")
SaveNavigatorState();
}
}
private void SaveNavigatorState()
{
if(Request.QueryString["control"] != null && Request.QueryString["class"] != null)
{
string controlID = Request.QueryString["control"].ToString();
string className = Request.QueryString["class"].ToString();
Session[controlID] = className;
}
}


Then on my navigator codebehind, I just check for session data on load.
posted @ 2007-06-14 06:26 Sun River| 编辑 收藏
    只有注册用户登录后才能阅读该文。阅读全文
posted @ 2007-06-14 03:31 Sun River| 编辑 收藏
   Part I    Java SE
1. tell me some classes in the java collections?
2. hashmap is interface or class?
3. what is reflection? how do you use it? give an situation.

  Part II  JavaScript
1. How to create a new browser?

  Part III XML and SOAP
1. XSL for what?
2. Caster for what?
3. JDOM explain?
4. JAXB?
5. explain soap?
6. what kind class in soap?
7.
  Part IV JDBC and transaction and weblogic setup for db?
1. Oracle stored procedure?
2. Prefined statement?
3.   
  Part V Struts
  Part VI Java EE
 
posted @ 2007-06-02 01:03 Sun River| 编辑 收藏

   Yet only a handful of those protocols are commonly used, chief amongst them is HTTP. HTTP is particularly attractive because it is accepted by corporate firewalls. Consequently, HTTP has outgrown its origins in Web browsing and has been adopted by many applications. For example, the latest XML protocols, such as SOAP, are also build on HTTP.

Java Support

Java supports HTTP through two APIs. The servlet API (and JSP) covers server-side programming while the java.net package offers client-side support through HttpURLConnection.

While I have had few problems with the servlet API, I have found that HttpURLConnection requires some work to interface with firewalls. All the services you need are available but the documentation is sketchy at best. Here are some of the problems I have encountered... and the solutions.

Typically, a client on a corporate network has no direct connection to the Internet. Access goes through proxy servers that monitor the traffic and enforce security rules.

The Basics

In the java.net API, proxies are supported through two system properties: http.proxyHost and http.proxyPort. They must be set to the proxy server and port respectively. The following code fragment illustrates it:

 String url = http://www.marchal.com/,

 proxy = "proxy.mydomain.com",

 port = "8080";

 URL server = new URL(url);

 Properties systemProperties = System.getProperties();

systemProperties.setProperty("http.proxyHost",proxy);

systemProperties.setProperty("http.proxyPort",port);

HttpURLConnection connection = (HttpURLConnection)server.openConnection();

connection.connect();

InputStream in = connection.getInputStream();

readResponse(in);          

Of course, you would need to use the proxy and port values suitable for your network. You can most likely find them in the configuration of your browser. If unsure, ask your system administrator.

Using Authentication

Increasingly, companies require employees to log in to the proxy before accessing the Internet. Login is used to better monitor Internet usage; for example, to monitor what sites are visited.

 HttpURLConnection supports proxy authentication through the Authenticator class. To enable authentication, your application subclasses Authenticator and defines the getPasswordAuthentication() method. A minimalist implementation is as follows:

 public class SimpleAuthenticator   extends Authenticator

         {

            private String username, password;

             public SimpleAuthenticator(String username,String password)

            {

               this.username = username;

               this.password = password;

                       }

            protected PasswordAuthentication getPasswordAuthentication()

                        {

               return new PasswordAuthentication(

                username,password.toCharArray();
                         }

              }

     Next, it must register the authenticator through Authenticator.setDefault(). If we adapt the previous code sample to use Authenticator, it looks like this:                        

         String url = "http://www.marchal.com/",

                                 proxy = "proxy.mydomain.com",

                                 port = "8080",     

                            username = "usr",

                            password = "pwd";             

         Authenticator.setDefault(new SimpleAuthenticator(username,password));     

         URL server = new URL(url);  

         Properties systemProperties = System.getProperties();    

       systemProperties.setProperty("http.proxyHost",proxy);            

         systemProperties.setProperty("http.proxyPort",port);               

         HttpURLConnection connection = ( HttpURLConnection)server.openConnection();

         connection.connect();

         InputStream in = connection.getInputStream();

         readResponse(in);                

A More Serious Issue

So far, I have covered the most common situations where HttpURLConnection works properly. However, I have encountered a few networks where HttpURLConnection is not usable.

 It appears that the problem is linked to a faulty configuration of the DNS server. For some reason, HttpURLConnection always attempts to resolve the host name against the DNS server. Normally, it fails gracefully and the connection goes is rerouted through the proxy server. A few DNS servers return an inappropriate answer that results in a UnknownHostException.

 There's an interesting theoretical debate as to whether the DNS server behaviour is acceptable. Although I am no expert on the topic, it would appear it is not. However, as a developer, you seldom have the option to reconfigure the DNS server, so you have to find a workaround.

 My solution is to roll out my own implementation of the HTTP protocol. In its simplest form, a GET request looks like the following listing:                                  

         String url = "http://www.marchal.com/",

         proxy = "proxy.mydomain.com",

         port = "8080",

         authentication = "usr:pwd";

         URL server = new URL(url);

         Socket socket = new Socket(proxy,port);

       Writer writer = new OutputStreamWriter(socket.getOutputStream(),   "US-ASCII");

         writer.write("GET " + server.toExternalForm() + " HTTP/1.0\r\n");

       writer.write("Host: " + server.getHost() + "\r\n");

         writer.write("Proxy-Authorization: Basic "

                      + new sun.misc.BASE64Encoder().encode(authentication.getBytes())+ "\r\n\r\n");

         writer.flush();

         BufferedReader reader = new BufferedReader(new InputStreamReader(         

                            socket.getInputStream(),"US-ASCII"));

         String line = reader.readLine();

         if(line != null && line.startsWith("HTTP/"))

         {

            int sp = line.indexOf(' ');

            String status = line.substring(sp + 1,sp + 4);

            if(status.equals("200"))

            {

               while(line.length() != 0)

                 line = reader.readLine();

               readResponse(reader);

            }

    else     throw new FileNotFoundException("Host reports error " +    status);

         }

 else

   throw new IOException("Bad protocol"); 

 reader.close();    

writer.close();

socket.close();            

Notice that the proxy username and password are given as username:password and are later encoded in base 64.

 Conclusion

HTTP is an interesting protocol because it is supported by all corporate firewalls. The Java developer needs to pay special attention to proxies and other authentication issues, though.

posted @ 2007-03-06 10:52 Sun River| 编辑 收藏

(1)假设在helloapp应用中有一个hello.jsp,它的文件路径如下:
%CATALINA_HOME%/webapps/helloapp/hello/hello.jsp    
那么在浏览器端访问hello.jsp的URL是什么? (单选)
选项:
(A) http://localhost:8080/hello.jsp
(B) http://localhost:8080/helloapp/hello.jsp
(C) http://localhost:8080/helloapp/hello/hello.jsp

(2)假设在helloapp应用中有一个HelloServlet类,它位于org.javathinker包下,那么这个类的class文件应该放

在什么目录下? (单选)
选项:
(A) helloapp/HelloServlet.class
(B) helloapp/WEB-INF/HelloServlet.class
(C) helloapp/WEB-INF/classes/HelloServlet.class
(D) helloapp/WEB-INF/classes/org/javathinker/HelloServlet.class

(3)假设在helloapp应用中有一个HelloServlet类,它在web.xml文件中的配置如下:
<servlet>
  <servlet-name> HelloServlet </servlet-name>
  <servlet-class>org.javathinker.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name> HelloServlet </servlet-name>
  <url-pattern>/hello</url-pattern>
</servlet-mapping>
那么在浏览器端访问HelloServlet的URL是什么? (单选)
选项:
(A) http://localhost:8080/HelloServlet
(B) http://localhost:8080/helloapp/HelloServlet
(C) http://localhost:8080/helloapp/org/javathinker/hello
(D) http://localhost:8080/helloapp/hello


(4)客户请求访问HTML页面与访问Servlet有什么异同?(多选)
选项:
(A)相同:都使用HTTP协议
(B)区别:前者Web服务器直接返回HTML页面,后者Web服务器调用Servlet的方法,由Servlet动态生成HTML页面
(C)相同:前者Web服务器直接返回HTML页面,后者Web服务器直接返回Servlet的源代码。
(D)区别:后者需要在web.xml中配置URL路径。
(E)区别:前者使用HTTP协议,后者使用RMI协议。


(5)HttpServletRequest对象是由谁创建的?(单选)
选项:
(A)由Servlet容器负责创建,对于每个HTTP请求, Servlet容器都会创建一个HttpServletRequest对象
(B)由JavaWeb应用的Servlet或JSP组件负责创建,当Servlet或JSP组件响应HTTP请求时,先创建

HttpServletRequest对象


(6)从HTTP请求中,获得请求参数,应该调用哪个方法? (单选)
选项:
(A)调用HttpServletRequest对象的getAttribute()方法
(B)调用ServletContext对象的getAttribute()方法
(C)调用HttpServletRequest对象的getParameter()方法

(7)ServletContext对象是由谁创建的?(单选)
选项:
(A)由Servlet容器负责创建,对于每个HTTP请求, Servlet容器都会创建一个ServletContext对象
(B)由JavaWeb应用本身负责为自己创建一个ServletContext对象
(C)由Servlet容器负责创建,对于每个JavaWeb应用,在启动时,Servlet容器都会创建一个ServletContext对象


(8)jspForward1.jsp要把请求转发给jspForward2.jsp,应该在jspForward1.jsp中如何实现? (单选)
选项:
(A) <a href=“jspForward2.jsp”>jspForward2.jsp </a>
(B) <jsp:forward page=“jspForward2.jsp”>

(9)当浏览器第二次访问以下JSP网页时的输出结果是什么?(单选)

<!% int a=0;     %>
<%
     int b=0;
     a++;
     b++;
%>

a:<%= a %> <br>
b:<%= b %>
  
选项:
(A)  a=0  b=0
(B) a=1  b=1
(c) a=2  b=1

(10)下面哪个说法是正确的? (单选)
选项:
(A) 对于每个要求访问maillogin.jsp的HTTP请求,Servlet容器都会创建一个HttpSession对象
(B)每个HttpSession对象都有惟一的ID。
(C)JavaWeb应用程序必须负责为HttpSession分配惟一的ID

(11)如果不希望JSP网页支持Session,应该如何办? (单选)
选项:
(A) 调用HttpSession的invalidate()方法
(B) <%@ page session= “false\">


(12)在标签处理类中,如何访问session范围内的共享数据? (多选)
选项:
(A)在TagSupport类中定义了session成员变量,直接调用它的getAttribute()方法即可。
(B)在标签处理类TagSupport类中定义了pageContext成员变量,先通过它的getSession()方法获得当前的

HttpSession对象,再调用HttpSession对象的getAttribute()方法。
(C)pageContext.getAttribute(“attributename”,PageContext.SESSION_SCOPE)


(13)在下面的选项中,哪些是TagSupport类的doStartTag()方法的有效返回值? (多选)
选项:
(A) Tag.SKIP_BODY
(B) Tag.SKIY_PAGE
(C) Tag.EVAL_BODY_INCLUDE
(D) Tag.EVAL_PAGE


(14)以下代码能否编译通过,假如能编译通过,运行时得到什么打印结果?(单选)
request.setAttribute(\"count\",new Integer(0));
Integer count = request.getAttribute(\"count\");
选项:
A)不能编译通过  B)能编译通过,并正常运行  
C) 编译通过,但运行时抛出ClassCastException

答案:
(1)C (2)D  (3)D  (4)A,B,D  (5)A  (6)C  (7)C  (8)B  (9)C   (10)B
(11)B  (12)B,C  (13)A,C  (14)A

判断题:(其它试题请下载)

1 . Java 程序里 , 创建新的类对象用关键字 new ,回收无用的类对象使用关键字 free 。

2 .对象可以赋值,只要使用赋值号(等号)即可,相当于生成了一个各属性与赋值对象相同的新对象。

3 .有的类定义时可以不定义构造函数,所以构造函数不是必需的。

4 .类及其属性、方法可以同时有一个以上的修饰符来修饰。

5 . Java 的屏幕坐标是以像素为单位,容器的左下角被确定为坐标的起点

6 .抽象方法必须在抽象类中,所以抽象类中的方法都必须是抽象方法。

7 . Final 类中的属性和方法都必须被 final 修饰符修饰。

8 .最终类不能派生子类,最终方法不能被覆盖。

9 .子类要调用父类的方法,必须使用 super 关键字。

10 .一个 Java 类可以有多个父类。

11 .如果 p 是父类 Parent 的对象,而 c 是子类 Child 的对象,则语句 c = p 是正确的。

12 .一个类如果实现了某个接口,那么它必须重载该接口中的所有方法。

13 .当一个方法在运行过程中产生一个异常,则这个方法会终止,但是整个程序不一定终止运行。

14 .接口是特殊的类,所以接口也可以继承,子接口将继承父接口的所有常量和抽象方法。

15 .用“ + ”可以实现字符串的拼接,用 - 可以从一个字符串中去除一个字符子串。

16 .使用方法 length( ) 可以获得字符串或数组的长度。

17 .设 String 对象 s=”Hello ” ,运行语句 System.out.println(s.concat(“World!”)); 后 String 对象 s 的内容为 ”Hello world!” ,所以语句输出为

Hello world!

18 .创建 Vector 对象时构造函数给定的是其中可以包容的元素个数,使用中应注意不能超越这个数值。

19 .所有的鼠标事件都由 MouseListener 监听接口的监听者来处理。

20 .一个容器中可以混合使用多种布局策略。

21 . Java 中,并非每个事件类都只对应一个事件。

22 .一个线程对象的具体操作是由 run() 方法的内容确定的,但是 Thread 类的 run() 方法是空的 , 其中没有内容 ; 所以用户程序要么派生一个 Thread 的子类并在子类里重新定义 run() 方法 , 要么使一个类实现 Runnable 接口并书写其中 run() 方法的方法体。

23 . Java 的源代码中定义几个类,编译结果就生成几个以 .class 为后缀的字节码文件。

24 . Java Applet 是由独立的解释器程序来运行的。

25 . Java Applet 只能在图形界面下工作。

26 . Java 的字符类型采用的是 ASCII 编码。

27 . Java 的各种数据类型占用固定长度,与具体的软硬件平台环境无关

28 . Applet 是一种特殊的 Panel ,它是 Java Applet 程序的最外层容器。

29 .子类的域和方法的数目一定大于等于父类的域和方法的数目。

30 . System 类不能实例化,即不能创建 System 类的对象。

31 .用户自定义的图形界面元素也可以响应用户的动作,具有交互功能

32 . Java 中数组的元素可以是简单数据类型的量,也可以是某一类的对象。

33 . Vector 类中的对象不能是简单数据类型。

34 . Java 中的 String 类的对象既可以是字符串常量,也可以是字符串变量。

35 .容器是用来组织其他界面成分和元素的单元,它不能嵌套其他容器。

posted @ 2007-02-22 11:59 Sun River| 编辑 收藏
  1. How EJB Invocation happens? - Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client. Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to Bean (Enterprise Bean).
  2. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? - You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as passed-by-value, that means that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it.

  3. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is, again, up to the implementer.
  4. Can the primary key in the entity bean be a Java primitive type such as int? - The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive).
  5. Can you control when passivation occurs? - The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD -”The passivation-strategy can be either “default” or “transaction”. With the default setting the container will attempt to keep a working set of beans in the cache. With the “transaction” setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).
  6. What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other? - Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you dont need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container.
  7. What is EJB QL? - EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistenceand is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.
  8. Brief description about local interfaces? - EEJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.
  9. What are the special design care that must be taken when you work with local interfaces? - It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.
  10. What happens if remove( ) is never invoked on a session bean? - In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.
  11. What is the difference between Message Driven Beans and Stateless Session beans? - In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.
  12. How can I call one EJB from inside of another EJB? - EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.
  13. What is an EJB Context? - EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.
posted @ 2006-12-18 19:28 Sun River| 编辑 收藏

-- Facade: Provide a unified interface to a set of interfaces in a subsystem, it defines a higher-level interface that makes the subsystem easier to use.

posted @ 2006-12-15 19:33 Sun River| 编辑 收藏

Question: How you will handle exceptions in Struts?
Answer: In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
Example:

<exception 
      key="database.error.duplicate" 
      path="/UserExists.jsp" 
      type="mybank.account.DuplicateUserException"/>
b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.
Question:Explain Struts navigation flow?
Struts Navigation flow.
1) A request is made from previously displayed view.
2) The request reaches the ActionServlet which acts as the controller .The ActionServlet Looksup the requested URI in an XML file (Struts-Config.xml) and determines the name of the Action class that has to perform the requested business logic.
3)The Action Class performs its logic on the Model Components associated with the Application.
4) Once The Action has been completed its processing it returns the control to the Action Servlet.As part of its return the Action Class provides a key to determine where the results should be forwarded for presentation.
5)The request is complete when the Action Servlet responds by forwarding the request to the view, and this view represents the result of the action.
Question: What is the purpose of tiles-def.xml file, resourcebundle.properties file, validation.xml file?
1. tiles-def.xml
  tiles-def.xml is used as a configuration file for an appliction during tiles development. You can define the layout / header / footer / body content for your View.
  Eg:
<tiles-definitions>
   <definition name="siteLayoutDef" path="/layout/thbiSiteLayout.jsp">
      <put name="title" value="Title of the page" />
      <put name="header" value="/include/thbiheader.jsp" />
      <put name="footer" value="/include/thbifooter.jsp" />
      <put name="content" type="string">
      Content goes here
   </put>
  </definition>
</tiles-definitions>

<tiles-definitions>
<definition name="userlogin" extends="siteLayoutDef">
<put name="content" value="/dir/login.jsp" />
</definition>
</tiles-definitions>

2. validation.xml
The validation.xml file is used to declare sets of validations that should be applied to Form Beans.
Each Form Bean you want to validate has its own definition in this file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields. Eg:

<form-validation>
<formset>
<form name="logonForm">
<field property="username"
depends="required">
<arg0 key=" prompt.username"/>
</field>
<field property="password"
depends="required">
<arg0 key="prompt.password"/>
</field>
</form>
</formset>
</form-validation>

3. Resourcebundle.properties

Instead of having hard-coded error messages in the framework, Struts Validator allows you to specify a key to a message in the ApplicationResources.properties (or resourcebundle.properties) file that should be returned if a validation fails. Eg:

In ApplicationResources.properties
errors.registrationForm.name={0} Is an invalid name.
In the registrationForm.jsp
<html:messages id="messages" property="name">
<font color="red">
<bean:write name="messages" />
</html:messages>

Output(in red color) : abc Is an invalid name

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

1. Purpose of tiles-def.xml file is used to in the design face of the webpage. For example in the webpage "top or bottom or left is
fixed" center might be dynamically chaged.
It is used for the easy design of the web sites. Reusability

2. resourcebundle.properties file is used for lot of purpose. One of its purpose is internationalization. We can make our page to view on any language. It is independent of it. Just based on the browser setting it selects the language and it displayed as you mentioned in the resourcebundle.properties file.

3. Validation rule.xml is used to put all the validation of the front-end in the validationrule.xml. So it verifies. If the same rule is applied in more than one page. No need to write the code once again in each page. Use validation to chek the errors in forms.

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

tiles-def.xml - is required if your application incorporates the tiles framework in the "View" part of MVC. Generally we used to have a traditional JSP's (Which contgains HTML & java scriplets) are used in view. But Tiles is an advanced (mode or less ) implementation of frames used in HTML. We used to define the frames in HTML to seperate the header html, footer html, menu or left tree and body.html to reuse the contents. Hence in the same way, Tiles are defined to reuse the jsp's in struts like architectures, and we can define the jsp's which all are to be display at runtime, by providing the jsp names at runtime. To incorporate this we need tile-def.xml and the Class generally which extends RequestProcessor should extend TilesRequestProcessor.

resourcebundle.properties — It is to incorporate i18n (internationalization) in View part of MVC.

validation.xml - This file is responsible for business validations carried at server side before processing the request actually. It reduces the complexity in writing _JavaScript validations, and in this way, we can hide the validations from the user, in View of MVC.

Question: What we will define in Struts-config.xml file. And explain their purpose?
In struts-config.xml we define Date Sources / Form Beans / Global Exceptions / Global Forwards / Action Mappings / Message Resources / Plug-ins

Example :

<!– Date Sources –>
<data-sources>
<data-source autoCommit="false" description="First Database Config" driverClass=" org.gjt.mm.mysql.Driver" maxCount="4" minCount="2" password="admin" url="jdbc: mysql://localhost/ARTICLEDB" user="admin">
</<data-sources>
<!– Form Beans –>
<form-beans>
<form-bean name="registrationForm" type="com.aaa.merchant.wsp.ActionForms.RegistrationForm">
</form-bean>

<!– Global Exceptions –>
<global-exceptions>
<exception key="some.key" type="java.io.IOException" handler="com.yourcorp.ExceptionHandler"/>

</global-exceptions>

<!– A global-forward is retrieved by the ActionMapping findForward method. When the findForward method can't find a locally defined forward with the specified name, it searches the global-forwards available and return the one it finds.–>
<global-forwards>
<forward name="logoff" path="/logoff"/>
<forward name="logon" path="/logon.jsp"/>
</global-forwards>

<!– Actionn Mappings –>
<action-mappings>
<action path="/validateRegistration" type="com.dd.merchant.wsp.Actions.ValidateRegistration" validate="true" input="" name="registrationForm">
<forward name="success" path="/logon.jsp">
</forward>
</action>
</action-mappings>

<!– Message Resources –>
<message-resources parameter="wsppaymentsweb.resources.ApplicationResources"/>

<!– Plug-ins –>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>

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

Struts-Config.xml is one of the most important part of any web application based on Sturts. This file is responsible for instructing the Struts what forms are available, what actions are available, and also allows a number of plug-in models to be added to the base Struts package. It can contain Data Source Configuration,Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions, Message Resources Definitions etc.

The most important are Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions.

The <form-bean/> is configured using only two attributes, name and type and doesn't contain any body. The form-bean tag is used to describe an instance of a particular Form Bean that will be later bound to action.

The attribute name specifies the name of the form bean, which is a unique identifier to this form bean & the attribute type specifies the absolute path of the class file.

<global-forwards/>: It is also configured using only two attributes, name and path and there is also an optional attribute redirect. The <forward/> specifies the mapping of a logical name to a context-relative URI path. In the above sample xml file we can see, one of the <forward/> is specified with the name as failure and its corresponding path as index.jsp. That means whenever the logical name failure is encountered the action will be forwarded to the index.jsp page.

The optional attribute redirect is set to false by default. When it is set to true it causes the ActionServlet to use HttpSevletResponse.sendRedirect() method.

<action-mappings/>: The action mapping mainly defines the mapping between the logical Action name and the physical action class. Now lets have an understanding about its attributes.

· The attribute path must be compulsorily defined and it should start with a '/' character. It specifies the context relative path of the submitted request.

· The type attribute specifies the absolute path of the fully qualified class name of the Action class.

· The attribute name must be the same as that of the form bean name for which you want to associate the action.

· The attribute scope specifies the scope of the particular form bean which is an optional one and its default value is session.

· The next attribute validate is also an optional one which by default is set to true. When set to true, the validate() method in the form bean is called which gets associated with a particular Action.

· The next attribute, input is also optional. Whenever a validation error is encountered then the control returns to the path specified in the input attribute.

<controller/>: The <controller/> can be used to modify the default behaviour of the Struts Controller i.e, we can define a RequestProcessor.

===============================
In struts-config.xml, we define all the global-forwards, action mappings, view mappings, form-bean mappings, controller mapping and finally message-resources declaration if any.
Why we need to declare means, the Controller servelet defined in struts internally looks for this xml file for its proceddings. In real scenario, that the controller servlet inplemented internally is nothing but a slave to this struts-config.xml. The information provided in this file is nothing but like the intelligence to the controller servlet to say - what to do in which situation ?
So, Controller servlet, needs this file to proceede/ run the application.

What is DispatchAction?

DispatchAction is specialized child of Struts Action class. It combines or group the methods that can further access the bussiness logic at a single place. The method can be anyone from CRUD [Create,Retrieve,Update or Delete] or it can be security check one like autheniticate user etc.
This class apart from having thread-safe execute method also can have user-defined methods.
In struts-config.xml files following changes are required for Dispatch action to work:

<action-mappings>
<action path="/login"
type ="com…..LoginAction"
name ="loginForm"
parameter ="task"
scope = "request"
validate = "false"
input = "/index.jsp">
<forward name="success" path="/jsp/common/index.jsp"/>
<forward name="loginagain" path="/index.jsp"/>
</action>
</action-mappings>

If above is your struts-config.xml file structure and LoginAction extends DispatchAction instead of normal Action class. And assuming [keep assuming] your LoginAction class have method named authenticateUser, then in your login.jsp add any hidden parameter called task with value as your method name and on submit of that page following will be the url:

http://localhost:8080/yourproject/jsp/login.jsp?login.do&task=authenticateUser

Thus if we try to combine the last part of this puzzle we get the climax at struts-config.xml file's action-mapping tag described above. The parameter property of <action> tag have the task as it's value pointing to task variable in the request having it's value as authenticateUser hence the framework search in the LoginAction a method called authenticateUser through reflection and forwards the execution flow to it. This is all folks, the briallancy of Struts framework. Note DispatchAction class is included in 1.1 version.

 

How to call ejb from Struts?

 

We can call EJB from struts by using the service locator design patteren or by Using initial context with create home object and getting return remote referenc object.

What is the difference between ActionErrors and ActionMessages?

There is no differnece between these two classes.All the behavior of ActionErrors was copied into ActionMessages and vice versa. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — where as errors being only one kind of message.

The difference between saveErrors(…) and saveMessages(…) is simply the attribute name under which the ActionMessages object is stored, providing two convenient default locations for storing controller messages for use by the view. If you look more closely at the html:errors and html:messages tags, you can actually use them to get an ActionMessages object from any arbitrary attribute name in any scope.

 

What are the various Struts tag libraries?

The Struts distribution includes four tag libraries for the JSP framework (in struts-config.xml) :
* Bean tag library [ struts-bean.tld ] : Contains tags for accessing JavaBeans and their properties. Developers can also define new beans and set properties
* HTML tag library [ struts-html.tld ] : Contains tags to output standard HTML, including forms, textfields, checkboxes, radio buttons
* Logic tag library [ struts-logic.tld ] : Contains tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library [ struts-tiles.tld / struts-template.tld ] : For tiles implementation
* Nested tag library [ struts-nested.tld ] : allows the use of nested beans.

The libraries are designed to:

* Facilitate the separation of presentation and business logic.
* Dynamically generate Web pages.
* Implement the flow of control to and from the ActionServlet.

How you will handle errors and exceptions using Struts?

Struts exception handling can be done by two ways:
1. Declarative (using struts features via struts-config.xml)

<global-exceptions>
<exception
type="hansen.playground.MyException2"
key ="errors.exception2"
path="/error.jsp"/>
</global-exceptions>

This makes coding in the Action class very simple
Since the execute method declares throws Exception we don't need a try-catch block.
Struts saves the exception using one of its global constants. You may use the field G lobals.EXCEPTION_KEY to retrieve it from the request object.

2. Programmatic (using the usual try-catch exception handling in Action Class)

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

We can Handle the errors by holding them into ActionError or ActionErrors classes defined by struts Framework. The other way around is by using the methods say saveErrors()….etc defined in Action class and can throw the error messages.

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

Struts handles errors by providing the ActionErrors class which is
extended from org.apache.struts.action…
To install your customized exception handler, the first step is to
create a class that extends org.apache.struts.action.ExceptionHandler. There are
two methods that you can override, execute() and storeException().
For handling exceptions you have to mention in <global-exceptions> tag
of struts-config.xml which accepts attributes like exception type,key and
path.

How you will save the data across different pages for a particular client request using Struts?

One simple and general way is by using session Object.

In specific, we can pass this by using request Object as well.

======================================
Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request.

request.getSession()
session.setAttribute()

What is Action Class? What are the methods in Action class?

An Action class is some thing like an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.
The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method. Struts Action class is a unit of logic. It is where a call to business function is made. In short the Action class acts like a bridge between client side(user action) and business operation(on server.
Some of the impotant methods of Action class are, execute()
generateToken() resetToken() getServlet()

Explain about token feature in Struts?

 

Use the Action Token methods to prevent duplicate submits:
There are methods built into the Struts action to generate one-use tokens. A token is placed in the session when a form is populated and also into the HTML form as a hidden property. When the form is returned, the token is validated. If validation fails, then the form has already been submitted, and the user can be apprised.
 saveToken(request)
on the return trip,
 isTokenValid(request)
resetToken(request)

What is the difference between ActionForm and DynaActionForm

# The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

# The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.

# ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

# ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).

# DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

# Time savings from DynaActionForm is insignificant. It doesn t take long for today s IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters and setters in the IDE than fixing your Action code and redeploying your web application)

posted @ 2006-12-04 15:46 Sun River| 编辑 收藏

Tech Tips Quiz

Over the years, the Enterprise Java Technologies Tech Tips have covered a wide variety of enterprise Java technology topics. Here's a short quiz that tests your knowledge of some topics covered in past Tech Tips. You can find the answers at the end of the quiz.

1.                  Which of the following inheritance strategies is not supported by the Java Persistence API?

a.                               Single Table Per Class Hierarchy

b.                              Joined Subclass

c.                               Single Table Per Class

d.                              Multiple Hierarchy

2.                  What is the primary purpose of the javax.xml.ws.Provider API?

a.                               Binds XML to Java objects.

b.                              Allows web services to work directly with messages.

c.                               Simplifies WSDL creation.

d.                              Specifies the URL of a web service provider.

e.                               None of the above

3.                  Which of the following statements about the ELResolver class is true?

a.                               In Java EE 5, the classes VariableResolver and PropertyResolver have been merged into the ELResolver class.

b.                              The way an expression is resolved can be customized by adding custom ELResolver subclasses to the ELResolver chain.

c.                               To make an ELResolver class visible to the Java EE runtime, it must be declared in an application configuration resource file.

d.                              All of the above.

4.                  What does the <service-name-pattern> element in the following set of XML statements do: 
            <handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
              <handler-chain>\
               <service-name-pattern   xmlns:ns1="http://example.com/handlers">
    
           ns1:HelloService      
                  </service-name-pattern>

    
                   <handler/>
    
                   <handler/>
    
               </handler-chain>
              </handler-chains>
    

a.                               Applies the handlers specified in the <handler-chain> element to the service with the Java EE qname {http://example.com/handlers}HelloService .

b.                              Adds a service named HelloService to the handlers specified in the <handler-chain> element.

c.                               Applies the handlers specified in the <handler-chain> element to all ports whose names begin with HelloService .

d.                              None of the above.

 

5.                  What role does an XMLHttpRequest object play in an AJAX-enabled application?

a.                               It's used as a proxy to transmit requests to a server in a different domain.

b.                              It's used to identify a filter for exchange of XML-based AJAX requests between the client and server.

c.                               It's used to transmit AJAX requests asynchronously over HTTP to a server-side component.

d.                              There is no such thing as an XMLHttpRequest object.

Answers

1.                  Which of the following inheritance strategies is not supported by the Java Persistence API?

d.                              Multiple Hierarchy. The Java Persistence API allows for three different inheritance strategies that dictate how subclasses are mapped to database tables. The three strategies are single table per class hierarchy, joined subclass, and single table per class. 

 

2.                  What is the primary purpose of the javax.xml.ws.Provider API?

b.                              Allows web services to work directly with messages. The JAX-WS 2.0 specification provides two new APIs which make it possible for web services to work with messages or message payloads. The APIs are javax.xml.ws.Provider and java.xml.ws.Dispatch . Provider is a server-side API, while Dispatch is a client-side API. 
 

3.                  Which of the following statements about the ELResolver class is true?

d.                              All of the above. For more about the ELResolver class, especially how to create a customized ELResolver .

 

4. What does the <service-name-pattern> element in the following set of XML statements do: 
            <handler-chains xmlns="http://java.sun.com/xml/ns/javaee">        
            <handler-chain>
      
                 <service-name-pattern 

    
               xmlns:ns1="http://example.com/handlers">     
                      ns1:HelloService

                       </service-name-pattern>  

                <handler/>  
                <handler/>

    
             </handler-chain>
    
       </handler-chains>
    
e.       Applies the handlers in the specified in the <handler-chain>element to the service with the Java EE qname {http://example.com/handlers}HelloService. The <service-name-pattern>element applies handlers to specific services. Handlers are interceptors that can be easily plugged into the JAX-WS 2.0 runtime environment to do additional processing of inbound and outbound messages. A handler chain is an ordered list of handlers that is used for configuring handlers. .

5.What role does an XMLHttpRequest object play in an AJAX-enabled application?

  c.      It's used to transmit AJAX requests asynchronously over HTTP to a server-side component. An XMLHttpRequest object plays a central role in the AJAX methodology as the means of interaction between the client and server-side component that processes AJAX requests. 

 

posted @ 2006-11-27 09:26 Sun River| 编辑 收藏
     摘要: Part I. XSLT Programming   1)   What is the exac...  阅读全文
posted @ 2006-11-27 08:00 Sun River| 编辑 收藏
1). Processing (parsing) XML documents using: 
   - Document Object Model (DOM)
   - Simple API for XML (SAX)
   Transforming XML documents using 
   -
XSL/XSLT
   - XPath
2).

Steps for DOM Parsing

1. Tell the system which parser you will use

2. Create a JAXP document builder

3. Invoke the parser to create a Document representing an XML

document

4. Normalize the tree

5. Obtain the root node of the tree

6. Examine and modify properties of the node

 
3).

Steps for SAX Parsing

1. Tell the system which parser you want to use

2. Create a parser instance

3. Create a content handler to respond to parsing events

4. Invoke the parser with the designated content handler and

document

posted @ 2006-11-27 05:26 Sun River| 编辑 收藏

1). What is a document type definition and what is its purpose in XML? Explain the difference between a well-formed and a valid XML document.
Answer: The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements. A DTD can be declared inline in your XML document, or as an external reference. Two definitions:
   -).A well-formed file is one that obeys the general XML rules for tags: tags must be properly nested, opening and closing tags must be balanced, and empty tags must end with '/>'.
   -). A valid file is not only well-formed, but it must also conform to a publicly available DTD that specifies which tags it uses, what attributes those tags can contain, and which tags can occur inside which other tags, among other properties.

2). External DTD:
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">

3). Minimal but Complete XSLT  Stylesheet

<?xml version="1.0"?>

   < xsl:stylesheet version="1.0"

            xmlns:xsl="http://www.w3.org/1999/ XSL/Transform">

< /xsl:stylesheet >

4). Using XSLT, how would you extract a specfic attribute from an element in an XML document?
Ans: Extract attributes from XML data
   <xsl:template match="element-name">
     Attribute Value:
        <xsl:value-of select="@attribute" />
         <xsl:apply-templates/>
    </xsl:template>

5). Templates--Controls which output is created from which input

--" xsl:template element form

--" match attribute contains an Xpath expression (Xpath expression identifies input node set it matches)

--" For each node in the node set, the

template contents (things between xsl:template tags) are instantiated and inserted into the output tree.

6). Attributes

In the DTD, XML element attributes are declared with an ATTLIST declaration. An attribute declaration has the following syntax:

<!ATTLIST element-name attribute-name attribute-type default-value>

As you can see from the syntax above, the ATTLIST declaration defines the element which can have the attribute, the name of the attribute, the type of the attribute, and the default attribute value.

The attribute-type can have the following values:

ValueExplanation
CDATA
The value is character data
(eval|eval|..)
The value must be an enumerated value
ID
The value is an unique id 
IDREF
The value is the id of another element
IDREFS
The value is a list of other ids
NMTOKEN
The value is a valid XML name
NMTOKENS
The value is a list of valid XML names
ENTITY
The value is an entity 
ENTITIES
The value is a list of entities
NOTATION
The value is a name of a notation
xml:
The value is predefined

The attribute-default-value can have the following values:

ValueExplanation
#DEFAULT value
The attribute has a default value
#REQUIRED
The attribute value must be included in the element
#IMPLIED
The attribute does not have to be included
#FIXED value
The attribute value is fixed


Attribute declaration example

DTD example:
<!ELEMENT square EMPTY>
  <!ATTLIST square width CDATA "0">

XML example:
<square width="100"></square>

In the above example the element square is defined to be an empty element with the attributes width of  type CDATA. The width attribute has a default value of 0. 

Default attribute value

Syntax:
<!ATTLIST element-name attribute-name CDATA "default-value">

DTD example:
<!ATTLIST payment type CDATA "check">

XML example:
<payment type="check">

Specifying a default value for an attribute, assures that the attribute will get a value even if the author of the XML document didn't include it.

Implied attribute

Syntax:
<!ATTLIST element-name attribute-name attribute-type #IMPLIED>
DTD example:
<!ATTLIST contact fax CDATA #IMPLIED>

XML example:
<contact fax="555-667788">

Use an implied attribute if you don't want to force the author to include an attribute and you don't have an option for a default value either. 

Required attribute

Syntax:
<!ATTLIST element-name attribute_name attribute-type #REQUIRED>
DTD example:
<!ATTLIST person number CDATA #REQUIRED>

XML example:
<person number="5677">

Use a required attribute if you don't have an option for a default value, but still want to force the attribute to be present.

Fixed attribute value

Syntax:
<!ATTLIST element-name attribute-name attribute-type #FIXED "value">
DTD example:
<!ATTLIST sender company CDATA #FIXED "Microsoft">


XML example:
<sender company="Microsoft">

Use a fixed attribute value when you want an attribute to have a fixed value without allowing the author to change it. If an author includes another value, the XML parser will return an error.

Enumerated attribute values

Syntax:
<!ATTLIST element-name attribute-name (eval|eval|..) default-value>
DTD example:
<!ATTLIST payment type (check|cash) "cash">

XML example:
<payment type="check">
or
<payment type="cash">
posted @ 2006-11-27 00:48 Sun River| 编辑 收藏
1. Explain what is EJB?
2. what is manditory parts of EJB?
3. What is 4 transaction isolation levels of JDBC?
4. Explain dirty read, nonrepeatable read and phantom read?
5. Give the steps using websphere to develop the ejb application (code change, ejb deploy, servlet etc.)
6. Give the architecture of a SOA application and explain every parts
7. What is JSP model 1 and model 2?
8. Explain the connection pooling
posted @ 2006-11-22 09:52 Sun River| 编辑 收藏
DD
The general procedure for deploying J2EE-based EJB applications assumes the following general steps:
  1. Set J2EE server environment variables—Environment variables must be set for running a J2EE server environment and vary per vendor implementation and operating-system platform.

  2. Configure J2EE server properties—Configuration properties for most J2EE server implementations can be set to suit your particular network and operating environment.

  3. Compile J2EE EJB application code—All J2EE EJB implementation, home, remote, and dependent utility code must be compiled using a standard Java compiler.

  4. Create a J2EE EJB application deployment descriptor—An XML-based deployment descriptor is created according to the EJB application DTD. Some vendor products can create this file for you from a GUI-based configuration tool.

  5. Create vendor-specific deployment descriptors—Because no standard means exists to bind J2EE standard EJB reference names to a J2EE server's JNDI-based naming service, a vendor-specific deployment descriptor mechanism is required to perform this mapping. This deployment descriptor must map EJB reference names used by J2EE components to the actual JNDI names associated with EJB home interfaces. Other vendor-specific properties may also be set for customizing both session and entity beans. Vendors may provide a GUI-based means to configure these files.

  6. Package J2EE EJB application code—The EJB deployment descriptors, all compiled J2EE EJB implementation classes, all compiled J2EE EJB implementation interfaces, and all other compiled classes dependent on your EJBs need to be packaged into an EJB JAR file with a .jar extension. J2EE-based products might supply command-line or GUI-based utilities for this purpose.

  7. Start the J2EE server—The J2EE-compliant server must generally be started at this stage. The exact mechanism for starting a server is often vendor-dependent but can be as simple as invoking a single startup command from the command line.

  8. Create a J2EE application deployment descriptor—A J2EE application deployment descriptor must be created to collect one or more Web, EJB, and application client modules into a cohesive J2EE application. Many products will create this file for you automatically or via a GUI-based configuration tool.

  9. Package J2EE application code—The application and JNDI mapping deployment descriptor, Web applications, EJB applications, and application clients need to be packaged into an enterprise archive (EAR) file with an extension of .ear. Many products also create this archive for you automatically or via GUI-based development tools.

  10. Deploy the J2EE enterprise application code—Finally, the integrated J2EE application is deployed to the J2EE server environment for access by enterprise application clients. This step is also often automated via GUI tools. http://e-docs.bea.com/wls/docs61/webapp/webappdeployment.html

posted @ 2006-11-16 15:01 Sun River| 编辑 收藏

Spring 中的 AOP 简单使用

   

    AOP 作为 Spring 这个轻量级的容器中很重要的一部分,得到越来越多的关注, Spring Transaction 就是用 AOP 来管理的,今天就通过简单的例子来看看 Spring 中的 AOP 的基本使用方法。

 

  首先确定将要 Proxy 的目标,在 Spring 中默认采用 JDK 中的 dynamic proxy ,它只能够实现接口的代理,如果想对类进行代理的话,需要采用 CGLIB proxy 。显然,选择 编程到接口 是更明智的做法。

 

下面是将要代理的接口:

public interface FooInterface {
    public void printFoo();
    public void dummyFoo();
}

以及其一个简单的实现:
public class FooImpl implements FooInterface {
    public void printFoo() {
        System.out.println("In FooImpl.printFoo");

    }

    public void dummyFoo() {
        System.out.println("In FooImpl.dummyFoo");
    }
}
 
接下来创建一个 Advice ,在 Spring 中支持 Around,Before,After returning Throws 四种 Advice ,这里就以简单的 Before Advice 举例:
 
public class PrintBeforeAdvice implements MethodBeforeAdvice {
    public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
        System.out.println("In PrintBeforeAdvice");
    }

}
 
有了自己的 business interface advice ,剩下的就是如何去装配它们了,首先利用 ProxyFactory 以编程方式实现,如下:
 

public class AopTestMain {
    public static void main(String[] args) {
        FooImpl fooImpl = new FooImpl();
        PrintBeforeAdvice myAdvice = new PrintBeforeAdvice();
     
        ProxyFactory factory = new ProxyFactory(fooImpl);
        factory.addBeforeAdvice(myAdvice);
        FooInterface myInterface = (FooInterface)factory.getProxy();

        myInterface.printFoo();
        myInterface.dummyFoo();
    }

}
 
 
现在执行程序,神奇的结果就出现了:
 
  In PrintBeforeAdvice
  In FooImpl.printFoo
  In PrintBeforeAdvice
  In FooImpl.dummyFoo
 
  
虽然这样能体会到 Spring AOP 的用法,但这决不是值得推荐的方法,既然使用了 Spring ,在 ApplicationContext 中装配所需要 bean 才是最佳策略,实现上面的功能只需要写个简单的 applicationContext 就可以了,如下:
 
  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "
http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    <description>The aop application context</description>
    <bean id="fooTarget" class="FooImpl"/>
    <bean id="myAdvice" class="PrintBeforeAdvice"/>
    <bean id="foo" class="org.springframework.aop.framework.ProxyFactoryBean">
     <property name="proxyInterfaces">
       <value>FooInterface</value>
     </property>
     <property name="target">
       <ref local="fooTarget"/>
     </property>
     <property name="interceptorNames">
       <list>
         <value>myAdvice</value>
       </list>
     </property>
    </bean>

</beans>

 

   当然, main 中的代码也要进行相应的修改:
    
public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new 
             ClassPathXmlApplicationContext("applicationContext.xml");
    FooInterface foo = (FooInterface)context.getBean("foo");
    foo.printFoo();
    foo.dummyFoo();
}
 
  
现在运行一下,结果将和上面的运行结果完全一样,这样是不是更优雅?当需要更改实现时,只需要修改配置文件就可以了,程序中的代码不需任何改动。
 
  
但是,这时候会发现被 proxy object 中的所有方法调用时都将运行 advice 中的 before ,这显然不能满足绝大多数情况下的需要,此时,只 需借用 Advisor 就可以了,当然要在 Advisor 中利用 pattern 设置好哪些方法需要 advice ,更改 applicationContext 如下:
 
  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "
http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    <description>The springeva application context</description>
    <bean id="fooTarget" class="FooImpl"/>
    <bean id="printBeforeAdvice" class="PrintBeforeAdvice"/>
    <bean id="myAdvisor"
          class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
      <property name="advice">
        <ref local="printBeforeAdvice"/>
      </property>
      <property name="pattern">
        <value>.*print.*</value>
      </property>
    </bean>
    <bean id="foo" class="org.springframework.aop.framework.ProxyFactoryBean">
      <property name="proxyInterfaces">
        <value>FooInterface</value>
      </property>
      <property name="target">
        <ref local="fooTarget"/>
      </property>
      <property name="interceptorNames">
        <list>
          <value>myAdvisor</value>
        </list>
      </property>
    </bean>
</beans>

 

    主程序不需进行任何修改,运行结果已经变样了

   In PrintBeforeAdvice
    In FooImpl.printFoo
    In FooImpl.dummyFoo
 
  
至此,应该已经理解了 Spring AOP 的使用方法,当然 Spring AOP 最重要的应用是 Transaction Manager ,举个这方面的 applicationContext 例子看看:
 
  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "spring-beans.dtd">

<beans>
    <bean id="propertyConfigurer"   
         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location">
        <value>/WEB-INF/jdbc.properties</value>
      </property>
    </bean>
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName">
        <value>${jdbc.driverClassName}</value>
      </property>
      <property name="url">
        <value>${jdbc.url}</value>
      </property>
      <property name="username">
        <value>${jdbc.username}</value>
      </property>
      <property name="password">
        <value>${jdbc.password}</value>
      </property>
    </bean>
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
      <property name="dataSource">
        <ref local="dataSource"/>
      </property>
      <property name="mappingResources">
        <value>smartmenu.hbm.xml</value>
      </property>
      <property name="hibernateProperties">
        <props>
          <prop key="hibernate.dialect">${hibernate.dialect}</prop>
        </props>
      </property>
    </bean>
 
    <bean id="transactionManager"       
          class="org.springframework.orm.hibernate.HibernateTransactionManager">
      <property name="sessionFactory">
        <ref local="sessionFactory"/>
      </property>
    </bean>
    <bean id="smartmenuTarget" class="SmartMenuHibernate">
      <property name="sessionFactory">
        <ref local="sessionFactory"/>
      </property>
    </bean>
    <bean id="smartMenu"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
      <property name="transactionManager">
        <ref local="transactionManager"/>
      </property>
      <property name="target">
        <ref local="smartmenuTarget"/>
      </property>
      <property name="transactionAttributes">
        <props>
          <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
          <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
        </props>
      </property>
    </bean>
  </beans>
 
 
要想彻底理解 Spring AOP ,最好还是多看看源码,开源就是好啊!

 

 

 

posted @ 2006-11-16 13:29 Sun River| 编辑 收藏

J2EE 五层逻辑模型和常见 Framework

 

 

                      ————————————————

                      |                          客户端层                     |        用户交互, UI 实现

                      | Browser,WirelessDevice,WebService |    Http, Soap 协议 (SOP 体系 )

                      ————————————————

 

                      ————————————————

                      |                             表现层                       |   集中登录,会话管理

                      | Struts,Jsf,Webwork,Tapstry, Velocity | 内容创建,格式,传送

                      ————————————————

 

                       ————————————————

                       |                       业务服务层                     |   业务逻辑 , 事务 , 数据 , 服务

                       | SessionEJB Spring Jdoframework) | SessionEjb POJO Service

                        ————————————————

 

                       ————————————————

                       |                            集中层                        |  资源适配器,遗留 / 外部系统  

                       |Jms,Jdbc,Connnector,External Service  |        规则引擎,工作流

                       ————————————————

                       ( 持久化 EntityBean,Hibernate,iBatis,Jdo,Dao,TopLink etc.)      

 

                        ————————————————

                        |                           资源层                             | 资源,数据库,外部服务

                        | DataBase,Resource,External Service   | ( 大型主机, B2B 集中系统 )

                        ————————————————

 

当然一个常见典型的 J2EE 系统可能是这样的

 

客户端 —— 表现层 —— 业务层  —— 持久层 —— 数据库   

FireFox + Velocity + Struts + Spring + Hibernate + MySql + Tomcat + Eclipse

我比较习惯用开源产品。强烈支持开源 !! *.*

                                                           

作为一个程序员,常常打交道的是中间层 ( 表现层,业务层,集成层 )

每个层常用的技术简单的介绍如下:


表现层 (Present Tier)


Intercepting Filter ——
用于对请求的预处理和后处理

 

    拦截过滤器拦截输入的请求和输出的响应,并加入了一个过滤器。 Filter 可以通过配置加入和取消 ( 象在 web.xml 中加入 ServletFilter) ,这样多个过滤器还可以不冲突地组合使用。当预处理以及 / 或者 (filter 虽然后 response 参数,但有时候 filter 不做处理 ) 后处理完成后,这组过滤器种的最后一个把控制器交给原来的目标对象。对于 request 来说,这个目标对象通常是前端控制器,但也可能是一个视图。在 Struts 中, Action 的执行方法中参数由 request, response, actionMapping,actionForm 等等组成。而在 Webwork 中, Action 不用去依赖于任何 Web 容器,不用和那些 JavaServlet 复杂的请求( Request )、响应 (Response) 关联在一起。对请求( Request )的参数 (Param) ,可以使用拦截器框架自动调用一些 get() set() 方法设置到对应的 Action 的字段中。所以 Action excute() 方法没有任何参数,也不存在 FormBean 。正是这种拦截器,使得 Action 变得非常简单, Action 不用继承 servlet ,不依赖 servlet 容器,实现了请求响应与 Action 之间的解耦,而且可以很方便的在 action 中不依赖 web 容器进行单元测试。

 

Front Controller —— 集中控制请求处理

 

    前端控制器是一个容器,用来装载表现层的共同处理逻辑 ( 如果不采用这个控制器,逻辑代码就会错误的放在视图里 ) 。控制器负责处理请求,进行内容的获取,安全性,视图管理,导航等操作,并委派一个分配器组件分派视图。

 

Application Controller —— 实现操作和视图管理的集中化,模块化

 

    应用控制器集中了控制,数据获取,视图和命令处理的调用。前端控制器为输入的请求提供了一个集中的访问点和控制器,而应用控制器则负责找出并调用命令,并且还要找出并分派视图。比如 Struts 中的 ActionServlet,Webwork 种的 ServletDispatcher 等。

posted @ 2006-11-16 13:18 Sun River| 编辑 收藏

1). Steps for Building a JMS Sender Application

1.Get ConnectionFactory and Destination object (Topic or Queue) through JNDI         

// Get JNDI InitialContext object

Context jndiContext = new InitialContext();

// Locate ConnectionFactory object via JNDI

TopicConnectionFactory factory =
      (TopicConnectionFactory) jndiContext.lookup("MyTopicConnectionFactory");

// Locate Destination object (Topic or Queue) through JNDI

Topic weatherTopic = (Topic) jndiContext.lookup("WeatherData");

2.Create a Connection                              
                                 
                    
// Create a Connection object from ConnectionFactory object
                                 TopicConnection topicConnection = factory.createTopicConnection();

3.Create a Session to send/receive messages

         // Create a Session from Connection object.

            // 1st parameter controls transaction

            // 2nd parameter specifies acknowledgment type

         TopicSession session =

            topicConnection.createTopicSession (false, Session.CLIENT_ACKNOWLEDGE);

4.Create a MessageProducer (TopicPublisher or QueueSender)

                                          // Create MessageProducer from Session object
                              // TopicPublisher for Pub/Sub
                              // QueueSender for Point-to-Point
                              TopicPublisher publisher =session.createPublisher(weatherTopic);

5.Start Connection
                                                // Until Connection gets started, message flow
                                    // is inhibited: Connection must be started before
                                    // messages will be transmitted.
                                    topicConnection.start();

6.Send (publish) messages
                                    // Create a Message
                                     TextMessage message =session.createMessage();
                                    message.setText("text:35 degrees");
                                    // Publish the message
                                    publisher.publish(message);

7.Close Session and Connection

2). Steps for Building a JMS Receiver Application (non-blocking mode)

1.Get ConnectionFactory and Destination object

(Topic or Queue) through JNDI

2.Create a Connection

3.Create a Session to send/receive messages

4.Create a MessageConsumer (TopicSubscriber or QueueReceiver)

            // Create Subscriber from Session object
            TopicSubscriber subscriber =session.createSubscriber(weatherTopic);

5.
Register MessageListener for non-blocking mode
         WeatherListener myListener= new WeatherListener();
         // Register MessageListener with TopicSubscriber object
         subscriber.setMessageListener(myListener);

6.Start Connection

7.Close Session and Connection

3). Steps for Building a JMS Receiver Application for blocking mode)

1
.Get ConnectionFactory and Destination object (Topic or Queue) through JNDI

2.Create a Connection

3.Create a Session to send/receive messages

4.

Create a MessageConsumer

5.Start Connection

6.

Receive message

7.Close Session and Connection

posted @ 2006-10-30 01:11 Sun River| 编辑 收藏
     摘要:   阅读全文
posted @ 2006-10-28 15:15 Sun River| 编辑 收藏

pageContext - the PageContext object. Provides an API to access various objects including:

    • context - the context for the JSP page's servlet and any Web components contained in the same application.

    • session - the session object for the client.

    • request - the request triggering the execution of the JSP page.

  • pageScope - a java.util.Map that maps page-scoped attribute names to their values.

  • requestScope - a java.util.Map that maps request-scoped attribute names to their values.

  • sessionScope - a java.util.Map that maps session-scoped attribute names to their values.

  • applicationScope - a java.util.Map that maps application-scoped attribute names to their values.

  • param - a java.util.Map that maps parameter names to a single String parameter value (obtained by calling ServletRequest.getParameter(String name)).

  • paramValues - a java.util.Map that maps parameter names to a String[] of all values for that parameter (obtained by calling ServletRequest.getParameterValues(String name)).

  • header - a java.util.Map that maps header names to a single String header value (obtained by calling HttpServletRequest.getHeader(String name)).

  • headerValues - a java.util.Map that maps header names to a String[] of all values for that header.

  • cookie - a java.util.Map that maps cookie names to a single Cookie object. Cookies are retrieved according to the semantics of HttpServletRequest.getCookies(). If the same name is shared by multiple cookies, an implementation must use the FIRST one encountered in the array of Cookie objects returned by the getCookies() method. However, users of the cookie implicit object must be aware that the ordering of cookies is currently unspecified in the servlet specification.

  • initParam - a java.util.Map that maps context initialization parameter names to their String parameter value (obtained by calling ServletContext.getInitParameter(String name)).

Examples:

The request's URI (obtained from HttpServletRequest):

${pageContext.request.requestURI}
					

The value of the numberOfItems property of the session-scoped attribute named cart:

${sessionScope.cart.numberOfItems}
					

The context path:

${pageContext.request.contextPath}
					

The session-scoped attribute named 'profile' (null if not found):

${sessionScope.profile} 
					

The String value of the productId parameter, or null if not found:

${param.productId} 
					

The value of the productId request parameter:

${param["productId"]}
					

The String[] containing all values of the productId parameter, or null if not found:

${paramValues.productId} 
					

A collection's members can be accessed using square brackets as shown by retrieval of the userName parameter from the param object. Members of an array or List can be accessed if the value in square brackets can be coerced to an int.

<html>
	<head><title>Customer Profile for ${param["userName"]}</title></head>
	<body>
		...
	</body>
</html>

					
Maps can be accessed using the dot operator OR square brackets. For example, ${param.userName} is EQUIVALENT to ${param["userName"]}.

The host HTTP attribute:

${header["host"]}
					

Here is an example of accessing a page-scoped object that is called pageColor:

<body bgcolor="${pageScope.pageColor}"> 

					
it is equivalent to:
<body bgcolor="${pageScope['pageColor']}">

					

posted @ 2006-10-16 01:19 Sun River| 编辑 收藏
Web Application Login Authentication
None
Select when no authentication is desired.
HTTP Basic Authentication (RFC 2617)
Select to specify browser authentication.
Realm
Enter the realm string. The web server then authenticates the user in the specified realm.
HTTP Digest Authentication (RFC 2617)
Select to specify digest authentication.
Form-based Authentication
Select to specify user-written HTML form for authentication.
Login Page
Enter an HTML page, JSP page, or HTTP servlet that is used to authenticate the user. The page must return an HTML page containing a FORM that conforms to a specific naming convention. This is done through the <form-login-config> tag in the <login-config> subelement of the generated web.xml file.
Error Page
Enter an HTML page that is sent to a user when authentication fails. This page contains information about the connection failure.
HTTPS Client Authentication (Public Key Certificate)
Select to specify client-side authentication.

Please refer to http://e-docs.bea.com/wls/docs61/webapp/web_xml.html
posted @ 2006-10-10 01:55 Sun River| 编辑 收藏
Identify which attribute scopes are thread-safe:
  1. Local variables Yes, thread-safe
  2. Instance variables
  3. Not thread-safe
    Since a single servlet instance may be handling multiple service requests at any given time.
  4. Class variables
  5. Not thread-safe
    Since multiple servlets and /or service requests may try to access a class variable concurrently.
  6. Request attributes
  7. Yes, thread-safe
    Since the request object is a local variable
  8. Session attributes
  9. Not thread-safe
    Since sessions are scoped at the web application level, hence the same session object can be accessed concurrently by multiple servlets and their service requests
  10. Context attributes
  11. Not thread-safe
    Since the same context object can be accessed concurrently by multiple servlets and their service requests
posted @ 2006-10-08 12:41 Sun River| 编辑 收藏
 
  1. Page translation
  2. JSP page compilation

  3. Load class

  4. Create instance

  5. Call jspInit

  6. Call _jspService

  7. Call jspDestroy

posted @ 2006-10-08 12:21 Sun River| 编辑 收藏

Question 1:

You need to create a database connection in your application after reading the username, password, and database server URL from the deployment descriptor. Which will be the best place to do this?

Choices:

  • A. Servlet constructor
  • B. init() method
  • C. service() method
  • D. doGet() method
  • E. doPost() method

Correct choice:

  • B

Explanation:

The init() method is invoked once and only once by the container, so the creation of the database connection will be done only once, which is appropriate. The service() , doGet() , and doPost() methods might be called many times by the container.

The username, password, and URL are to be read from the deployment descriptor. These initialization parameters are contained in the ServletConfig object, which is passed to the init() method. That is why we need to use the init() method instead of the constructor for this purpose, even though the constructor is also called only once.

Question 2:

A user can select multiple locations from a list box on an HTML form. Which of the following methods can be used to retrieve all the selected locations?

Choices:

  • A. getParameter()
  • B. getParameters()
  • C. getParameterValues()
  • D. getParamValues()
  • E. None of the above

Correct choice:

  • C

Explanation:

The getParameterValues(String paraName) method of the ServletRequest interface returns all the values associated with a parameter. It returns an array of Strings containing the values. The getParameter() method returns just one of the values associated with the given parameter, so choice A is incorrect. There are no methods named getParameters() or getParamValues() , so choices B and D are incorrect.

posted @ 2006-10-08 05:01 Sun River| 编辑 收藏
Question 1:

Consider the following servlet code:

public class MyServlet extends HttpServlet
{
final static int i=0;
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
private HttpSession session=req.getSession();
private ServletContext ctx=getServletContext();
synchronized(ctx)
{
Object obj=ctx.getAttribute(); // code to alter obj
}
}
}

Which of the following variables in the above code are thread safe?

Choices:

  • A. i
  • B. session
  • C. ctx
  • D. req
  • E. obj
  • F. res

Correct choices:

  • A , C , D , and F

Explanation:

The static variable i is thread safe because it is final (cannot be modified), or else it would not have been safe. Request and response objects are scoped only for the lifetime of the request, so they are also thread safe. Session and ServletContext objects can be accessed from multiple threads while processing multiple requests, so they are not thread safe. However, in this case, the ServletContext object is synchronized, so it can be accessed only by one thread at a time. obj is not thread safe because even though the ServletContext object is synchronized, its attributes are not. They need to be synchronized separately. Hence choices B and E are incorrect and choices A, C, D and F are correct.

Question 2:

Which of the following statements are true?

Choices:

  • A. Multiple instances may be created on a servlet implementing SingleThreadModel
  • B. No more than one instance is created for a servlet implementing SingleThreadModel
  • C. Even static variables in a SingleThreadModel servlet are thread safe
  • D. If no threading model is implemented, by default a servlet is executed in a multi-threaded model

Correct choices:

  • A and D

Explanation:

When SingleThreadModel is implemented, the servlet container ensures that only one thread is executing the servlet's method at a time. So what will happen for multiple requests? In that case, the container may instantiate multiple instances of the servlet to handle multiple requests, so option A is correct and B is incorrect.

If the SingleThreadModel interface is not implemented, a servlet uses the multi-threaded model (that is, multiple threads can access the methods of the servlet). Static variables can be accessed through multiple instances of the same class, so they are not always thread safe. Hence choices B and C are incorrect and choices A and D are correct.

posted @ 2006-10-08 04:29 Sun River| 编辑 收藏

Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:

Questions:

- Entry level:
  - Is AJAX a programming language?
  - What is AJAX?
  - How new is AJAX?
  - Why can/should AJAX be used?
 A: AJAX is best suited for small (hopefully unobtrusive) updates to the current
    web page, based on information that is not available until it has been provided
    by the end user.
  - When should AJAX NOT be used?
  A: It would not be appropriate to use AJAX when the "answer/result" can be determinded
    by the client.  Generally, the purpose of AJAX is to submit a short request to the server,
    and process the response in such a way as to add value to the currently displayed page.
    It would also not be appropriate to use AJAX when the magnitude of the response is such
    that it would be easier, and more clear to redisplay the page.

  - What objects are used by AJAX programs?

- Intermediate-level?
  - Describe the  formats and protocols used/specified by AJAX
  - Describe some things that can't be done with AJAX
 A: Sending a request to a server outside of the domain from which  the web page originated.
  - How should AJAX objects be created?
  - For what error conditions should programs check?
  - Are Finite State Machines (FSM's) appropriate for use with AJAX?
  - Identify and describe the state transitions that can/should occur within a transaction
A: - Reset : When the XmlHttpRequest object is created, no connection yet exists between the clent, and the server.
      Open  : When the xmlHttp.open() is issued, the request is being prepared for transmission to the server
      Sent   : When the xmlHttp.send() is issued, the request is transmitted to the server application
      Rcvd   : When the xmlHttp callback routine is called, the readyState and status fields of the object define why the routine was called

Q. How do you know that an AJAX request has completed?
A. The XHR.readyState is 4 and the XHR.status is 200 (or zero if the request is to a local file). The callback function is called four times - first with status=1, then 2,3, and finally 4.
Q. How does XML processing differ on the different browsers?
A. It's an ActiveX object on IE, but is native on the other browsers
Q: What values exists for the XmlHttpRequest.readyState field, and what do they mean?
A: readyState values:
    0 = uninitialized
    1 = loading
    2 = loaded
    3 = interactive
    4 = complete  


Other areas to check up on:
   How do you process the returned XML data?
   If it's a Java/J2EE place: what about AJAX and JSF?
   How to populate the XML response on the server?
   How to terminate an active request?

posted @ 2006-10-05 10:09 Sun River| 编辑 收藏