Saturday, February 14, 2009

Jsp Objects / Implicit Objects in Jsp

Jsp Implicit Objects:

Implicit objects in JSP are Java objects that JSP Container makes available to developers in each page. These implicit Objects are automatically available in JSP. JSP Container provides developer to access these implicit objects in their program using JavaBeans and Servlets. These objects need not be declared or instantiated by the JSP author.

They are available only within the _jspService method and not in any declaration. These objects are called implicit objects since they are automatically instantiated by the container and are accessed using standard variables. The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.

Many implicit objects available in JSP. Some of them are mentioned below:

request object in jsp

The request object has a request scope. It is an instance of the classes that implement javax.servlet.ServletRequest interface. It encapsulates the request coming from a client and uses the getParameter() method to access request parameters. It is passed to the JSP by the container as a parameter to the _jspService() method. This denotes the data included with the HTTP Request. The client first makes a request that is then passed to the server. The requested object is used to take the value from client’s web browser and pass it to the server. This is performed using HTTP request like headers, cookies and arguments.

response object in jsp

The response object has a page scope. It is an instance of the classes that implement javax.servlet.ServletResponse class. It encapsulates the response generated by the JSP to be sent to the client in response to the request. It is generated by the container and passed to the JSP as a parameter to the _jspService() method. This denotes the HTTP Response data. The result or the information from a request is denoted by this object. This is in contrast to the request object. The class or the interface name of the object response is http.HttpServletResponse. The object response is of type Javax.servlet.http. ttpservletresponse. Generally, the object response is used with cookies. The response object is also used with HTTP Headers.

Session object in jsp

The session object has a scope of an entire HttpSession. It is an instance of the javax.servlet.http.HttpSession class. It represents the session created for the requesting client, and stores objects between client's requests. The session object views and manipulates session information, such as the session identifier, creation time, and last accessed time. It also binds objects to a session, so that the user information may persist across multiple user connections.

The session object is valid only for HTTP requests.This denotes the data associated with a specific session of user. The class or the interface name of the object Session is http.HttpSession. The object Session is of type Javax.servlet.http.httpsession. The previous two objects, request and response, are used to pass information from web browser to server and from server to web browser respectively. The Session Object provides the connection or association between the client and the server. The main use of Session Objects is for maintaining states when there are multiple page requests.

jsp Out object

This denotes the Output stream in the context of page. The class or the interface name of the Out object is jsp.JspWriter. The Out object is written: Javax.servlet.jsp.JspWriter. The out object has a page scope. It is an instance of the javax.servlet.jsp.JspWriter class. The JspWriter class is the buffered version of the Printwriter class. It represents the output stream opened back to the client and provides the access to handle servlet's output stream.

jsp PageContext object

This is used to access page attributes and also to access all the namespaces associated with a JSP page. The lass or the interface name of the object PageContext is jsp.pageContext. The object PageContext is written: Javax.servlet.jsp.pagecontext The PageContext object has a page scope. It is an instance of the javax.servlet.jsp.PageContext class. It encapsulates the page-context for the particular JSP page. A pageContext instance provides access to all the namespaces associated with a JSP page. It also provides access to several page attributes such as to include some static or dynamic resource. Implicit objects are added to the PageContext automatically.

jsp Page object

The Page object denotes the JSP page, used for calling any instance of a Page's servlet. The class or the interface name of the Page object is jsp.HttpJspPage. The Page object is written: Java.lang.Object.

jsp Application object

The application object has an application scope. It is an instance of the javax.servlet.ServletContext class. It represents the context within which the JSP is executing. It defines a set of methods that a servlet uses to communicate with its servlet container. These functions include getting the MIME type, request dispatching, and writing contents to a log file. It allows the Web components in the JSP page in the application to share information. This is used to share the data with all application pages. The class or the interface name of the Application object is ServletContext. The Application object is written: Javax.servlet.http.ServletContext.

jsp config object

