Wednesday, February 25, 2009

URL'S

http://www.leepoint.net/notes-java/index.html
http://java2s.com/
http://www.studiesinn.com/topic-details/9/37.html
http://ajaxtraining.blogspot.com/

Saturday, February 21, 2009

Interface

We use interface to achieve polymorphism. In simple english, the users of your class will have a reference of the interface rather than the class which actually implement that method. This is an object oriented principle that enforce 'keeping the concerns separate' and 'program to super class/interface rather than sub class'. For example: assuming Calculator is an interface, the users of your controller are allowed to call getCalculator to get it. Now, for users, the point of contact is 'Calculator', they shouldn't be interested which class actually implemented the Calculator interface to provide the logic.
public Calculator getCalculator() {
return new BasicCalculator();
}
In future version, you can change the logic, and your users will not be bothered, for example, in an overridden method:
public Calculator getCalculator()
{return new EnhancedCalculator();}
Take an example of T.V, you will see that the remote control is the Interface to your T.V functions. If some Functions are subjected to change/enhanced there should be no effect on the interface/remote control in this example.
Plus if you don't want to expose your logic to some one, (means you don't some one to share your code) you can give him you interface, a standard way to use your logic.

"Interface is like defining some protocol.
When you start building some module or package you must code it into some proper manner so if someone else wants to update or work on it, its working is clear for them. Means it should be generic code. So instead of starting whole thing into single class, you thing about some generic methods, constants your module needed, without thinking of its implementation. So here comes the concept of Interface and Abstract Classes.
When you start implementing method define in Interface you start working with classes which implementing your interface. "

Tricky Questions

1)Can I get Session object from servlet or jsp to simple java class?
2)What is a singleton class?
3)What is the difference between sendRedirect and forward in servlet ?
4)What happened if i clone a singleton object?
5)What is the difference between PrintWriter and JspWriter class?
6)Can I call a static variable with object?
7)What are the collection framework hibernate supports?
8)How to get variable value from javascript in to jsp page?
9)What is the difference between pageContext and SevletContext?
10)Why java doesnot support multiple inheritance?
11) Can we use a ResultSet object after closing the Connection??
Actually not, but you can use RowSet in connectionless mode
12) By default java will import java.lang
println() is the method of class PrintStream and in the package java.io.*
Why how we are able to use println() without importing java.io.*
we dont use println() directly :P , instead we use System.out.println() where out is a final static member of type PrintStream in System class, and System class imports java.io.* for us so we need not bother to import java.io package.
11) Explain Memory leak in java ?
12) Write a program of Dead Lock condition in java .
13) What is the difference between sleep(1000) and wait(1000) ?
15) What is delegation in Java?

Friday, February 20, 2009

Marker Interface and Reflection Mechanism

Marker Interface
The marker interface is just an empty interface. Its purpose is to "mark". That is, a class is suppose to contain certain capability so it "marks" itself with a marker interface -- for example a class capable of cloning itself marks itself with 'Cloneable' interface. Its just a way of Object Oriented Programming. A certain framework (for example RMI) will only deal with classes which are "mark" with their required interfaces (for example Remote).
Reflection Mechanism
Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class.
Ex.
import java.lang.reflect.*;
class B
{
private int val=10;
}
class A
{
public static void main(String[] args) throws Exception
{
B bob=new B();
Field fld=bob.getClass().getDeclaredField("val");fld.setAccessible(true);
System.out.println("value:"+fld.getInt(bob));}}

Thursday, February 19, 2009

why EJB is only in appserver

EJB specs are part of Java Enterprise specifications. An App server implements JEE specifications, hence an EJB container is part of an app server. An EJB utilizes several other JEE components hence it usually does not exist as stand alone container.

There were some efforts to implement EJB as standalone container (just like JSP/Servlet container), but it wasn't successful.

Eclipse Shortcuts - Some really useful ones

