+ All Categories
Home > Documents > Java Ken

Java Ken

Date post: 08-Nov-2014
Category:
Upload: amit-tripathy
View: 8 times
Download: 0 times
Share this document with a friend
Description:
java qst paper
Popular Tags:
28
What are the Things we can't mark as Static ? 1.Constructors 2. Classes 3. Interfaces 4. Inner Classes 5. Inner Class Methods 6. Instance Variables 7. Local Variables 1. Why abstract class cant be instantiated ? An Abstract class is a class that is declared as abstract . It may or may not include abstract methods . We must declare Abstract class and Abstract methods with the key word abstract . Abstract classes cannot be instantiated, means we can't create an object to Abstract class . We can create Subclasses to Abstract classes . An Abstract class may or may not have abstract methods , abstract method in the sense a method can declared without any body implementation is called abstract method . So in that case JVM does not know how much memory it has to allocate for that abstract method because abstract method does not have body implementation. So JVM will not able to allocate memory for the abstract methods when the time of creating instance to Abstract class . So JVM unable to create the instance to Abstract class . So that we can't create the object for the Abstract class . It is also possible that we can create an Abstract class with all concrete methods, that is without any abstract methods also. In that case also we can't create the instance for
Transcript
Page 1: Java Ken

What are the Things we can't mark as Static ?

1.Constructors2. Classes3. Interfaces4. Inner Classes5. Inner Class Methods6. Instance Variables7. Local Variables1. Why abstract class cant be instantiated ?

An Abstract class is a class that is declared as abstract. It may or may not include abstract methods. 

We must declare Abstract class and Abstract methods with the key word abstract.

Abstract classes cannot be instantiated, means we can't create an object to Abstract class. We can create Subclasses to Abstract classes.

An Abstract class may or may not have abstract methods, abstract method in the sense a method can declared without any body implementation is called abstract method. So in that case JVM does not know how much memory it has to allocate for that abstract method because abstract method does not have body implementation. So JVM will not able to allocate memory for the abstract methods when the time of creating instance to Abstract class. So JVM unable to create the instance to Abstract class. So that we can't create the object for the Abstract class. 

It is also possible that we can create an Abstract class with all concrete methods, that is without any abstract methods also. In that case also we can't create the instance for the Abstract class. Why because the abstract keyword simply indicates to JVM that the class cannot be instantiated. 

The designers of Java made the JVM that when it find abstract keyword for any class then JVM can't create the instance for that class.

What is the performance of sendRedirect() compared to forward() ?

Page 2: Java Ken

When compared to forward(), sendRedirect() is low performance why because :

- In case of forward() only once the Client sends the request to Server.

- But in case of response.sendRedirect() internally Client become active to make a new request and to send Server. So in case of response.sendRedirect() Client will send two requests to Server. So it takes times to resend the request to Server. So that it is slow process when compared to forward().

What will happen if we declare variable as part of scriptlet ?

If we decalre any variable in scriplet then that variable will become local variable to the service() method.

By using which we can forward the request to a resource which is part of another Server ?

By using sendRedirect() we can forward request to another Server. 

- We can use forward() to forward request to a resource within the same Server only.

response.sendRedirect() : With response.sendRedirect() also we get the same response, whatever we will get with the RequestDispatcher.forward(). 

But in response.sendRedirect() whenever the Client makes any request it goes to the Container, there the Container decides whether the concerned Servlet can handle the request or not. If not then the Servlet decides that the request can be handle by other Servlet or JSP. Then the Servlet calls the response.sendRedirect() method of the response object and sends back the response to the Browser along with the status code. 

Then the Browser sees the status code and look for that Servlet which can now handle the request. Again the Browser makes a new request, but with the name of thatServlet which can now handle the request and send to the Server. Then the Container now executes the service() method of thet new Servlet. And the result that was sent by the new Servlet, will be displayed by the Browser. 

- Here eventhough we are sending one request from Browser, internally two

Page 3: Java Ken

times our Browser send request to Server. Because of the response.sendRedirect() Browserwill again send a new request.

Difference between forward() and response.sendRedirect() : Functionality wise both these methods are same. That is we get the same result with these two methods.

1….But in case of forward() once if the Client sends the request to Server then it become ideal till it receive the response from the Server. But in case ofresponse.sendRedirect() internally Client become active to make a new request and to send Server. So in case of response.sendRedirect() Client will send two requests to Server. 