The config object has a page scope. It is an instance of the javax.servlet.ServletConfig class. The ServletConfig parameter can be set up in the web.xml inside the element. It uses the getInitParameter(String param) to obtain initialization parameters and the getServletContext() method to obtain the ServletContext object. This is used to get information regarding the Servlet configuration, stored in the Config object. The class or the interface name of the Config object is ServletConfig. The object Config is written Javax.servlet.http.ServletConfig.

jsp implicit object exception

The exception object has a page scope. It is an instance of the java.lang.Throwable class. It refers to the runtime exception that resulted in the error-page being invoked. This is available only in an error page, i.e., a page that has isErrorPage=true in the page directive.

Servlet LifeCycle / Life Cycle of a Servlet

Servlet: Servlets are server side java components which provide a powerful mechanism for developing server side java programs. Servlets are mainly used to develop Web-based applications.

Servlet lifecycle

Servlet lifecycle is handled by the servlet container. Servlets are managed components and are managed by web(servlet) container. Servlet life cycle management is the most important responsibility of web container. A servlet is managed through a well defined life cycle that defines how it is loaded, instantiated ad initialized, handles requests from clients and how it is taken out of service.

Syntax:

public void init(ServletConfig config) throws ServletException
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()

The servlet life cycle consists of four steps:

1. Instantiation
2. Initialization(init())
3. request handling (service())
4. end of service (destroy())

Instantiation (Loading the Servlet)


During this step, web(servlet) container loads the servlet class and creates a new instance of the servlet. The container can create a servlet instance at container startup or it can delay it until the servlet is needed to service a request.


Initialization


During initialization stage of the Servlet life cycle, the web(servlet) container initializes the servlet instance by calling the init() method. The container passes an object implementing the ServletConfig interface via the init() method. This configuration object allows the servlet to access name-value initialization parameters from the web application’s deployment descriptor web.xml file. The container guarantees that the init() method will be called before the service() method is called.


The init() method is typically used to perform servlet initialization, creating or loading objects that are used by the servlet in the handling of its requests. The init() method is commonly used to perform one time activity that is it will be called only once in the life time of the servlet. One of the most common use of init() method is to setup the database connection or connection pool.

Request handling


After a servlet is properly initialized, it is ready to handle the client requests. If the container has a request for the servlet, it calls the servlet instance’s service() method. The request and response information is wrapped in ServletRequest and ServletResponse objects respectively, which are then passed to the servlet's service() method. In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.


Service() method is responsible for processing the incoming requests and generating the response. The service phase of the Servlet life cycle represents all interactions with requests until the Servlet is destroyed. The Servlet interface matches the service phase of the Servlet life cycle to the service() method. The service() method of a Servlet is invoked once per a request and is responsible for generating the response to that request.


The Servlet specification defines the service() method to take two parameters: a javax.servlet.ServletRequest and a javax.servlet.ServletResponse object. These two objects represent a client's request for the dynamic resource and the Servlet's response to the client.

By default a Servlet is multi-threaded, meaning that typically only one instance of a Servlet1 is loaded by a JSP container at any given time. Initialization is done once, and each request after that is handled concurrently2 by threads executing the Servlet's service() method.

End of service() method


When the servlet container determines that a servlet should be removed from service, it calls the destroy () method of the Servlet instance to allow the servlet to release any resources it is using. The servlet container can destroy a servlet because it wants to conserve some memory or server itself is shutting down.


Before the servlet container calls the destroy() method, it allows any threads that are currently running in the service method of the servlet to complete execution, or exceed a server defined time limit. Once the destroy() method has completed, the container will release the servlet instance for garbage collection. If it needs another instance of the servlet to process requests it creates the new instance of the servlet and life cycle starts again.

Destroy() method is used to release any resources it is using. The most common use of destroy() method is to close the database connections. The destruction phase of the Servlet life cycle represents when a Servlet is being removed from use by a container. The Servlet interface defines the destroy() method to correspond to the destruction life cycle phase. Each time a Servlet is about to be removed from use, a container calls the destroy() method.

String Class & StringBuffer

Difference between StringBuffer and String Class :

