Wednesday, September 28, 2005

What is Cookie ? What is its purpose ?

Cookie is nothing more than a little piece of data(a name/value string pair) exchanged between the client and the server. The server sends the cookies to the client, and the client returns the cookie when the client makes another request. Cookie exchange is automatic.

By default cookies stay alive only as long as a session exists; once the client quits his browser, the cookies disappears. That’s how the “JSESSIONID” cookie works.

But we can make a cookie to stay alive even AFTER the browser shuts down. In this way our web application can still get the cookie information even though the session with that client is long gone.

If we set cookies programatically we don’t have to bother whether the user restarted his browser and hasn’t been on the site for a week.

Cookie Purpose: Session Tracking

Http Cookie is the most used session tracking mechanism and is required to be supported by all servlet containers.

Specification dictates that the session tracking cookie must be “JSESSIONID” cookie.

Why do u use Session Tracking in HttpServlet ?

The HTTP protocol uses stateless connections. The client browser makes a connection to the server, sends the request, gets the response and closes the connection. In other words the connection exists only for a single request/response.

Because the session doesn’t persist, the container doesn’t recognize that client making a second request is the same client from a previous request. As for as the container is concerned each request is from a new client.

Hence to maintain a conversational state across multiple requests from the same client we use HttpSession Objects for Session Tracking.

From Spec

SRV.7.1.1 Cookies
Session tracking through HTTP cookies is the most used session tracking mechanism and is required to be supported by all servlet containers.

What is the difference between a Servlet and a CGI?


When CGI ( Common Gateway Interface) script is invoked, the server creates a separate process for it. The server has a limitation on the number of process it can create. When the request is too high the server efficiency comes down.

The most popular platform for writing CGI script is perl. The server needs to load the CGI script and perl interpreter for every incoming request that it receives. This brings down the efficiency of the server.

Unlike CGI script the servlet initialization code is executed only once. In the case of servlets, each request is handled by a separate thread by container in the web browser. This helps web servers to be more efficient by preventing creation of unnecessary process.

What is a Servlet? What is a web component?

From Spec:

A servlet is a Java technology-based Web component, managed by a container, that generates dynamic content. Like other Java technology-based components,servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.

First, when most people refer to a servlet, they actually mean an object of class HttpServlet. When I refer to a servlet, think "HttpServlet".

A servlet is an object who has the ability to communicate with a web browser. It receives requests from a browser. These requests can ask for a web page, or they can send data that a user entered on a web page. To code one of these, all you have to do is declare a class that extends HttpServlet, override the doGet and/or doPost method. It is in these methods that you add your own code(Business Logic) to do whatever you want. To send a webpage back to the browser, all you need to do is write HTML code as Strings inside println statements.

A web component is either a servlet or a JSP page

Tuesday, September 27, 2005

What will happen if I call destroy method from service method?


Calling destroy() method from service [ doGet (or) doPost ] method is just like calling another method . There will be no effect on the life cycle of the servlet until destroy is called by the Container. Means destroy() will work like any other ordinary method till it is called by Container for shutting down the servlet.

The container will execute whatever logic is in the destroy() method, and then return the control back to the service method, just like it would with any other method call.

The point to remember here is that the destroy() method does not actually destroy the servlet as the name would imply. Instead, it is a place for you to put logic that should run when the container is preparing to destroy the servlet instance. For instance, if you needed to cleanup resources, this would be the place to do it.

Note:

You should not call the life-cycle methods yourself. They are meant to be called by the container. The one who calls the servlet's destroy is the Container NOT the programmer. When the Container did so, then the servlet is available (eligible) for garbage collection.

Monday, September 26, 2005

When the servlet A forwards to another servlet B to generate response via RequestDispatcher.forward method, which method (doGet or doPost) of servlet B does the container invoke?

To be precise - the method GET or POST is set in a header that is part of the original request - the servlet that the request is being forwarded to will examine the request and use the appropriate method. You can change the method by means of a custom request wrapper if necessary.

What are the differences between method getRequestDispatcher(String path) and getNamedDispatcher(String path) in ServletContext Class?


NamedDispatcher

Returns a RequestDispatcher object that acts as a wrapper for the named servlet.

getNamedDispatcher(String path) method takes the name of the Servlet as parameter which is declared via Deployment descriptor.

Example

Deployment Descriptor

------------------------------------------------------------------------------------

servlet

servlet-name FirstServlet /servlet-name

servlet-class com.example.ServletExample /servlet-class

/servlet


------------------------------------------------------------------------------------


RequestDispatcher dispatch = request.getNamedDispatcher(“FirstServlet”);

dispatch.forward(request, response);