2…..The main difference is that by using forward() we can dispatch the request to another resource (Servlet/JSP) within the Application or in another Application, but these applications should run in the same Server. That means we can't forward request to another resource of Application running in another Server. But by usingresponse.sendRedirect() we can forward request to another Application running in another Server also.

Explain about Abstraction in Java with some Examples ?

Definition : Showing the Essential data and hiding the non-Essential data is known as Abstraction. 

Example : suppose you take equals(Object obj) method in Object Class, when we use this method ? when we want to compare whether two objects are equal or not, for that we are using this equals() method, but we don't know how it was implemented by Java people, just we are using that method. 

- So here what Java people has done means, they Hide the implementation of that equals() method to users (means ours) . Because that is not essential to users, only the essential is that method name, What it returns, Class and Package in which it included. that only required.

So you can say this is one of the examples for Abstraction.

Here are some more Examples : 

Page 4: Java Ken

JSP is an extension of the Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Servlet technology is capable of generating HTML with out.println(“<html>….. </html>”) statements, where out is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain (Hard Coading). The JSP technology solves this by providing a level of abstraction so that the we can use custom tags and action elements, which can speed up Web development and are easier to maintain.

- So here we just using Tags, but we are not aware of these tag implementations, those are hidden by Java People.

And Why we need abstraction means : 

- Abstraction is an important OO concept. The ability for a program to ignore some aspects of the information that it is manipulating, ie. Ability to focus on the essential. Each object in the system serves as a model of an abstract "actor" that can perform work, report on and change its state, and "communicate" with other objects in the system, without revealing how these features are implemented.

Here see general Examples :

Example 1 : You see some websites, the user have a limited options, some options are disabled means hidden, but Adminstrator have rides to use all the options that means options will be the same for that s/w but for users some are disbled and for Admin pepople can a have ride to use that options. So here we can say those options are implemented using abstraction by the developers who developed that s/w. 

Example 2 : 

When you drive your car you do not have to be concerned with the exact internal working of your car (unless you are a mechanic). What you are concerned with is interacting with your car via its interfaces like steering wheel, brake pedal, accelerator pedal etc. Hence the knowledge you have of your car is abstract.

Page 5: Java Ken

 Can an Abstract Class be Final ?

No, Abstract Class cannot be final

No it can't be. Abstract class may contain only defined methods also. So no need to extend it to another class. But we can't create object to Abstract class to access methods of that class. So we need to use object of Subclass to access them. final resist the inheritance. So abstract and final together is not possible....

 How Java handles visibility of elements ?

The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.

Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.

Access Modifiers :

1. private2. protected3. default4. public

Public access modifier :

Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.

Private access modifier :

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an

Page 6: Java Ken

interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.

Protected access modifier :

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.

Default access modifier :

Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

Explain when the finalize() method will be called?

The Object class provides a callback method, finalize(), that may be invoked on an object when it becomes garbage.

Java provides us a mechanism to run some code just before our object is deleted by the Garbage Collector. This code is located in a method named finalize(). 

When JVM trying to delete the objects, then some objects refuse to delete if they held any resource. If our object opened up some resources, and we woluld like to close them before our object is deleted. So before Garbage operation we have to clean up the resources which the object held on, that clean up code we have to put in finalize()method. 

- We can override finalize() to do cleanup, such as freeing resources. Any code that we put into our Class's overridden finalize() method is not guarunteed to run, so don't provide essential code in that method.

Page 7: Java Ken

 Hibernate Criterion

Hibernate offers a set of APIs that map the SQL functionality to objects. This allows programmers to use an entirely object-oriented approach without falling back on a relational methodology. Keep reading to find out more.

Though HQL works with the object-oriented approach, we still need to know SQL. The only difference is the replacement of the relational methodology with the object-oriented one. In essence, a developer still has to drop into an SQL-like syntax for CRUD operations.

To overcome this obstacle and provide an extensible as well as completely object-oriented solution, Hibernate exposes a set of APIs that map the SQL functionality to objects, eliminating the need for an SQL-like syntax. These APIs constitute the Hibernate Criteria Query APIs.

Core Classes of Criteria Queries :

Each class of the Criteria Query API represents an aspect of the relational approach. 

There are five core APIs that are commonly used. They are :

1. Criteria2. Criterion3. Restrictions4. Projection5. Order

The Criteria class provides the gateway to working with criteria APIs. It is an interface that provides a simplified API for retrieving objects containing or composed of Criterion objects. In a situation where the restrictions query is composed of a variable number of fields, this approach is very useful. To get a reference to the Criteria class, use the createCriteria() method of the Session class. This method takes the name of the ORM class on which the query has to be executed. In essence the Session acts as a factory for the Criteria class. 