A String object is immutable. A StringBuffer object is mutable. StringBuffer object is like a String object but can be modified. A string buffer is a sequence of characters but the length and content of the sequence can be changed through certain method calls. The principal operations on a StringBuffer are append() and insert() methods. The append() method adds characters at the end of the buffer and the insert() method adds the characters at a specified location.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Every string buffer has a capacity. As long as the length of the character sequence does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If there is an overflow, the string buffer is automatically made larger.

Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.

String str = new String ("Item"); str += "Found!!";

If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:

StringBuffer str = new StringBuffer ("Item");
str.append("Found!!");

Normally we assume that the first part of the code is more efficient because they think that the second part, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.
The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String.

To trace that,we must see the generated bytecode from our two examples. The bytecode for the example using String looks like this:

0 new #7
3 dup
4 ldc #2
6 invokespecial #12
9 astore_1
10 new #8
13 dup14 aload_1
15 invokestatic #23
18 invokespecial #13
21 ldc #1
23 invokevirtual #15
26 invokevirtual #22
29 astore_1

The bytecode at locations 0 through 9 is executed for the first line of code, namely:

String str = new String("Stanford ");

Then, the bytecode at location 10 through 29 is executed for the concatenation:

str += "Lost!!";

The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.

After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done withthe call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer
object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are veryexpensive.

In summary, the two lines of code above result in the creation of three objects:
A String object at location 0 A StringBuffer object at location 10 A String object at location 26

Now, let's look at the bytecode generated for the example using StringBuffer:

0 new #8
3 dup4 ldc #2
6 invokespecial #13
9 astore_110 aload_1
11 ldc #1
13 invokevirtual #
15 16 pop

The bytecode at locations 0 to 9 is executed for the first line of code:

StringBuffer str = new StringBuffer("Stanford ");

The bytecode at location 10 to 16 is then executed for the concatenation:

str.append("Lost!!");

Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.

In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.

StringBuilder StringBuffer

StringBuilder vs StringBuffer

StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands (buffer size) as needed. Related classes: String, CharSequence.

StringBuilder was added in Java 5.0. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster. No imports are necessary because these are both in the java.lang package.

StringBuffer and StringBuilder methods and constuctors

Assume the following code:

StringBuffer sb = new StringBuffer();
StringBuffer sb2;
int i, offset, len;
char c;
String s;
char chararr[];

Constructors

sb = new StringBuffer(); // Creates new, empty, StringBuffer
sb = new StringBuffer(n); // Creates new StringBuffer of size n
sb = new StringBuffer(s); // Creates new StringBuffer with initial value s

Using StringBuffer

sb2 = sb.append(x) //appends x (any primitive or object type) to end of sb.
sb2 = sb.append(chararr, offset, len) //appends len chars from chararr starting at index offset.
sb2 = sb.insert(offset, x) // inserts x (char, int, String, ...) at position offset.
sb.setCharAt(index, c) // replaces char at index with c

Deleting from StringBuffer

sb2 = sb.delete(beg, end) //deletes chars at index beg thru end.
sb.setLength(n) // Sets the length of the content to n by either truncating current content or extending it with the null character ('\u0000').
Use sb.setLength(0); to clear a string buffer.

Extracting Values from StringBuffer

c = sb.charAt(i) // char at position i.
s = sb.substring(start) // substring from position start to end of string.
s = sb.substring(start, end) // substring from position start to the char before end.
s = sb.toString() // Returns String.

Searching in StringBuffer

i = sb.indexOf(s) //Returns position of first (leftmost) occurrence of s in sb.
i = sb.lastIndexOf(s) // Returns position of last (rightmost) occurrence of s in sb.
Misc
i = sb.length() // length of the string s.
sb2 = sb.reverse()

Converting values in StringBuffer

An interesting aspect of the append() and insert() methods is that the parameter may be of any type. These methods are overloaded and will perform the default conversion for all primitive types and will call the toString() method for all objects.

Chaining calls in StringBuffer

Some StringBuffer methods return a StringBuffer value (eg, append(), insert(), ...). In fact, they return the same StringBuffer that was used in the call. This allows chaining of calls. Eg,

sb.append("x = ").append(x).append(", y = ").append(y);