I am trying to categorize them below:
Shortcuts for moving through members of a class:
Ctrl + Shift + Up Arrow Key — > It allows you to move one member up, that is if you have a large methods, and would like to move between methods this shortcut is very useful, rather then scrolling you can use this shortcut to move up the hierarchy in your class file, it jumps one member (including variables and methods) up.
Ctrl + Shift+ Down Arrow Key — > It allows you to move one member down, that is if you have a large methods, and would like to move between methods this shortcut is very useful, rather then scrolling you can use this shortcut to move down the hierarchy in your class file, it jumps one member (including variables and methods) down.
Ctrl+ F3 — > This one will pop up a window where you can see all the members of the class , and you can even type in the name of the member variable you are looking for, in a large class file having dozens of method and member variables, this shortcut should be your favorites weapon.
Shortcuts for closing files in Eclipse:
Ctrl + W — > It closes the current file on which you are working.
Ctrl + Shift + W — > Use this with caution , as it closes all the files in the editor at a single go.
Ctrl + F4 — > It closes the current file on which you are working, same as that of Ctrl + W.
Ctrl + Shift + F4 — > Use this with caution , as it closes all the files in the editor at a single go, same as that of Ctrl+ Shift + W. Depends on you choice which one to use.
Shortcuts for saving files in Eclipse:
Ctrl + S– > It is use for saving the current file on which you are working.
Ctrl + Shift + S — > It is used to save all the files in the editor which are open. (A good one if you have edited multiple files)
Shortcuts for Finding and moving around quickly:
Ctrl + L– > It takes you to the line number you specify, again one of the best shortcuts.
Ctrl + K — > Find Next, this is very useful, if you have something in search already using this will make you move around to the next search criteria.
Ctrl + Shift + K– > Find Previous, this will allow you to search backwards.
Shortcuts for Editing (Deleting) :
Ctrl + D– > Used for deleting a line.
Ctrl + Delete — > Used for deleting next word.
Ctrl + Backspace — > Used for deleting previous word.
Ctrl + Shift + Delete — > Delete to end of line.

Tuesday, February 10, 2009

What is scoped memory and why java uses it?

In java, a frequent occurence of a common phenomenon related to memory management is creation and destruction of temporary objects. What are java temporary objects? For example in java, when two strings are concatenated, a StringBuffer object is created. As two Java String objects cannot be added directly (immutable property), a helper object StringBuffer is used to construct a resultant java String object. This StringBuffer object is a temporary object, which is of no direct interest to the programmer. Most of the programming constructs are built in this type of model. Result of it is there are lot of garbage left behind.
Now the question is, what happens to the temporary java object and such garbage after the intended operation completes? Will it be saved for the life time of the program, or JVM (java virtual machine) or what is the underlying policy to destroy it? In automatic memory management the hassles of allocating and deallocating memory is no more a part of programmer’s job in java. But the downside of it is you never know, when an object will be freed. The java garbage collector (GC) doesnot provide any defined time boundaries.
This is where the java scoped memory concept comes into picture. Scoped memory concept is declaring to the JVM that, I am going to use this much amount of memory and those can be freed after this period. That is defining a boundary and bringing predictability. This predictability is needed the most for real time programming. Where you need to be certain about the cycles, time and cost of the operation.
In java scoped memory, the memory is preallocated for the task. This will ensure that the program will not get struck in the mid of operation because of memory resource shortage and constraints. Memory is deallocated and freed when the associated task gets completed. Therefore the recycling process of the memory is fast. But, all the objects related to that task and comes under that designated scope will disappear. If some objects are needed for future reference then that particular object needs to be associated to a different memory mechanism.
This is one of the latest feature in java adding power to the real-time java implementation. For more detail look into the Sun Java Real-Time System (Java RTS). It is Sun’s commercial implementation of the Real-Time Specification for Java (JSR-001).

Why not declare a constructor in servlet?

Technically you can define constructors in servlet. But, the declared constructor cannot access the ServletConfig object or throw a ServletException.
Then why is it not customary to declare a constructor in a servlet? Because the init() method is used to perform servlet initialization. In JDK 1.0 (servlet were written in this version), constructors for dynamically loaded Java classes such as servlets cannot accept arguments. Therefore init() was used to initialize by passing the implemented object of ServletConfig interface and other needed parameters.
Also, Java constructors cannot be declared in interfaces. So, javax.servlet.Servlet interface cannot have a constructor that accepts a ServletConfig parameter. To overcome this, init() method is used for initialization instead of declaring a constructor.