In statement form it would be :Code:

Criteria criteria= session.createCriteria(Order.class)

The above statement returns a reference to Criteria for the Order ORM class.

Looking at the second core API, in the relational approach, conditions placed

Page 8: Java Ken

on retrieving data are known as criterion. The Criterion class is the object-oriented representation of the relational criterion. It can be used as restrictions on the criteria query. In other words, Criterion is the object-oriented representation of the “where” clause of a SQL query. The conditions to be applied (also known as restrictions) can be provided by the Restrictions class. 

In code this would be :Code:

Criterion crit=Restriction.eq(“orderId”,”OD00009”);criteria.add(crit);

From the above example it is clear that the Criterion is the “where” clause, which, when added to the Criteria object, provides a complete query with restrictions. Here the built-in Restriction type eq() (for testing equality) is being used.

The Restriction API provides the built-in types for Criterion. Essentially, the Restriction class is a factory to the Criterion class. All of its methods are static. In Hibernate 2.x, the Expression class provided the services that are now provided by the Restriction class. The Restriction class provides almost all the required restrictions such as equals (eq()), logical and (and()), like (like()) and so on.

The Projection class is an object-oriented representation of query resultset projection in a Criteria query. In simpler terms, projection refers to the fields mentioned in the select clause of a query. The same can be achieved by using the Projection class in a Criteria query. The Projection class acts as a factory for the Projection class. Projection can be added by using the addProjection() method of the ProjectionList class. The addProjection() method of the Criteria class in turn returns a Criterion object. 

In code this would be :Code:

List orders = session.createCriteria(Order.class).setProjection( Projections.projectionList().add( Projections.rowCount() )).list();

The Order class represents the “order by” clause of SQL. By using the asc() and desc() methods of this class, order can be imposed upon the Criteria resultselt.

Criteria Queries :

Page 9: Java Ken

DML plays the most important role in the R (retrieve) operation of the CRUD quad. This is reflected in the core classes of Criteria API. 

The retrieval of data itself can be separated into four major categories :

1. Projection2. Restriction3. Aggregation4. Grouping

The usage of core classes among these categories cannot be generalized. The reason for this will be evident from the details. All the examples are based on the ORDER and PRODUCTS table.

The Select clause is just a part of the services provided by the Projection class. 

Following is SQL query for projection of all fields of the ORDER table in SQL :Code:

SELECT * FROM ORDER

The Criteria equivalent would be :Code:

List orders= session.createCriteria(Order.class).list();

The above statement executes the corresponding SQL statement at the database server, populates the instances of the Order ORM class, adds them to a list and returns the List object. 

Actually, the above statement is composed of two statements :Code:

Criteria criteria= session.createCriteria(Order.class) and List orders=criteria.list().

The combination of such dependent statements is known as method chaining. The above code retrieves all the rows from the ORDER table. But what if only the data contained in one of the fields has to be retrieved, as in the following SQL query :Code:

SELECT NAME FROM PRODUCT

Page 10: Java Ken

Here, the Projection class comes into play. The above query can be rewritten into a Criteria query as :Code:

List products=session.createCriteria(Product.class). setProjection(Projection.property(\”name\”)).list();

It is clear from the above example that to query based on just one field, the fieldname is passed as an argument to the property() method of the Projection class. The Projection instance returned in turn becomes an argument to the setProjection() method. Similarly, to retrieve data based on two fields, ProjectionList has to be used. 

Hence the SQL query :Code:

SELECT NAME, ID FROM PRODUCT

Would becomeCode:

List products =session.createCriteria(Product.class).setProjection(Projections.propertyList().add(Projection.property(\”name\”)).add(Projection.property(\”id\”))).list();

Now let’s make the query more complex by introducing joins. What would be the equivalent of a query such as the one below :Code:

SELECT O.*, P.* FROM ORDERS O, PRODUCT P WHERE O.ORDER_ID=P.ORDER_ID;

If you think the Criteria representation of the above would be as complex, then have a look at the following :Code:

List orders = session.createCriteria(Order.class).setFetchMode(“products”,FetchMode.JOIN).list();

It’s as simple as that. The only thing to be done is to call the setFetchMode() of the Criteria class with two parameters: the name of the class with which the current class has to be joined and mode of the fetching of the data from the associated class. In the above case, the class name is actually the instance variable provided within the Order class. The mode is Join.