Efficiency of StringBuffer compared to String

Because a StringBuffer object is mutable (it can be changed), there is no need to allocate a new object when modifications are desired. For example, consider a method which duplicates strings the requested number of times.

// Inefficient version using String.

public static String dupl(String s, int times) {
String result = s;
for (int i=1; i result = result + s;
}
return result;
}

If called to duplicate a string 100 times, it would build 99 new String objects, 98 of which it would immediately throw away! Creating new objects is not efficient. A better solution is to use StringBuffer.

// More efficient version using StringBuffer.

public static String dupl(String s, int times) {
StringBuffer result = new StringBuffer(s);
for (int i=1; i result.append(s);
}
return result.toString();
}

This creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer will automatically expand as needed. These expansions are costly however, so it would be better to create the StringBuffer the correct size from the start.

// Much more efficient version using StringBuffer.

public static String dupl(String s, int times) {
StringBuffer result = new StringBuffer(s.length() * times);
for (int i=0; i result.append(s);
}
return result.toString();
}

Because StringBuffer is created with the correct capacity, it will never have to expand. There is no constructor which allows both an initial capacity to be specifed and an initial string value. Therefore the loop has one extra iteration in it to give the correct number of repetitions.

forward n sendRedirect

Difference Between sendRedirect() and Forward() :

Forward( ) :

javax.Servlet.RequestDispatcher interface.

* RequestDispatcher.forward( ) works on the Server.
* The forward( ) works inside the WebContainer.
* The forward( ) restricts you to redirect only to a resource in the same web-Application.
* After executing the forward( ), the control will return back to the same method from where the forward method was called.
* The forward( ) will redirect in the application server itself, it does'n come back to the client.
* The forward( ) is faster than Sendredirect( ) .

To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain RequestDispatcher Object. The Servlet technology provides in three ways.

1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a String containing the path of the other resources, path is relative to the root of the ServletContext.

RequestDispatcher rd=request.getRequestDispatcher ("secondServlet");
Rd.forward(request, response);

2. getRequestDispatcher( ) of the javax.Servlet.Request interface , the path is relative to current HttpRequest.

RequestDispatcher rd=
getServletContext( ).getRequestDispatcher("servlet/secondServlet"); Rd.forward(request, response);

3. By using the getNameDispatcher( ) of the javax.Servlet.ServletContext interface.

RequestDispatcher rd=
getServletContext( ).getNameDispatcher("secondServlet");
Rd.forward(request, response);

Sendredirect( ) :

javax.Servlet.Http.HttpServletResponce interface

* RequestDispatcher.SendRedirect( ) works on the browser.
* The SendRedirect( ) allows you to redirect trip to the Client.
* The SendRedirect( ) allows you to redirect to any URL.
* After executing the SendRedirect( ) the control will not return back to same method.
* The Client receives the Http response code 302 indicating that temporarly the client is being redirected to the specified location , if the specified location is relative , this method converts it into an absolute URL before redirecting.

SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen.

Response. SendRedirect( "absolute path");

Absolutepath – other than application , relative path - same application.

Conclusion:

forward() runs on the server side where as sendRedirect runs both on the client as well as on the server side thats why the response generated by sendRedirect() is slow as compared to rd.forward().

sendRedirect() you can forward the request to any web application either in the same server or to the another one. Incase of forward() the request has to be forwarded to the same web application.

forward() method holds the previous request and response objects while using sendRedirect(),it will create fresh request and response objects.

sendRedirect() always sends a header back to the client/browser, this header then contains the resource(page/servlet) which you wanted to be redirected. the browser uses this header to make another fresh request. sendRedirect has a overhead since its like any other Http request being generated by ur browser.

response.sendRedirect() sends a response to the browser asking it to load another page, whereas in the case of RequestDipsatcher.forward() control is transferred to another servlet or jsp within the server.

Using sendRedirect() on one server, we call redirect a call to a resource on located on different server which is not possible using forward().

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container.

sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

Calling other Servlets or other resources

Calling other Servlets or other resources
using a RequestDispatcher
('include' and 'forward')