Friday, February 6, 2009

Serialization

Serialization is used to persist the state of an object into any permanent storage device (or) serialization is the technique of transporting objects over a data stream. It involves serializing of the object's state i.e. packing the data state of the object into bytes and then sending them over a stream to a reciever.
To make a class or a bean serializable we hv to implement either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable.
transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

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).THE ROLE OF SERIALIZATION IN EJB-------->A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You’re invoking methods remotely from JVM space ‘A’ on objects which are in JVM space ‘B’ – possibly running on another machine on the network. To make this happen, all arguments of each method call must have their current state plucked out of JVM ‘A’ memory, flattened into a byte stream which can be sent over a TCP/IP network connection, and then deserialized for reincarnation on the other end in JVM ‘B’ where the actual method call takes place. If the method has a return value, it is serialized up for streaming back to JVM A. Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement java.io.Serializable.

http://en.wikipedia.org/wiki/Serialization

Sunday, February 1, 2009

Explain typical Bean life cycle in Spring Bean Factory Container.

The following steps talk about throw light on how a bean life cycle is inside a bean factory container:
The bean's definition is found by the bean factory container from the XML file and instantiates the bean.
The Spring framework populates all of the properties as specified in the bean definition using DI.
If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean's ID.
If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.
If an init-method is specified for the bean, it will be called.
Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

JDBC Problems and how does Spring framework help to resolve them?

JDBC helps in accessing underlying RDBMS but it sometimes be quite cumbersome to use them and in following situations it become problematic:
-You have to ensure that ResultSets, Statements and (most importantly) Connections are closed after use. Hence correct use of JDBC results in a lot of code which is a common source of errors. Connection leaks can quickly bring applications down under load.
-The SQLException does not provide much information about what actually the probelm is as JDBC does not offer an exception hierarchy, but throws SQLException in response to all errors.The meaning of these values varies among databases.
Spring addresses these problems in two ways:
-By providing APIs that move tedious and error-prone exception handling out of application code into the framework. The framework takes care of all exception handling; application code can concentrate on issuing the appropriate SQL and extracting results.
-By providing a meaningful exception hierarchy for your application code to work with in place of SQLException. When Spring first obtains a connection from a DataSource it examines the metadata to determine the database product. It uses this knowledge to map SQLExceptions to the correct exception in its own hierarchy descended from org.springframework.dao.DataAccessException. Thus your code can work with meaningful exceptions, and need not worry about proprietary SQLState or error codes. Spring's data access exceptions are not JDBC-specific, so your DAOs are not necessarily tied to JDBC because of the exceptions they may throw.

Aspect Oriented Programming and how is it related with Spring?

Aspect Oriented Programming(AOP) is a paradigm of developmental approach which is based on:-separation of concerns encompasses breaking down a program in parts which overlap in functionality as little as possible.-cross-cutting concerns is how modules,classes,procedures intersect each other and defy concern like encapsulation-advancement in modularization.An AOP language consists of crosscutting expressions that encapsulate the concern in one place. AspectJ has a number of such expressions and encapsulates them in a special class, an aspect.An aspect can-change the behavior of the base code (the non-aspect part of a program) by applying advice(additional behavior) at various joint points (points in a program) specified by query called a point cut (that detects whether a given join point matches).-make structural changes to other classes, like adding members or parents.Spring implements AOP using -dynamic proxies (where an interface exists) or-CGLIB byte code generation at runtime (which enables proxying of classes). It works well in any application server and standalone environment so there is no vebdor dependency.-Spring can use AOP for declarative transaction management eliminating the need of EJB conatiner or JTA for achieving the same.-Spring AOP supports method interception and both stateful (one instance per advised object) and stateless interceptors (one instance for all advice).-Spring AOP can be used to implement application-specific aspects also.It all depends upon how much comfortable you are with Aspect concepts rather Spring AOP capabilities.-Spring AOP integrates transparently with the Spring BeanFactory concept.

Inversion of Control/Dependency Injection