Page 11: Java Ken

So retrieval is done, but there is just one problem. If the data has to be retrieved based on a condition, then what? Then Restriction has to be used.

In layman’s terms, restriction means imposing conditions. To retrieve data based on certain conditions, Restriction must be used. Here the Restriction class comes into the picture. All the conditions provided by SQL are available in Criteria. The ones most commonly used are as follows:

Restriction.between is used to apply a between constraint to the field.

Restriction.eq is used to apply an equal constraint to the field.

Restriction.ge is used to apply a greater than or equal constraint to the field.

Restriction.gt is used to apply a greater than constraint to the field.

Restriction.idEq is used to apply an equal constraint to the identifier property.

Restriction.in is used to apply an in constraint to the field.

Restriction.isNotNull is used to apply an is not null constraint to the field.

Restriction.isNull is used to apply an is null constraint to the field.

Restriction.ne is used to apply a not equal constraint to the field.

So a SQL such as this :Code:

SELECT * FROM ORDERS WHERE ORDER_ID=’1092’;

Would becomeCode:

List orders= session.createCriteria(Order.class).add(Restrictions.eq(“orderId”,”1092”)).list();

Applying the restrictions becomes easy in the case of joins as well. For example, the following query :Code:

Page 12: Java Ken

SELECT O.*, P.* FROM ORDERS O, PRODUCT P WHERE .ORDER_ID=P.ORDER_ID AND P.ID=’1111’;

Would becomeCode:

List orders = session.createCriteria(Order.class).setFetchMode(“products”,FetchMode.JOIN).add(Restrictions.eq(“id”,”1111”)).list();

Just adding the Restriction to Criteria returned by setFetchMode() does the same thing that the above given SQL does.

Through restriction conditions can be imposed on data retrieval, there are situations where the data to be retrieved has to be based on the groups of values of a column. In such conditions, Aggregation must be used. Criteria provides aggregation functionality through the Projection class itself. So to get the count of all the rows present in the ORDER table based on the ID field, the criteria query would be :Code:

