Wednesday, April 02, 2008

Sample SCBCD 5.0 Questions

To get all 300 SCBCD 5.0 Questions, click here.

1) Consider the following Stateless Session Bean,


@Stateless
public class MyTestBean implements MyTestLocal
{

public void cleanResources( )
{
}

}

You want to annotate the method cleanResources() with @PreDestroy Annotation using XML Deployment Descriptor. Which of the following will correctly do that? 1.



MyTestBean

cleanResources



2.



MyTestBean

cleanResources



3.




MyTestBean
cleanResources


4. None of the above.

2) A Stateful Session Bean by name 'ResourceAllocatorBean' has a business method by name 'allocate' along with a number of methods. You have developed an interceptor class 'net.javabeat.ejb3.LoggingInterceptor' which you want to apply to the method 'allocate' of the 'ResourceAllocatorBean'. Which of the following is the correct way to achieve that?
1.





ResourceAllocatorBean
net.javabeat.ejb3.LoggingInterceptor
allocate



2.





ResourceAllocatorBean
net.javabeat.ejb3.LoggingInterceptor
allocate



3.





ResourceAllocatorBean
net.javabeat.ejb3.LoggingInterceptor



4. None of the above.

3) Given the following session bean,


@Stateful
public class CounterBean implements CounterRemote
{
// Line 'A'
public int count()
{
// Line 'B'.
userTransaction.begin();
// Do something here
userTransaction.commit();
}
}

Which of the following code snippets can be inserted into the lines marked by identifiers A and B so that the above bean code will compile without any compilation errors? 1.



@Resource
private SessionContext sessionContext; // Line 'A'
Transaction userTransaction = sessionContext.getTransaction(); // Line 'B'

2.



@Resource
private SessionContext sessionContext; // Line 'A'
UserTransaction userTransaction = sessionContext.getUserTransaction(); // Line 'B'

3.



@Resource
private ApplicationTransaction transaction; // Line 'A'
UserTransaction userTransaction = transaction.getUserTransaction(); // Line 'B'

4. None of the above.

4) Which of the following is not a life-cycle method for a Stateful Session Bean?
1. Post Construction
2. Pre Destruction
3. Post Activation
4. Pre Construction
5. Pre Passivation
6. All the Above

5) Imagine that you have a business interface by name 'Template'. Which of the following ways can be used by the Client Application to acquire a reference to the business interface (assuming that this interface is bound in the JNDI Context)?
1.



@Resource
SessionContext context;
รข€¦
Template template = (Template)context.lookup("template");

2.


@EJB
Template template;

3.



Template template = null;
InitialContext context = new InitialContext();
template = (Template)Context.lookup("java:comp/ejb/template");

4. All the above.

6) Which of the following code snippets correctly declares a Message-Driven Bean by name 'TestMessageDrivenBean'?
1.



public class TestMessageDrivenBean implements javax.jms.MessageListener
{
public void onMessage(Message message)
{
// Business logic here.
}
}

2.



public class TestMessageDrivenBean implements javax.ejb.MessageListener
{
public void onMessage(Message message)
{
// Business logic here.
}
}

3.


public class TestMessageDrivenBean implements javax.ejb.MessageListener
{
public void ejbRemove()
{
}


public void setMessageDrivenContext(MessageDrivenContext context)
{
}
}

4. All the above.

7) Imagine that the Application you develop periodically sends some events to some other parts of the Application at some defined intervals. Which of the following enterprise bean(s) can be used in this scenario?
1. Entity Bean
2. Stateful Session Bean
3. Stateless Session Bean
4. Message Driven Bean
5. Timer Bean
6. None of the above.

8) Assume that your Application has created as instance of EntityManager with the following piece of code,
EntityManagerFactory factory = Persistence.createEntityManagerFactory("...");
EntityManager manager = factory.createEntityManager();
Which of the following methods can be used to check whether the handle of the EntityManager instance is valid?
1. EntityManager.isValid()
2. EntityManager.isHandleValid()
3. EntityManager.isOpen()
4. None of the above.

9) Which of the following way is used for creating an extended persistence context?
1.