Spring is an Inversion of Control container through its bean factory concept.IoC helps in loose coupling of the code .Spring is most closely identified with a flavor of Inversion of Control known as Dependency Injection(DI)--a name coined by Martin Fowler, Rod Johnson and the PicoContainer team in late 2003.DI is an old concept which caught the fancy of Java EE community not so long ago.DI is quite useful in test driven development and avoiding dependencies on other collaborating objects helps in building unit tests of objects behavior that is under test.
It follows famous Hollywood principle "Don't call me.I will call you". IoC moves the responsibility for making things happen into the framework, and away from application code. Whereas your code calls a traditional class library, an IoC framework calls your code. It segregates the calling mechanism of methods from actual implementation.
Dependency Injection is a form of IoC.In DI an object uses the other object to provide a specific functionality.It removes explicit dependence on container APIs.The ordinary Java methods are used for injecting dependencies by collaborating objects or configuration values into application object instances. With Dependency Injection the container figures out that a component needs an X object, and provides it to it at runtime. The container does this figuring out based on method signatures (usually JavaBean properties or constructors) and, possibly, configuration data such as XML.
DI can be accomplished either by Setter Injection or Constructor Injection and Spring supports both.
Some advantages of DI:
-No need for look up code at runtime, hence simpler to write and maintain. JavaBean setter method or constructors arguments are used to introduce DI in Spring.
-Easier testing of JavaBeans through JUnits.
-Spring framework provides strongly typed dependencies which a developer needs not be bothered about and type mismatches are raised as errors when the framework configures the application.
-With a DI approach, dependencies are explicit, and evident in constructor or JavaBean properties.
-Spring is non invasive that means using it won't invade your code with dependency on its APIs.No dependency on container APIs of most business objects. Any third party code or any POJO can be introduced as a Spring Bean.
-Spring BeanFactories are very lightweight,can be used inside applets, as well as standalone Swing applications,work fine withing EJB containers as well.

Hibernate Mapping Cheat Sheet

http://ndpsoftware.com/HibernateMappingCheatSheet.html

Tuesday, January 27, 2009

what Hibernate is and will show some examples

Main features
Hibernate is a solution for object relational mapping and a persistence management
solution or persistent layer. This is probably not understandable for anybody learning
Hibernate.
What you can imagine is probably that you have your application with some functions
(business logic) and you want to save data in a database. When you use Java all the
business logic normally works with objects of different class types. Your database tables
are not at all objects.
Hibernate provides a solution to map database tables to a class. It copies the database
data to a class. In the other direction it supports to save objects to the database. In this
process the object is transformed to one or more tables.
Saving data to a storage is called persistence. And the copying of tables to objects and
vice versa is called object relational mapping.
Why using Object Relational Mapping?
Better system architecture
When you include all functionality of your application and the access to the database
within your dialogs, you will have some severe disadvantages.
It is really difficult to reuse code. You will repeat code at many places. If you change
anything it is quite hard to find out all places where you have to add changes.
When you separate your dialogs from your logic and the logic from the persistence
mechanism you can more easily apply changes to one part without influencing the other
parts.
Reduce time for standard DB actions
Most queries in database development are simple “insert, update, delete” statements.
There is no need to develop all these tedious statements. Hibernate helps you save time.
Loading classes from the database looks like
Query query = session.createQuery("select b from Bug as b");
for (Iterator iter = query.iterate(); iter.hasNext();) {
bugs.add((Bug) iter.next());
}
return bugs;
saving a class “bug” to the database looks like
session.update(bug);
Advanced features difficult to develop yourself
Caching solutions, transactions and other features Hibernate provides are not so easy to
implement. It is actually non sense to develop something which allready exist.
Using Hibernate everything is there. You just have to use it.
How Hibernate works
What is nice and in my opinion an advantage over entity beans, hibernate starts from simple java
classes (Pojo = Plain Old Java Objects).
To use hibernate you will create a simple java class:
public class Bug
implements Serializable
{
private int hashValue = 0;
private java.lang.Integer id;
private java.lang.String title;
public Bug()
{
}
public Bug(java.lang.Integer fid)
{
this.setId(fid);
}
public java.lang.Integer getId() {
return id;
}
public void setId(java.lang.Integer id) {
this.id = id;
}
public java.lang.String getTitle() {
return title;
}
public void setTitle(java.lang.String title) {
this.title = title;
}
.............
Than you create a mapping file. The mapping file explains Hibernate which field in the class is
mapped to which field in the database.




public.bug_fid_seq





And you start using your hibernate class.
Example to create a new entry in the database:
try {
Bug bug = new Bug();
bug.setTitle("Title");
bug.setTuserFk(tuser);
Transaction tx = session.beginTransaction();
session.save(bug);
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
}
The creation of the description file can be done with tools like MyEclipse. MyEclipse provides
functionality to create classes and description files directly from database tables.
Hibernate includes tools to
• generate Java classes from description files
• description files from existing database tables
• database tables from description files.

Monday, January 26, 2009

JSP interview questions.

1. Can you explain JSP page life cycle?
2. What is EL?
3. how does EL search for an attribute?
4. What are the implicit EL objects in JSP?
5. How can we disable EL?
6. what is JSTL?
7. Can you explain in short what the different types of JSTL tags are?
8. How can we use beans in JSP?
9. What is tag for
10. What are JSP directives?
11. what are Page directives?
12. what are include directives?
13. Can you explain taglib directives?
14. How does JSP engines instantiate tag handler classes instances?
15. what’s the difference between JavaBeans and taglib directives?
16. what are the different scopes an object can have in a JSP page?
17. what are different implicit objects of JSP?
18. what are different Authentication Options available in servlets?
19. Can you explain how do we practically implement security on a resource?
20. How do we practically implement form based authentication?
21. How do we authenticate using JDBC?
22. Can you explain JDBCRealm?
23. Can you explain how do you configure JNDIRealm?
24. How did you implement caching in JSP?
25. How do we prevent browser from caching output of my JSP pages?
26. Can we explicitly destroy a servlet object?

50 Servlets Interview Questions & Answers

1) What is servlet?

Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.