To have your servlet access another resource, such as another servlet, a JSP page or a CGI script, you can either:

* Have the servlet make an HTTP request (this is a general Java programming language skill).

* Make a request for the resource using a RequestDispatcher object, if the resource is available from the server that is running the servlet.

To gain access to a RequestDispatcher object, use the ServletContext object's getRequestDispatcher() method. The getServletContext() method should be called on the ServletConfig reference (config) stored during the servlet's init() method:

config.getServletContext().getRequestDispatcher(url)

The getRequestDispatcher method takes the requested resource's relative URL as an argument. The format of this argument is a slash ("/") followed by one or more slash-separated directory names, and ending with the name of the resource. The URL must be for a resource currently available on the server that is running the servlet. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, this method will return null. The Kinabaloo Web Server can handle all the main resource types, such as HTML and JSP pages, and other servlets.



Forwarding a Request

Once you have the RequestDispatcher object, you can pass the responsibility for responding to the client request to another resource. Forwarding is useful, for example, when the servlet processes the request but the response is generic so it can be handed off to another resource.

A servlet might, for example, handle a user's credit card information when a user places an order, then pass the client request to another servlet that returns a "Thank you" page. In the Duke's Bookstore example, BookStoreServlet gets (creates if necessary) the user session, then has the request dispatcher return the front page of the bookstore:

public class BookStoreServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// Get the dispatcher; it will send the main page to the user

RequestDispatcher dispatcher = config.getServletContext().getRequestDispatcher("/bookstore.html");

if (dispatcher == null) {

// No dispatcher means the resource (bookstore.html in this case) can not be found

response.sendError(response.SC_NO_CONTENT);

} else {

// Send the user the bookstore's opening page

dispatcher.forward(request, response);

}

...



Note that the ServletConfig object config was obtained during the init(ServletConfig config) method of the servlet.

Remember that the forward method should be used to give another resource full responsibility for replying to the user. If you have already accessed a ServletOutputStream or PrintWriter object, you cannot use this method - it will throw an IllegalStateException in these circumstances.

If you have already started replying to the user by accessing a PrintWriter or ServletOutputStream, you must use the include method instead.



Including a Request

The include(URL) method of the RequestDispatcher interface allows the calling servlet to respond to the client, and also allows another resource to send part of the reply. The servlet can use the PrintWriter and ServletOutputStream objects both before and after calling the include method.

You must keep in mind, however, that the called (included) resource should not try to set any http headers in the client response (if the resource tries to set headers, the headers are not guaranteed to be set).

The following example shows what a ReceiptServlet might look like if, instead of merely thanking the user for the order, it also included an order-summary. The following example thanks the user for the order, then includes the output of an order summary servlet in the output:

public class ReceiptServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

// Process a customer's order

...

// Thank the customer for the order

res.setContentType("text/html");

PrintWriter toClient = res.getWriter();

toClient.println("");

toClient.println("

Thank you for your order!

");

// Get the request-dispatcher, to send an order-summary to the client

// (OrderSummary is a servlet)

RequestDispatcher summary = config.getServletContext().getRequestDispatcher("/OrderSummary");

// Have the servlet summarize the order. Skip summary on error.

if (summary != null) {

try {

summary.include(req, res);

} catch (Exception e) {...}

}

// and finish the response page :

toClient.println("

Come back soon!

");

toClient.println("");

toClient.close();

}

}

10 sample FAQs - coreJava

1 what is a transient variable
A transient variable is a variable that may not be serialized.

2 which containers use a border Layout as their default layout
The window, Frame and Dialog classes use a border layout as their default layout.

3 Why do threads block on I/O
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.

4 How are Observer and Observable used
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that i...

5 What is synchronization and why is it important
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a ...

6 Can a lock be acquired on a class
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object..

7 What's new with the stop(), suspend() and resume() methods in JDK 1.2
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

8 Is null a keyword
The null value is not a keyword.

9 What is the preferred size of a component
The preferred size of a component is the minimum component size that will allow the component to display normally.

10 What method is used to specify a container's layout
The setLayout() method is used to specify a container's layout.