EntityManager entityManager = ...;
PersistenceContext context = entityManager.createExtendedPersistenceContext();

2.



EntityManagerFactory factoy = Persistence.createEntityManagerFactory();
EntityManager entityManager = factory.createEntityManager();
PersistenceContext context =
entityManager.createPersistenceContext(PersistenceContextType.EXTENDED);

3.



@PersistenceContext(unitName = "...", type=PersistenceContextType.EXTENDED)
private EntityManager entityManager;

4. None of the above.

10) Which of the following criteria is needed to make a plain java class by name 'Employer' as an entity and that can also be transferred and accessible by a remote application?
1.



@Entity
public class Employer
{
}

2.



public class Employer extends javax.persistence.Entity
{
}

3.



@Entity
public class Employer implements Serializable
{
}

4. All the above.
Answers

1) b.
Option b is correct. The element 'lifecycle-callback-method' must be used specifying the name of the method and this element should be included within the element 'pre-destroy'.

2)4) a.
Option a is correct. This option correctly defines the elements for associating an enterprise bean and the interceptor class along with the method that should be intercepted.

3) b.
Option b is correct. The business method 'count' is trying to explicitly start a transaction, then do some business logic and finally commit the transaction. Here, since the transaction is controlled at the Application level, this transaction should be of type 'UserTransaction'. A UserTransaction object can be obtained a reference by calling the method getUserTransaction() on the Session Context object which is already initialized by the Container by applying the Annotation '@Resource'.

4) d.
Option d is correct. The life-cycle method Pre Construction is not valid for a Stateful Session Bean (as well as for any Enterprise Bean).

5) d.
All the options are correct. Options a and b using the dependency injection mechanism for initializing the business interface (from EJB 3.0). Option c uses the older style (EJB 2.1) for acquiring the reference to the business interface.

6) a.
Option a is correct. It is mandatory for a Message-Driven Bean to implement the MessageListener interface thereby overriding the onMessage() method.

7) c and d.
Options c and d are correct. It should be noted that only Stateless Session Beans and Message Driven Beans can make use of the Timer Service provided by the Container.

8) c.
Option c is correct. The method isOpen() will return true if the handle of the EntityManager is valid and it is not closed.

9) c.
Option c is correct. There is no such interface called PersistenceContext defined by the JPA Specification. A Persistence context is a virtual object that comes into existence whenever an EntityManager instance is created.

10) c.
Option c is correct. The class must be annotated with @Entity and must implement the Serializable interface (or the Externalizable interface).

To get all 300 SCBCD 5.0 Questions, click here.

List of Certification Exams Released by Javabeat

350 SCJP 1.5 Mock Exam Questions

400 SCJP 1.6 Mock Exam Questions

300 SCWCD 5.0 Mock Exam Questions

300 SCWCD 1.4 Mock Exam Questions

300 SCBCD 5.0 Mock Exam Questions

SCBCD 5.0 Mock Exam Questions


JavaBeat has released 300 mock exam questions for SCBCD 5.0 exam. The cost of this kit is JUST $12 or 300 INR. You can buy these mock exams here.


Thursday, March 01, 2007

Sun Updates Mobile Java Platform

Sun Microsystems announced the availability of the Mobile Services Architecture (MSA), the next generation Java platform for mobile phones and other handheld devices. MSA is available now for mobile devices and Sun's NetBeans development platform.

Sun developed the MSA along with 13 other companies, including operators, OEMs and software vendors. The MSA is the next step in the evolution of Sun's mobile API set, Java Technology for the Wireless Industry (JTWI).

"What we did with JTWI was make a compilation of a number of specs together to create a standard platform developer could count on being in handsets. MSA is the next generation. It supersedes JTWI with much more features and functionality than what we had," John Muhlner, group manager for Java ME product marketing at Sun (Quote), told internetnews.com at an event to announce the new platform.


The new APIs (define) in MSA allow for the creation of mobile applications and services that use 3D graphics, personal information management, Bluetooth, animation, Web services, location services and payment services.