2) What are the classes and interfaces for servlets?
There are two packages in servlets and they are javax.servlet and javax.servlet.http.

Javax.servlet contains:

Interfaces Classes
Servlet Generic Servlet
ServletRequest ServletInputStream
ServletResponse ServletOutputStream
ServletConfig ServletException
ServletContext UnavailableException
Single ThreadModel

Javax.servlet.http contains:

Interfaces Classes
HttpServletRequest Cookie
HttpServletResponse HttpServlet
HttpSession HttpSessionBindingEvent
HttpSessionContext HttpUtils
HttpSeesionBindingListener

3) What is the difference between an applet and a servlet?

a) Servlets are to servers what applets are to browsers.
b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

4) What is the lifecycle of a servlet?

Each Servlet has the same life cycle:
a) A server loads and initializes the servlet by init () method.
b) The servlet handles zero or more client’s requests through service ( ) method.
c) The server removes the servlet through destroy() method.

5) What is the ServletConfig () and why are using ServletConfig?

This interface is implemented by services in order to pass configuration information to a servlet when it is first loaded. A service writer implementing this interface must write methods for the servlet to use to get its initialization parameters and the context in which it is running.

Public interface ServletConfig

6) what is meant by the ServletContext () and use of the method?
Public interface ServletContext:

The ServletContext interface gives servlets access to information about their environment, and allows them to log significant events. Servlet writers decide what data to log. The interface is implemented by services, and used by servlets. Different virtual hosts should have different servlet contexts.

7) What is use of parseQueryString?

Parses a query string and builds a hash table of key-value pairs, where the values are arrays of strings. The query string should have the form of a string packaged by the GET or POST method. (For example, it should have its key-value pairs delimited by ampersands (&) and its keys separated from its values by equal signs (=).)
Note:
public static Hash table parseQueryString(String s)

8)what are the types of servlets.
Genereic Servlets,HttpServlets.

9) What are the different methods in HttpServlet?
doGet(),doPost(),doHead,doDelete(),deTrace()

10)What is the difference between GET and POST.
a) DoGet () method is used to get information, while doPost ( ) method is used for posting information.
b) DoGet () requests can’t send large amount of information and is limited to 240-255 characters. However, doPost ( ) requests passes all of its data, of unlimited length.
c) A doGet ( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost () request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.

11) Why do you need both GET and POST method implementations in Servlet?