Note: A servlet instance can determine its name using servletConfig.getServletName(); This method returns the name of the class that implements HttpServlet class.


RequestDispatcher:

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

RequestDispatcher dispatch = request.getRequestDispatcher("/tes");

Here “/tes represents the url-pattern element value of the servlet class.

servlet-mapping

servlet-name Test /servlet-name

url-pattern /tes /url-pattern

/servlet-mapping


It represents the path of the servlet class. Since both the base as well as target Servlet are in the same package structure by just specifying the url-pattern element value we will be able to access the target servlet.


We shouldn’t specify the entire path like

String str = “/WEB-INF/classes/com/example/posr/Test”

RequestDispatcher dispatch = request.getRequestDispatcher(str);

 To forward a request to a jsp page we use

RequestDispatcher dispatch = request.getRequestDispatcher("/TestJspOne.jsp");

Here ”/TestJspOne.jsp” the slash denotes the Jsp page is at the root of the application.

In the interface javax.servlet.RequestDispatcher, what is the difference between the forward(ServletRequest request, ServletResponse response) method and the include(ServletRequest request, ServletResponse response) method?


Forward will transfer the control to the target resource(servlet (or) JSP), without returning the control to the caller.


Include will
transfer the control to the target resource(servlet (or) JSP), but then returning the control to the caller after the execution.

Tuesday, September 20, 2005

Explain idempotent and non-idempotent.

Idempotent means the same request can be made more than once without causing negative consequences on the Server.

In Non-Idempotent Scenario the data submitted in the body of the POST might be destined for a transaction that can’t be reversed. Hence care has to be taken in the application logic.

IDEMPOTENT ==> GET, HEAD, PUT, DELETE, OPTIONS, TRACE

NON-IDEMPOTENT ==> POST