MSA also adds a Wireless Client optimized to support multiple, concurrent wireless applications, the Device Test Suite 2.0 for testing the quality and compliance of APIs to the specs, and the NetBeans Mobility Pack 5.5 for building applications in the NetBeans environment.


Finally, there is the Java Wireless Toolkit 2.5 for Connected Limited Device Configuration (CLDC), a collection of tools for building applications and a wireless platform emulator for testing the applications.

Java ME was severely fragmented for the longest time, and MSA will bring it some unity, said Muhlner. "These platform specs take the specific technologies and clarify or define certain options within the spec. It reduces fragmentation and makes for a more consistent application environment."


Jeff Griffin, MSA Expert Group representative for cell phone maker Sony Ericsson, agreed. "MSA is critical for us in the next phase of making Java more usable in mobile phones. The technology continues to grow, new JSRs are added to the mix. This means imp fragmentation. What umbrella JSRs like this are good is setting a baseline and saying everyone needs to start here," he said.

Thursday, January 18, 2007

SCJP 5.0 Mock Exams - Generics


SCJP 5.0 Mock Exams - Generics


  1. what is the result compiling and running the following piece of code?

import java.util.*;

class Test {

public static void main(String [] args) {

Set vals = new TreeSet<String>();

vals.add("one");

vals.add(1);

vals.add("two");

System.out.println(vals);

}

}


Options :

  1. Does not Compile

  2. Compiles with warning and prints output [one, 1, two]

  3. Compiles without warning and prints output [one, 1, two]

  4. Compiles with warning and throws exception at runtime

  5. Compiles without warning and throws exception at runtime


Answer :

D are correct Answers.

Compiles with warning due to un-safe assignment List vals = new ArrayList<String>();

Since TreeSet<String> is used, it will try to sort by natural order. Due to the presence of Integer (vals.add(1);) in the collection, it will throw ClassCastException at runtime(While try to cast Integer in to String).


  1. which of the following piece of code can be inserted to make the following code to compile?

import java.util.*;

class PickThePiece {

public static void main(String [] args) {

//insert the first line here

datas.add("delhi")

datas.add(new Object());

//insert the second line here

}

}

Options :

  1. List<Object> datas = new LinkedList<Object>();

String data = datas.get(0);

  1. List<Object> datas = new LinkedList<Object>();

String data = (String)datas.get(0);

  1. List<String> datas = new LinkedList<String>();

String data = (String)datas.get(0);

  1. List<String> datas = new LinkedList<String>();

String data = datas.get(0);

  1. all the above


Answer :

B,C, and D are the correct answers.

A is wrong because datas.get(0) will return a Object which cannot be directly assigned to a String without casting.


  1. What is the result of compiling and running the following code?

import java.util.*;

class SampleTest {

public static void main(String [] args) {

List samples = new ArrayList();

samples.add("100");

samples.add(200);

samples.add("300");

printData(samples);

}


static void printData(List<String> samples) {

for(String sample : samples) {

System.out.print(sample + “ “);

}

}

}


Options :


  1. Prints 100 200 300

  2. Compile time error

  3. Compiles without warning

  4. Compiles with warning

  5. Runtime Exception


Answer :

D, E are correct answers.

D) It produces warning since un-safe List samples is passed to a type safe collections(as a method argument).

E) Since samples.add(200), adds a Integer in to collection. While iterating through enhanced for loop, Integer is tried to cast to String causes ClassCastException.


  1. Consider the following code, select the valid options given below.

class Fruit {}

class Apple extends Fruit {}

class Orange extends Fruit {}


Options :

  1. List<? extends Fruit> stmt = new ArrayList<Fruit>();

  2. List<? super Apple> stmt = new ArrayList<Fruit>();

  3. List<? extends Fruit> stmt = new ArrayList<Apple>();

  4. List<? super Orange> stmt = new ArrayList<Orange>();

  5. All the above

  6. None of these


Answer :

E is the correct answer. All these options are valid.

Keyword “super “ – allows the type followed by keyword and its super type(parent ).

Keyword “extends” – allows the type followed by keyword and its sub type(child).


  1. What is the output of the following code?