A single servlet can be called from different HTML pages, so different method calls can be possible.

12) When init () and Destroy () will be called.

Init () is called whenever the servlet is loaded for the first time into the webserver.Destroy will be called whenever the servlet is removed from the web server.

13) Who is loading the init () method of servlet?

Web server

14) If you want to modify the servlet, will the Web server need to be Shutdown.

No

15) what is the advantage of Servlets over other server side technologies.

Platform independent, so once compiled can be used in any web server. For different processes different threads will execute inbuilt multithreaded.

16) What is Server-Side Includes (SSI)?

Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with a .shtml extension.

17) What is Single Threaded Model in Servlets and how is it useful give one practical example.

For every single user a different copy of this servlet is executed. Credit card transactions.

18) What are the uses Sessions?

It’s a part of the Session Tracking and it is for mainting the client state at server side.

19) What are the advantage of using Sessions over Cookies and URLReWriting?

Sessions are more secure and fast because they are stored at server side. But Sessions has to be used combined with Cookies or URLReWriting for mainting the client id that is sessionid at client side.

Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies which we are mainting may work or not but in sessions cookies are disable we can maintain
our sessionid using URLReWriting

In URLReWriting we can’t maintain large data because it leads to network traffic and access may be become slow. Where as in sessions will not maintain the data which we have to maintain instead
we will maintain only the session id.

20) What is session tracking and how do you track a user session in servlets?

Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are:

a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password

b) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server

c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.

d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.

e) Http Session- places a limit on the number of sessions that can exist in memory. This limit is set in the session.maxresidents property

21) what is Cookies and what is the use of Cookies?

Cookies are used to get user agents (web browsers etc) to hold small amounts of state associated with a user’s web browsing. Later that information read by server

22) what are cookies and how will you use them?

Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user.
A) Create a cookie with the Cookie constructor:
public Cookie (String name, String value)
b) A servlet can send a cookie to the client by passing a Cookie object to the add Cookie () method of
HttpServletResponse:
public void HttpServletResponse.addCookie(Cookie cookie)
c) A servlet retrieves cookies by calling the get Cookies() method of HttpServletRequest:
public Cookie[ ] HttpServletRequest.getCookie( ).

23) How many Cookies are supported to the host?

User agents accepted to support twenty per host. And its take four Kilobytes each.

24) What is the use of set Comment and get Comment methods in Cookies?

SetComment: If a user agent (web browser) presents this cookie to a user, the cookie’s purpose will be described using this comment. This is not supported by version zero cookies.

Public void set Comment (String use)
{
}
get Comment:
Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.

25) Why we are used setMaxAge () and getMaxAge () in Cookies?

SetMaxAge

public void setMaxAge (int expiry)

sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behaviour: the cookie is not stored persistently, and will be deleted when the user agent exits. A zero value causes the cookie to be deleted

getMaxAge ():

public int getMaxAge ()

Returns the maximum specified age of the cookie. If none was specified, a negative value is returned, indicating the default behavior described with setMaxAge.

26) What is the use of set Secure () and get Secure () in Cookies?

Set Secure

Indicates to the user agent that the cookie should only be sent using a secure protocol (https). This should only be set when the cookie’s originating server used a secure protocol to set the cookie’s value.

Public void setSecure(boolean flag)

getSecure:

Returns the value of the ’secure’ flag.

Public boolean getSecure()

27)What is meant by Http session and what is the use of sessions ?
The Http Session interface is implemented by services to provide an association between an HTTP client and HTTP server. This session, persists over multiple connections and/or requests during a given time period. Sessions are used to maintain state and user identity across multiple page requests.

Http Session session = req.getSession (true);

28) What are the methods in HttpSession and use of those methods?
a) getCreationTime()

Returns the time at which this session representation was created.

b) GetId ()

Returns the identifier assigned to this session.

c) getLastAccessedTime()

Returns the last time the client sent a request carrying the identifier assigned to the session.

d) getSessionContext()
Returns the context in which this session is bound.

e) getValue(String)

Returns the object bound to the given name in the session’s application layer data.
f) getValueNames()

Returns an array of the names of all the application layer data objects bound into the
session.
g) Invalidate ()