CONNECT
Specification reserves the method name CONNECT for use with a proxy that can dynamically switch to being a tunnel (e.g. SSL tunneling

Http Spec 1.1

What are the different Http methods available.

  1. Get
  2. Post
  3. Head
  4. Trace
  5. Put
  6. Delete
  7. Options
  8. Connect
Http Methods Notes

Difference between get() and post() methods ?

GET is used to get something back from the server.

With POST you can request something at the same time send form data to the server

If you are using GET method you are limited to a maximum of 2048 characters(Minus the number of characters in the actual path)

POST is however not limited by the size of the URL for submitting name/value pairs, because they are transferred in the Header and not the URL.

Note:

Internet Explorer has a maximum URL length of 2083 characters, with a maximum path length of 2048 characters. This limit applies to both GET and POST.

The data you send with the GET is appended to the URL up in the browser bar, so whatever you send is exposed. Hence it is a security threat.

SERVLET LIFE CYCLE LISTENERS AND EVENTS

The Java Servlet 2.4 specification provides mechanisms for notifying application code about events in the Web application life cycle. Servlet life cycle events include creation and destruction of a servlet context or an HTTP session, and creation, modification, or removal of servlet context attributes and HTTP session attributes. Furthermore, any object may be notified when it is bound to or unbound from an HTTP session attribute.

Application life cycle listeners are often used to provide consistent, managed access to other resources. For example, consider a set of servlets within the same Web application that share a database connection on a single server. To improve performance, some servlets save a database connection as a servlet context attribute, and reuse it across multiple servlet service invocations for multiple clients. When the application is shut down, the database connection should be closed. To manage the database connection, an application developer creates a servlet context event listener. The listener class opens the database and initializes a context attribute with a reference when the application is deployed. The listener class also closes the database when the application is undeployed.

To create a life cycle listener, an application developer writes classes that implement listener interfaces for life cycle events, and the deployer(web.xml) configures these classes to be used by a Web application. The class files for the listeners are configured using the deployment descriptor web.xml. Each Web application can have multiple listeners of each type.

The interfaces provided for listening to Web application life cycle events are:

  • javax.servlet.ServletContextListener. The methods in this interface are called when a new servlet context(application) is created or just before the servlet context is destroyed. All ServletContextListeners are notified of context initialization before any filter or servlet in the web application is initialized. All servlets have been destroy()ed before any ServletContextListeners are notified of context destruction.
  • javax.servlet.http.HttpSessionListener. The methods in this interface are called when an HTTP session is created or destroyed. The call to the method occurs before the session is invalidated.
  • javax.servlet.http.HttpRequestListener. The methods in this interface are called when a request is made to a servlet in the web application.
  • javax.servlet.ServletContextAttributeListener. The methods in this interface are called when a servlet context attribute is created, modified, or removed from a servlet context.
  • javax.servlet.http.HttpSessionAttributeListener. The methods in this interface are called when a session attribute is created, modified, or removed from an HTTP session.
  • javax.servlet.ServletRequestAttributeListener. The methods in this interface are called when a servlet request attribute is created, modified, or removed from a servlet context.
  • javax.servlet.http.HttpSessionBindingListener. The methods in this interface are called when an object of an attribute class is bound or unbound from an HTTP session.
  • javax.servlet.http.HttpSessionActivationListener. The methods in this interface are called when an object of an attribute class has to be notified when the session to which they’re bound is migrated to and from another session.

NOTE: To receive notification of Life Cycle Events, the implementation class must be configured in the deployment descriptor for the web application, barring(except) HttpSessionBindingListener and HttpSessionActivationListener.

Configuring Listener Classes

At deploy time, listener classes are declared using the listener tag in the deployment descriptor file, web.xml. The Web container is responsible for creating and providing callbacks to instances of the listener classes.

web-app

display-name JunWebApp /display-name

description

Demonstrate resource listing and life cycle listeners

/description

listener

listener-class

com.edu.LifeCycleServletContextListener

/listener-class

/listener

listener

listener-class

com.edu.LifeCycleHttpSessionListener

/listener-class

/listener

...


Scope

Event

Listener Interface and Event Class

Servlet Context

contextInitialized()

contextDestroyed()

ServletContextListener, ServletContextEvent

attributeAdded()

attributeRemoved()

attributeReplaced()

ServletContextAttributeListener, ServletContextAttributeEvent

HTTP Session

sessionCreated()

sessionDestroyed()

HttpSessionListener, HttpSessionEvent

sessionDidActivate()

sessionWillPassivate()

HttpSessionActivationListener, HttpSessionEvent

attributeAdded()

attributeRemoved()

attributeReplaced()

HttpSessionAttributeListener, HttpSessionBindingEvent (note the class name !)

valueBound()

valueUnbound()

HttpSessionBindingListener (note, interface must be implemented by attribute class !), HttpSessionBindingEvent

Servlet Request

requestInitialized() requestDestroyed

ServletRequestListener, ServletRequestEvent

attributeAdded()

attributeRemoved()

attributeReplaced()

ServletRequestAttributeListener, ServletRequestAttributeEvent

Thread safety

Thread safe

  • local variables
  • request attributes

Not Thread safe

  • instance variables
  • class variables
  • session attributes
  • context attributes

What is MIME. Explain in detail?

MIME stands for Multipurpose Internet Mail Extension.

It represents the content-type response header value. The MIME type tells the browser what kind of data the browser is about to receive so that the browser will know how to process it.

Example: response.setContentType("text/html");

Here text/html is the response header value.

when would a servlet be destroyed ?

Servlet container shutting down definitely calls the destroy method of servlet. If servlet container needs some free memory, it would call destroy method for those servlets whose service method have exited or after a timeout period has passed.

Before the webapp is reloaded or stopped and before ServletContextEvent of contextDestroyed method of any ServletContextListener interface is fired.


Monday, September 19, 2005

Does a session becomes invalid as soon as the user closes all browser windows ?

Closing or terminating windows will not terminate the session.

A session can be ended either programatically by calling invalidate() method (or) timed out simply. When the user closes all the browser windows the session started by the particular request will not come to an end immediately. The server will wait until the session times out. But one major point to note here is that once when the browser window with which the request was made is closed the same session cannot be continued further with IE browser but possible with FireFox.

You can find more about this

Here

From Spec

In the HTTP protocol, there is no explicit termination signal when a client is no longer active. This means that the only mechanism that can be used to indicate whena client is no longer active is a timeout period.

Friday, September 16, 2005

Explain the difference between Web Server and Web Container. What is the purpose of a Container.


Container is a java application in which your web components such Servlets and JSP’s are deployed. Its purpose is to provide


  • Communication Support
  • Lifecycle Support
  • Multi-Threading Support
  • Declarative Support
  • JSP Support


Look at page 41 in HFSJ book for brief explanation.

When you think of a web-server, you need to think about HTTP. A web-server talks HTTP. You can think of the web server as receiving the HTTP request from the client (browser) and if the request is asking for some dynamic content then the web server passes the request to the helper application thats part of the web server which is nothing but the container.

Some of the main jobs of the container would be to create and initialize servlets, manage their life cycle, find out which resource should serve a client request, allocate a thread for each incoming request and manage other web components like JSP's , filters (their life-cycle) etc.

The container then returns the response from the resource to the web-server. The web-server would format to actual HTTP response (header and body) and send it to the client.

Thursday, September 15, 2005

Is the RequestDispatcher returned by getRequestDispatcher(java.lang.String path) of ServletContext class thread-safe.


If you declare it in (and keep it local to) the service method (doPost, doGet...) it is.

If you declare it as an instance variable and set it's value in the service method, no.

Consider the following:

public class ServletX extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
req.getSession().setAttribute("key", new X());
req.getSession().setAttribute("key", new X());
req.getSession().setAttribute("key", "x");
req.getSession().removeAttribute("key");
}
}