import java.util.*;

class Color {}

class Blue extends Color {}

class Red extends Color {}


class TestColor {

public static void main(String [] args) {

1) List<Color> colors = new ArrayList<Color>();

2) colors.add(new Color());

3) colors.add(new Blue());

4) colors.add(new Red());

5) List<Color> newClr = alterColor(colors);

6) System.out.println(newClr);

}


static void alterColor(List clrs) {

7) clrs.add(new Object());

}

}


Options :

  1. Compile time error due to lines 3 and 4.

  2. Compile time error due to line 5.

  3. Compile time error due to line 7.

  4. Compiles with warning and produces some output.

  5. Compiles without warning and produces some output.

  6. Compiles fine and Exception is thrown at runtime.


Answers :

D is the correct answer.

Warning is due to non-type safe method call. Within the alterColor() method adding a new Object is not a issue because the collection becomes non-type safe.


  1. what is the result of the following code ?

import java.util.*;


class Bird {}

class Duck extends Bird {}

class Hen extends Bird {}


class FuzzyTest {

public static void main(String [] args) {

Map<String, Bird> birds = new HashMap<String, Bird>();

birds.put("bird", new Bird());

birds.put("hen", new Hen());

birds.put("duck", new Duck());

Map bs = addBirds(birds);

for(String b : bs.keySet())

System.out.print(b + " ");

}

static Map addBirds(Map brds) {

brds.put("bird", new Object());

return brds;

}

}


Options :

  1. Compiles and prints output “bird hen duck”.

  2. Compiles and prints output “bird duck hen”.

  3. Compiles and prints some output order cannot be determined.

  4. Run time Exception.

  5. Compilation fails.


Answer :

E is the correct answer.

Since bs is non-typesafe collection, bs.keySet() returns Object. But in enhanced for loop string is used to catch the returned values, that leads to compilation error.


  1. what are the valid statements can be filled in the blank, to make the code to compile and run?

import java.util.*;

interface Eat{}

class Animal implements Eat{}

class Dog extends Animal {}

class Cat extends Animal {}


class AnimalTest {

public static void main(String[] args) {

List<Animal> a = new ArrayList<Animal>();

List<Dog> d = new ArrayList<Dog>();

List<Cat> c = new ArrayList<Cat>();

checkAnimal(a);

checkAnimal(d);

checkAnimal(c);

}

static void checkAnimal( ________________ pets) {

System.out.print(“animals checked here”);

}

}


Options :

  1. List<? extends Animal>

  2. List<? super Animal>

  3. List<? extends Eat>

  4. List<? super Eat>

  5. List<?>

  6. All of the above


Answer :

A , C and E are the correct answers.

Keyword “super “ – allows the type followed by keyword and its super type(parent ).

Keyword “extends” – allows the type followed by keyword and its sub type(child).

Wild card ? – allows everything.


  1. what is the output of the following code?

import java.util.*;

class Example {

public static void main(String [] args) {

Set<String> values = new TreeSet<String>();

values.add(“yet”);

values.add(“get”);

values.add(“bet”);

displayValues(values);

}

static void displayValues(Set<?> values) {

values.add(“wet”)

for(Object v : values) ;

System.out.print(v + “ “);

}

}


Options :

  1. Compiles and gives output “yet get bet wet”.

  2. Compiles and gives output “bet get wet yet”.

  3. Compilation fails

  4. Compiles with warning and Exception thrown at runtime.

  5. Compiles without warning and Exception thrown at runtime.


Answer :

C is the correct answer.

When we use wildcard(?) to catch the collection , then modifications are not allowed in that collection. Here values.add(“wet”) will throw error at compilation time.


  1. Choose the valid ways to create an object for the following class.

class GenTest<T super Number> {

T num;

public T checkNumber(T n) {

return n;

}

}


Options :

  1. Compilation fails.

  2. GenTest<Number> gt = new GenTest<Number>();


  1. GenTest<Integer> gt = new GenTest<Integer>();


  1. GenTest<Object> gt = new GenTest<Object>();


  1. None of the above.



Answer :