Causes this representation of the session to be invalidated and removed from its context.
h) isNew()

A session is considered to be “new” if it has been created by the server, but the client has
not yet acknowledged joining the session.
j) putValue(String, Object)

Binds the specified object into the session’s application layer data with the given name.

k) removeValue(String)

Removes the object bound to the given name in the session’s application layer data.

29) How do you communicate between the servlets?

a) Servlet chaning
b) Servlet context (RequestDespatcher interface)

30)Can you send the mail from a servlet ,if yes tell how?

yes.using mail API

31) How do you access variables across the sessions.

Through ServletContext.

32) Where the session data will store?

Session objects

33) what is Servlet Context?

This object represents resources shared by a group of servlets like servlet’s environment, Application attributes shared in the context level.

34) How do you trap the debug the errors in servlets.

Error log file

35) How do you debug the Servlet?

Through servlet log ();

36) How do u implement threads in servlet?

Internally implemented

37) How do you handle Database access and in which method of the servlet do you like to create connection.

Init ()

38) If you want to improve the performance how do you create connections for multiple users?
Connection Pooling.

39) What is connection pooling?

Class which manages no of user requests for connections to improve the performance.

40) What are the different servers available for developing and deploying Servlets?

a) JRun2.0–Allaire
b) Apache –jserv
c) jwsdk2.0 –sun
d) servletexec
e) Tomcat web server–tomcat
f)Web logic AS–BEA Systems
g)NetDynamics5.0–sun
h)Iplanet–sun Netscape
i)Netscape–Netscape
g)IBM web sphere–IBM
h)oracle–oracle
i)Proton-Pramati technologies

41) Is it possible to communicate from an applet to servlet and how many ways and how?

Yes, there are three ways to communicate from an applet to servlet and they are:
a) HTTP Communication(Text-based and object-based)
b) Socket Communication
c) RMI Communication
(You can say, by using URL object open the connection to server and get the Input Stream from URLConnection object).
Steps involved for applet-servlet communication:
step: 1 Get the server URL.
URL url = new URL();
step: 2 Connect to the host
URLConnection Con = url.openConnection();
step: 3 Initialize the connection
Con.setUseCatches(false):
Con.setDoOutput(true);
Con.setDoInput(true);
step: 4 Data will be written to a byte array buffer so that we can tell the server the length of the data.
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
step: 5 Create the OutputStream to be used to write the data to the buffer.
DataOutputStream out = new DataOutputStream(byteout);

42) Why should we go for interservlet communication?

Servlets running together in the same server communicate with each other in several ways.
The three major reasons to use interservlet communication are:
a) Direct servlet manipulation - allows gaining access to the other currently loaded servlets and performing certain tasks (through the ServletContext object)
b) Servlet reuse - allows the servlet to reuse the public methods of another servlet.
c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)

43) Is it possible to call servlet with parameters in the URL?
Yes. You can call a servlet with parameters in the syntax as (? Param1 = xxx || m2 = yyy).

44) What is Servlet chaining?
Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.
In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.

45) How do servlets handle multiple simultaneous requests?
The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

46) How are Servlets and JSP Pages related?
JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.
Servlets:

47).How do servlets handle multiple simultaneous requests?
Using Threads

48).How do I automatically reload servlets?
Depends upon the server’s servlet reload properties.

48).My servlet, which ran correctly under the Servlet 2.0 APIs (Java Web Server 1.1.3) is not running under the Servlet 2.1 APIs (Java Web Server 2.0). What’s wrong?
You might have used servlet to servlet communication by using servletcontext methods like getServlet(),getServlets() which are depricated and returns null from new release that is from
servlet2.1 API.

49) What are the types of ServletEngines?

Standalone ServletEngine: A standalone engine is a server that includes built-in support for servlets.

Add-on ServletEngine: It’s plug-in to an existing server. It adds servlet support to a server that was not originally designed with servlets in mind.

Embedded ServletEngine: it is lightweight servlet deployment platforms that can be embedded in another application. that application become true server.

50) What is http tunneling?

It is mechanism of performing both write and read operations using http protocol. It is extending the functionality of http protocol.

51).How do I use native code in a servlet?
52) What’s with the javax.servlet package naming?
53. List out Differences between CGI Perl and Servlet?