List orders = session.createCriteria(Order.class).setProjection( Projections.proj

public HttpSession getSession(boolean create) :

- Returns the current HttpSession associated with this request or, if there is no current Session and create is true, returns a new Session.

- If create is false and the request has no valid HttpSession, this method returns null.

- To make sure the session is properly maintained, you must call this method before the response is committed.

Parameters : true - to create a new Session for this request if necessary; false to return null if there's no current Session

Returns : The HttpSession associated with this request or null if create is false and the request has no valid Session.

request.getSession(true) : This method will check

Page 13: Java Ken

whether Session already existed for the request or not. If it existed then it will return the already existed Session. IfSession is not already existed for this request then this method will create a new Session and return that new Session.

request.getSession(false) : This method will check whether Session already existed for the request or not. If it existed then it will return the already existed Session. IfSession is not already existed for this request then this method will return NULL, that means this method says that the request does not have a Session previously.

request.getSession() : Returns the current Session associated with this request, or if the request does not have a Session, creates one. Its by default work asrequest.getSession(true).

Why those 3 different methods are available means, It is not always a good idea to create a new Session. If we don't want to create a new Session then we should usegetSession(false).

When a Servlet will destroy ?

I think / know Container calls destroy() / init() methods only once in its Lifecycle. The destroy() will be called by the Container for cleanup purpose before it destroyed. But my question is when the Servlet will destroy. 

Is it true for the following cases ? 

Case 1 : When we redeploy the Servlet. Case 2 : When Server Crashes.

I know in this forums all are very consious about their answers & very talanted people. So kindly discuss with me about this post. Please give ur views.

Imp=========A Servlet will be destroyed by Container in below cases :

1. When we modify the Servlet and re-deploy, then Server will destroy the already existed Servlet object and initialize the new Servlet object with the modified Servlet Class.

Page 14: Java Ken

2. When Server getting shutdown or gets crashed then Server will destroy the Servlet object before it is shutting down.

3. When we un-deploy the Application from Server then the Server will destroy the Servlet object.

What is the difference between making the method synchronization and synchronization blocks?Java provides two basic Synchronization techniques :

1. Synchronized Methods

2. Synchronized blocks 

Synchronized Method : A Method declared with the synchronized keyword is called Synchronized Method

- To make a method Synchronized, simply add the synchronized keyword to its declaration.

There are two befits with the Synchronized Method :

First : It is not possible for two invocations of Synchronized Methods on the same Object to interleave. When one Thread is executing a Synchronized Method for an Object, all other Threads that invoke Synchronized Methods for the same Object block (suspend execution) until the first Thread is done with the Object.

Second : When a Synchronized Method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a Synchronized Method for the same Object. This guarantees that changes to the state of the Object are visible to all Threads. 

Example : Code:

public class SynchronizedCounter { private int c = 0;

public synchronized void increment() { c++; }

public synchronized void decrement() { c--;

Page 15: Java Ken

}

public synchronized int value() { return c; } }

Synchronized Block : A block of code declared with the synchronized keyword is called Synchronized Block

- To make a block of statements Synchronized, simply add the synchronized keyword to its declaration.

Example : Code:

public class SynchronizedCounter { private int c = 0;

public synchronized { c++; } }

Note : The main diffrence between Method and Block is - A Block gets executed when the control comes to it. But a Method gets executed when we are calling thatMethod only. Without method call a Method can't be executed, we have to call that Method explictily then only it gets executed.Introduction

While working with Hibernate web applications we will face so many problems in its performance due to database traffic. That to when the database traffic is very heavy . Actually hibernate is well used just because of its high performance only. So some techniques are necessary to maintain its performance. Caching is the best technique to solve this problem. In this article we will discuss about, how we can improve the performance of Hibernate web applications using caching.

The performance of Hibernate web applications is improved using caching by optimizing the database applications. The cache actually stores the data already loaded from the database, so that the traffic between our application and the database will be reduced when the application want to access that data again. Maximum the application will works with the data in the cache only. Whenever some another data is needed, the database will be accessed.

Page 16: Java Ken

Because the time needed to access the database is more when compared with the time needed to access the cache. So obviously the access time and traffic will be reduced between the application and the database. Here the cache stores only the data related to current running application. In order to do that, the cache must be cleared time to time whenever the applications are changing. Here are the contents.

1. Introduction.- First-level cache.- Second-level cache.2. Cache Implementations.- EHCache.- OSCache.- SwarmCache.- JBoss TreeCache.3. Caching Stringategies.- Read-only.- Read-Write.- Nonstriict read-write.- Transactional.4. Configuration.5. <cache> element.6. Caching the queries.7. Custom Cache.- Configuration.- Implementation :: ExampleCustomCache.8. Something about Caching.- Performance.- About Caching.9. Conclusion.

Hibernate uses two different caches for objects: first-level cache and second-level cache..

1.1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

1.2) Second-level cache

Second-level cache always associates with the Session Factory object. While

Page 17: Java Ken

running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.

2) Cache Implementations

Hibernate supports four open-source cache implementations named EHCache (Easy Hibernate Cache), OSCache (Open Symphony Cache), Swarm Cache, and JBoss Tree Cache. Each cache has different performance, memory use, and configuration possibilities.2.1) 2.1 EHCache (Easy Hibernate Cache) (org.hibernate.cache.EhCacheProvider)

* It is fast.* lightweight.* Easy-to-use.* Supports read-only and read/write caching.* Supports memory-based and disk-based caching.* Does not support clustering.

2.2)OSCache (Open Symphony Cache) (org.hibernate.cache.OSCacheProvider)

* It is a powerful .* flexible package* supports read-only and read/write caching.* Supports memory- based and disk-based caching.* Provides basic support for clustering via either JavaGroups or JMS.

2.3)SwarmCache (org.hibernate.cache.SwarmCacheProvider)

* is a cluster-based caching.* supports read-only or nonstrict read/write caching .* appropriate for applications those have more read operations than write operations.

2.4)JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)

* is a powerful replicated and transactional cache.* useful when we need a true transaction-capable caching architecture .

3) Caching Stringategies

Page 18: Java Ken

Important thing to remembered while studying this one is none of the cache providers support all of the cache concurrency strategies.3.1) Read-only

* Useful for data that is read frequently but never updated.* It is Simple .* Best performer among the all.

Advantage if this one is, It is safe for using in a cluster. Here is an example for using the read-only cache strategy.Code:

<class name="abc.mutable " mutable="true "><cache usage="read-only"/>....</class>

3.2) Read-Write

* Used when our data needs to be updated.* It’s having more overhead than read-only caches.* When Session.close() or Session.disconnect() is called the transaction should be completed in an environment where JTA is no used.* It is never used if serializable transaction isolation level is required.* In a JTA environment, for obtaining the JTA TransactionManager we must specify the property hibernate.transaction.manager_lookup_class.* To use it in a cluster the cache implementation must support locking.