A is the correct answer.

Since <T super Number> is an invalid syntax. If super keyword is replaced by extends, then B and C will be the valid answers.


  1. Choose the valid constructors for the following class.

class Generics<T>{}


Options :

  1. public Generics(){}

  2. public Generics<T>(){}

  3. public <T> Generics(T t){}

  4. public <T> Generics(){}

  5. All the above.


Answer :

A,C and D are correct answers.

B is incorrect because of improper syntax.













Servlets Interview Questions

Servlet Interview Questions

1. What is the servlet?
Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently

2. What is the architechture of servlet package?
Servlet Interface is the central abstraction. All servlets implements this Servlet 
Interface either direclty or indirectly
( may implement or extend Servlet Interfaces sub classes or sub interfaces)


Servlet
|
Generic Servlet
|
HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests
|
MyServlet

3. What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method to handle requests.
HttpServlet extends GenericServlet added new methods
doGet()
doPost()
doHead()
doPut()
doOptions()
doDelete()
doTrace() methods
Both these classes are abstract.

4. What's the difference between servlets and applets?
Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface.

5. What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.

6. When doGET() method will going to execute?
When we specified method='GET' in HTML
Example : < form name='SSS' method='GET'>

7. When doPOST() method will going to execute?
When we specified method='POST' in HTML
< form name='SSS' method='POST' >

8. What is the difference between Difference between doGet() and doPost()?
GET Method : Using get method we can able to pass 2K data from HTML
All data we are passing to Server will be displayed in URL (request string).

POST Method : In this method we does not have any size limitation.
All data passed to server will be hidden, User cannot able to see this info
on the browser.

9. What is the servlet life cycle?
When first request came in for the servlet , Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method

Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set.

10. Which protocol will be used by browser and servlet to communicate ?
HTTP




Source : www.javabeat.net











Servlets Interview Questions

Servlet Interview Questions


11. In how many ways we can track the sessions?
Method 1) By URL rewriting

Method 2) Using Session object

Getting Session form HttpServletRequest object
HttpSession session = request.getSession(true);

Get a Value from the session
session.getValue(session.getId());

Adding values to session
cart = new Cart();
session.putValue(session.getId(), cart);


At the end of the session, we can inactivate the session by using the following command
session.invalidate();

Method 3) Using cookies

Method 4) Using hidden fields


12. How Can You invoke other web resources (or other servelt / jsp ) ?
Servelt can invoke other Web resources in two ways: indirect and direct.

Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)

Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.

You can get this object using getRequestDispatcher("URL") method. You can get this object from either a request or a Context.

Example :
RequestDispatcher dispatcher = request.getRequestDispatcher("/jspsample.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}

13. How Can you include other Resources in the Response?
Using include method of a RequestDispatcher object.

Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response.

Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner");
&nbspif (dispatcher != null)
&nbspdispatcher.include(request, response);
}

14. What is the difference between the getRequestDispatcher(String path) ServletRequest interface and ServletContext interface?
The getRequestDispatcher(String path) method of ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.

15. What is the use of ServletContext ?
Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext.

16. Is there any way to generate PDF'S dynamically in servlets?
We need to use iText. A open source library for java. Please refer sourceforge site for sample servlet examples.

17. What is the difference between using getSession(true) and getSession(false) methods?
getSession(true) - This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object.

getSession(false) - This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

Source : www.javabeat.net

Struts Interview Questions

Struts Interview Questions

Question21: What are the disadvantages of Struts?
Answer: Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts:
a) High Learning Curve
Struts requires lot of efforts to learn and master it. For any small project less experience developers could spend more time on learning the Struts.

b) Harder to learn
Struts are harder to learn, benchmark and optimize.