Servlet CGI

Platform independent Platform dependent.

Language dependent Language independent.

Explain DI or IOC pattern

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. Dependancy Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected, rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter-, constructor- and interface-based injection. Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.

Spring Features

Spring is a layered Java/J2EE application platform,

Spring includes:

  • The most complete lightweight container, providing centralized, automated configuration and wiring of your application objects. The container is non-invasive, capable of assembling a complex system from a set of loosely-coupled components (POJOs) in a consistent and transparent fashion. The container brings agility and leverage, and improves application testability and scalability by allowing software components to be first developed and tested in isolation, then scaled up for deployment in any environment (J2SE or J2EE).

  • A common abstraction layer for transaction management, allowing for pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Generic strategies for JTA and a single JDBC DataSource are included. In contrast to plain JTA or EJB CMT, Spring's transaction support is not tied to J2EE environments.

  • A JDBC abstraction layer that offers a meaningful exception hierarchy (no more pulling vendor codes out of SQLException), simplifies error handling, and greatly reduces the amount of code you'll need to write. You'll never need to write another finally block to use JDBC again. The JDBC-oriented exceptions comply to Spring's generic DAO exception hierarchy.

  • Integration with Toplink, Hibernate, JDO, and iBATIS SQL Maps: in terms of resource holders, DAO implementation support, and transaction strategies. First-class Hibernate support with lots of IoC convenience features, addressing many typical Hibernate integration issues. All of these comply to Spring's generic transaction and DAO exception hierarchies.

  • AOP functionality, fully integrated into Spring configuration management. You can AOP-enable any object managed by Spring, adding aspects such as declarative transaction management. With Spring, you can have declarative transaction management without EJB... even without JTA, if you're using a single database in Tomcat or another web container without JTA support.

  • A flexible MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. Note that a Spring middle tier can easily be combined with a web tier based on any other web MVC framework, like Struts, WebWork, or Tapestry.

Features of Java

Here we list the basic features that make Java a powerful and popular programming language:
  • Platform Independence
    • The Write-Once-Run-Anywhere ideal has not been achieved (tuning for different platforms usually required), but closer than with other languages.

  • Object Oriented
    • Object oriented throughout - no coding outside of class definitions, including main().
    • An extensive class library available in the core language packages.

  • Compiler/Interpreter Combo
    • Code is compiled to bytecodes that are interpreted by a Java virtual machines (JVM) .
    • This provides portability to any machine for which a virtual machine has been written.
    • The two steps of compilation and interpretation allow for extensive code checking and improved security.

  • Robust
    • Exception handling built-in, strong type checking (that is, all data must be declared an explicit type), local variables must be initialized.

  • Several dangerous features of C & C++ eliminated:
    • No memory pointers
    • No preprocessor
    • Array index limit checking

  • Automatic Memory Management
    • Automatic garbage collection - memory management handled by JVM.

  • Security
    • No memory pointers
    • Programs runs inside the virtual machine sandbox.
    • Array index limit checking
    • Code pathologies reduced by
      • bytecode verifier - checks classes after loading
      • class loader - confines objects to unique namespaces. Prevents loading a hacked "java.lang.SecurityManager" class, for example.
      • security manager - determines what resources a class can access such as reading and writing to the local disk.

  • Dynamic Binding
    • The linking of data and methods to where they are located, is done at run-time.
    • New classes can be loaded while a program is running. Linking is done on the fly.
    • Even if libraries are recompiled, there is no need to recompile code that uses classes in those libraries.

      This differs from C++, which uses static binding. This can result in fragile classes for cases where linked code is changed and memory pointers then point to the wrong addresses.

  • Good Performance
    • Interpretation of bytecodes slowed performance in early versions, but advanced virtual machines with adaptive and just-in-time compilation and other techniques now typically provide performance up to 50% to 100% the speed of C++ programs.

  • Threading
    • Lightweight processes, called threads, can easily be spun off to perform multiprocessing.
    • Can take advantage of multiprocessors where available
    • Great for multimedia displays.

  • Built-in Networking
    • Java was designed with networking in mind and comes with many classes to develop sophisticated Internet communications.