Here is an example for using the read-write cache stringategy.Code:

<class name="abc.xyz" .... ><cache usage="read-write"/>….<set name="yuv" ... ><cache usage="read-write"/>….</set></class>

3.3) Nonstrict read-write

* Needed if the application needs to update data rarely.* we must specify hibernate.transaction.manager_lookup_class to use this in a JTA environment .* The transaction is completed when Session.close() or Session.disconnect()

Page 19: Java Ken

is called In other environments (except JTA) .

Here is an example for using the nonstrict read-write cache stringategy.Code:

<class name="abc.xyz" .... ><cache usage=" nonstringict-read-write"/>….</class>

3.4) Transactional

* It supports only transactional cache providers such as JBoss TreeCache.* only used in JTA environment.

Can we Serialize static variable ?

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 Serializationdoesnot 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 area. Implement the Serializable interface.b. Make sure that instance-level, locally defined state is serialized properly.c. Make sure that superclass state is serialized properly.d. 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.

difference between servlet constructor and init() method

Page 20: Java Ken

A Servlet is just like an Applet in the respect that it has an init() method that acts as a Constrcutor. 

- Since the Servlet Environment takes care of instantiating the Servlet (i.e., Container creating the insatnce of the Servlet dynamically using Class.forName()), an explicitConstructor is not needed. 

- If we want we can use Default Constructor in our Servlet, but we don't use Argumented Constructor. 

- Any initialization code you need to run should be placed in the init() method since it gets called when the Servlet is first loaded by the Servlet Container.

In the constructor it doesn't understand classes like ServletContext and ServletConfig.

It is possible to have a custom constructor for a Servlet, so long as you also add a default constructor with no arguments, but constructors are not called in the standardServlet Lifecycle. Servlets are usually instantiated by the Servlet Container using the Class.newInstance() method, with no arguments. At this point, the Servlet has no reference to its configuration or the general Servlet Context, so it cannot do any useful start-up activity. These configuration references are only available through theinit(ServletConfig) method.There are two types of Server are there 

1. Web Server2. Application Server.

Web Server : It is a Server that can handle only HTML pages. Supports HTTP protocol. When the Web Server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page (static content) or delegates the dynamic response generation to some other program such as CGI scripts or Servlets or JSPs in theApplication Server.

Application Server : It is a J2EE Sever which executes Servlets, JSP, and EJB applications and send the dynamic response to Web Server. It Exposes business logic and dynamic content to the client through various protocols such as HTTP, TCP/IP, IIOP, JRMP etc.

Examples : Web Logic, JBOSS, Websphere Application Server e.t.c.

Application Server has two Containers, They are :

1. Web Container : It executes Servlets and JSP applications. It can't handle

Page 21: Java Ken

EJB Applications.

Example : Tomcat

2. EJB Container : It executes EJB applications.

By default the Application Server and Web Containers comes with Web Server included within it.

To simplify code in JSP Expressions and Scriptlets, 9 Pre-defined variables, sometimes called Implicit Objects. 

We have access to certain Implicit Objects that are available for use in JSP documents, without being declared first. 

Below are the Predefined Variables : 

Page 22: Java Ken

1. application : This is the ServletContext as obtained via getServletConfig().getContext().

2. config : This is the ServletConfig object for this page.

3. exception : Represents the uncaught Throwable that resulted from a call to the error page.

4. out : This is the JspWriter object used to send output to the Client. 

5. page : Represents the this object for this instance of the JSP. Simply a synonym for this.

6. pageContext : Represents the PageContext object for JSP.

7. request : This is the HttpServletRequest associated with the request.

8. response : This is the HttpServletResponse associated with the response to the client. 

9. session : This is the HttpSession object associated with the Client during an HTTP request.

Page 23: Java Ken

 How can an application get to know when a HttpSession is removed ?

We can define a class which implements HttpSessionBindingListener and override the valueUnbound() method.

Hidden Comments are JSP comments. A comments that documents the JSP page but is not sent to the Client. The JSP Engine ignores a Hidden Comment, and does not process any code within Hidden Comment tags.

A comment that is sent to the Client in the viewable page source. The JSP Engine handles an output comment as un interpreted HTML text, returning the comment in theHTML output sent to the Client. We can see the comment by viewing the page source from our Web Browser.

We cannot override the _jspService() method within a JSP page. We can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like Database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().


Recommended