Question22: What is Struts Flow?
Answer: Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. (Ref: http://struts.sourceforge.net/struts-flow/index.html )

Question23: What are the difference between <bean:message> and <bean:write>?
Answer: <bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle.

<bean:write>: This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables the programmers to easily present the data.

Question24: What is LookupDispatchAction?
Answer: An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. (Ref. http://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.html).

Question25: What are the components of Struts?
Answer: Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller.
Model: Components like business logic / business processes and data are the part of Model.
View: JSP, HTML etc. are part of View
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.


Question26: What are Tag Libraries provided with Struts?
Answer: Struts provides a number of tag libraries that helps to create view components easily. These tag libraries are:
a) Bean Tags: Bean Tags are used to access the beans and their properties.
b) HTML Tags: HTML Tags provides tags for creating the view components like forms, buttons, etc..
c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets.
d) Nested Tags: Nested Tags helps to work with the nested context.

Question27: What are the core classes of the Struts Framework?
Answer:
Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc.

Question28: What are difference between ActionErrors and ActionMessage?
Answer: ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property.
Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message.

ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form).

Question29: 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.


Question30: What do you understand by JSP Actions?
Answer: JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.
There are six JSP Actions:

<jsp:include/>

<jsp:forward/>

<jsp:plugin/>

<jsp:usebean/>

<jsp:setProperty/>

<jsp:getProperty/>


Source : www.javabeat.net

Struts Interview Questions

Struts Interview Questions

Question11: Why cant we overide create method in StatelessSessionBean?
Answer:
From the EJB Spec : - A Session bean's home interface defines one or morecreate(...) methods. Each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. The return type of a create method must be the enterprise Bean's remote interface type. The home interface of a stateless session bean must have one create method that takes no arguments.

Question12: Is struts threadsafe?Give an example?
Answer:
Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action.