and given a Listener class

public class X implements HttpSessionBindingListener {
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("B");
}

public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("UB");
}
}

Which logging output would be generated by an invocation of the doGet method?
Given answer: BBUBUB
Please explain the output?


req.getSession().setAttribute("key", new X());----->B

req.getSession().setAttribute("key", new X());----->B
Since this line replaces the previous set "key" in the session it will also print UB because the previously set X object is unbound.

req.getSession().setAttribute("key", "x");
This will print UB since the X object is unbound.

req.getSession().removeAttribute("key");
This wont print anything because the String "x" is removed as a result of this method call.

So the output would be BBUBUB.

Before doing a RequestDispatcher forward, what are the attributes set by the container in the request object?

What are the attributes set by the container before doing an include?

Also, what is the purpose of setting these? I suppose these are already accessible through the request object. For example, the forwarded resource may use request.getQueryString() instead of request.getAttribute("javax.servlet.forward.query_string").

The attributes are:
javax.servlet.forward.request_uri
javax.servlet.forward.context_path
javax.servlet.forward.servlet_path
javax.servlet.forward.path_info
javax.servlet.forward.query_string

and for include

javax.servlet.include.request_uri
javax.servlet.include.context_path
javax.servlet.include.servlet_path
javax.servlet.include.path_info
javax.servlet.include.query_string


When calling RequestDispatcher.forward, we can specify new query parameters in a query string or override the existing query parameters. The getQueryString method on the forward page returns this query string. But request.getAttribute("javax.servlet.forward.query_string") returns the original query parameters.

Example:

If you call a Test servlet as:

http://localhost:8080/app/Test/?x=100

In the servlet,

RequestDispatcher rd = request.getRequestDispatcher("/Target?xyz=1");
rd.forward(request, response);

In the forwarded Target servlet,

request.getQueryString(); // prints "xyz=1"

But request.getAttribute("javax.servlet.forward.query_string"); // prints "x=100"

You can learn about this Here

Normally only 1 instance of a servlet is created, but if we configure the web server to have multiple instance say 10 instances of a servlet A, then in that situation, how many times will the init() method be called? 1 or 10 times?


Each servlet put into service via a declaration will have its init method called with the servlet config containing any init params for that declaration.

Each servlet declaration gets its own instance of a servlet regardless of whether an instance of that same servlet has already been created as a result of a different servlet declaration.

Here's what the Servlet Spec (2.4) says:

"For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance."

the servlet container must use only one instance per servlet declaration

Hence if we have 10 servlet declaration of the same Servlet we have 10 instance of the same Servlet with every instance having their int() method called 0nce.

My web.xml :

servlet
servlet-name Ch3 Beer /servlet-name
servlet-class BeerSelect /servlet-class
/servlet

servlet-mapping
servlet-name Ch3 Beer /servlet-name
url-pattern /SelectBeer.do /url-pattern
/servlet-mapping

servlet
servlet-name Ch31 Beer /servlet-name
servlet-class BeerSelect /servlet-class
/servlet

servlet-mapping
servlet-name Ch31 Beer /servlet-name
url-pattern /SelectBeer1.do /url-pattern
/servlet-mapping


Note the items above bolded.They are different.When u access the servlet by using "/SelectBeer.do" one instance of "BeerSelect" will be created by the container.When u access the same servlet using "/SelectBeer1.do" another instance will be created.Console output is conforming the same!!

While experimenting with session I noticed the following. If I call a certain servlet from Firefox, we have a sessionid and let's say its value is 1. If I call the same Servlet from a new IE window, I get a new sessionid ='2'. If I then open the same again in new Firefox window, the sessionid was the same as the first call; '1'. However, everytime I open a new IE window, I get a new sessionid value, unlike FireFox. What is the reason for such an inconsistency?


You can find the answer here

why do we have init method ?
After all why can't we make use of servlet constructor for initilization ?

You can't make use of the constructor because the container calls it and therefore you can't pass any parameters to the constructor. Also at the point the constructor is called the class is not really a Servlet because it doesn't have a reference to the ServletConfig, which provides all the initialisation parameters etc.


Why cant a container call constructor having parameters?

As it is the container that manages a servlets lifecycle, you must define a generic way of working for all servlets. You can't use the constructor because otherwise you would have to modify the container to tell him to instantiate this particular servlet.