Question13: Can we Serialize static variable?
Answer:
Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular object's state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields. There are four basic things you must do when you are making a class serializable. They are:

  1. Implement the Serializable interface.
  2. Make sure that instance-level, locally defined state is serialized properly.
  3. Make sure that superclass state is serialized properly.
  4. Override equals( )and hashCode( ).
    it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process .... (Source: http://www.oreilly.com/catalog/javarmi/chapter/ch10.html)
Question14: What are the uses of tiles-def.xml file, resourcebundle.properties file, validation.xml file?
Answer:
tiles-def.xml is is an xml file used to configure tiles with the struts application. You can define the layout / header / footer / body content for your View. See more at http://www.roseindia.net/struts/using-tiles-defs-xml.shtml.

The
resourcebundle.properties file is used to configure the message (error/ other messages) for the struts applications.

The file validation.xml is used to declare sets of validations that should be applied to Form Beans. Fpr more information please visit http://www.roseindia.net/struts/address_struts_validator.shtml.

Question15: What is the difference between perform() and execute() methods?
Answer:
Perform method is the method which was deprecated in the Struts Version 1.1.
In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.

Question16: What are the various Struts tag libraries?
Answer:
Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:
* Bean tag library - Tags for accessing JavaBeans and their properties.
* HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..
* Logic tag library - Tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library - For the application using tiles
* Nested tag library - For using the nested beans in the application


Question17: What do you understand by DispatchAction?
Answer:
DispatchAction is an action that comes with Struts 1.1 or later, that lets you combine Struts actions into one class, each with their own method. The org.apache.struts.action.DispatchAction class allows multiple operation to mapped to the different functions in the same Action class.
For example:
A package might include separate RegCreate, RegSave, and RegDelete Actions, which just perform different operations on the same RegBean object. Since all of these operations are usually handled by the same JSP page, it would be handy to also have them handled by the same Struts Action.

A very simple way to do this is to have the submit button modify a field in the form which indicates which operation to perform.

<html:hidden property="dispatch" value="error"/>
<SCRIPT>function set(target) {document.forms[0].dispatch.value=target;}</SCRIPT>
<html:submit onclick="set('save');">SAVE</html:submit>
<html:submit onclick="set('create');">SAVE AS NEW</html:submitl>
<html:submit onclick="set('delete);">DELETE</html:submit>

Then, in the Action you can setup different methods to handle the different operations, and branch to one or the other depending on which value is passed in the dispatch field.

String dispatch = myForm.getDispatch();
if ("create".equals(dispatch)) { ...
if ("save".equals(dispatch)) { ...

The Struts Dispatch Action [org.apache.struts.actions] is designed to do exactly the same thing, but without messy branching logic. The base perform method will check a dispatch field for you, and invoke the indicated method. The only catch is that the dispatch methods must use the same signature as perform. This is a very modest requirement, since in practice you usually end up doing that anyway.

To convert an Action that was switching on a dispatch field to a DispatchAction, you simply need to create methods like this

public ActionForward create(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...

public ActionForward save(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...

Cool. But do you have to use a property named dispatch? No, you don't. The only other step is to specify the name of of the dispatch property as the "parameter" property of the action-mapping. So a mapping for our example might look like this:

<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="dispatch"/>

If you wanted to use the property "o" instead, as in o=create, you would change the mapping to

<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="o"/>

Again, very cool. But why use a JavaScript button in the first place? Why not use several buttons named "dispatch" and use a different value for each?

You can, but the value of the button is also its label. This means if the page designers want to label the button something different, they have to coordinate the Action programmer. Localization becomes virtually impossible. (Source: http://husted.com/struts/tips/002.html).

Question18: How Struts relates to J2EE?
Answer:
Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard.

Question19: What is Struts actions and action mappings?
Answer:
A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward.

An action can perform tasks such as validating a user name and password.

An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action.

An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller.

Question20: Can I setup Apache Struts to use multiple configuration files?
Answer: Yes Struts can use multiple configuration files. Here is the configuration example:
<servlet>
<servlet-name>banking</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml,
/WEB-INF/struts-authentication.xml,
/WEB-INF/struts-help.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Source : www.javabeat.net

Struts Interview Questions

Struts Interview Questions

Q1: What is ActionServlet?
A: The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

Q2: How you will make available any Message Resources Definitions file to the Struts Framework Environment?
A:
Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.
Example:
<message-resources parameter="MessageResources" />

Q3: What is Action Class?
A:
The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

Q4: Write code of any Action Class?
A:
Here is the code of Action Class that returns the ActionForward object.
TestAction.java
package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 TestAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}

Q5: What is ActionForm?
A:
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

Q6: What is Struts Validator Framework?
A:
Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

Q7. Give the Details of XML files used in Validator Framework?
A:
The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

Q8. How you will display validation fail errors on jsp page?
A:
Following tag displays all the errors:
<html:errors/>

Q9. How you will enable front-end validation based on the xml in validation.xml?
A:
The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.

Question10: What is RequestProcessor and RequestDispatcher?
Answer:
The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client.

The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like
The ActionServlet Class
The RequestProcessor Class
The Action Class


The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application.
The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows.
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>



All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows.

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
<url-pattern>*.do</url-pattern>

A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/actionName.do

The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below.
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/do/*</url-pattern>
<url-pattern>*.do</url-pattern>

A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/do/action_Name
The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed.

Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method.
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception;

The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn’t already exist. The strut framework will create only a single instance of each Action class in your application.

Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>

Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>

The action forward mappings also can be specified in a global section, independent of any specific action mapping.
<global-forwards>
<forward name="Success" path="/action/somejsp.jsp" />
<forward name="Failure" path="/someotherjsp.jsp" />
</global-forwards>


public interface RequestDispatcher

Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.

getRequestDispatcher

public RequestDispatcher getRequestDispatcher(java.lang.String path)

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static.
The pathname must begin with a "/" and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher.

Parameters:
path - a String specifying the pathname to the resource
Returns:
a RequestDispatcher object that acts as a wrapper for the resource at the specified path
See Also:
RequestDispatcher, getContext(java.lang.String)


getNamedDispatcher

public RequestDispatcher getNamedDispatcher(java.lang.String name)

Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
Servlets (and JSP pages also) may be given names via server administration or via a web application deployment descriptor. A servlet instance can determine its name using ServletConfig.getServletName().
This method returns null if the ServletContext cannot return a RequestDispatcher for any reason.

Parameters:
name - a String specifying the name of a servlet to wrap
Returns:
a RequestDispatcher object that acts as a wrapper for the named servlet
See Also:
RequestDispatcher, getContext(java.lang.String), ServletConfig.getServletName()

Source : www.javabeat.net