Tuesday, March 20, 2012

JSP Interview Questions 2

How does JSP handle run-time exceptions?

You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=\"true\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

What are the implicit objects?

Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception.


Why are JSP pages the preferred API for creating a web-based client program?

Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.



Is JSP technology extensible?


Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.


What is the page directive is used to prevent a JSP page from automatically creating a session?

<%@ page session="false">

What is the difference between RequestDispatcher and sendRedirect?

RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.

JSP Interview Questions 1

Explain the life-cycle mehtods in JSP?

THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.


Difference between forward and sendRedirect?

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. When a 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.

What are implicit objects? List them?

Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
    * request
    * response
    * pageContext
    * session
    * application
    * out
    * config
    * page
    * exception

What is a Declaration?
A declaration declares one or more variables or methods for use later in the JSP source file.

A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.

<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>

 What is a Expression?

An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression


What is a Scriptlet?

A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can

1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also Expression).

3.Use any of the JSP implicit objects or any object declared with a tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.

Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.










What are the different scope valiues for the ?

The different scope values for are
1. page
2. request
3.session
4.application



What is a output comment?
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.

JSP Syntax


Example 1


Displays in the page source:



What is a Hidden Comment?
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 hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.

You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>

Examples
<%@ page language="java" %>

A Hidden Comment

<%-- This comment will not be visible to the colent in the page source --%>


 

Sunday, March 4, 2012

Servlet Interview Question

 What is a Servlet?

Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was used to provide server side capabilities for web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues made it less and less desirable among people who wanted enterprise class scalable applications. Java Servlets was the solution to all of CGIs problems. Built from ground up using Sun's java technology, servlets provide excellent framework for server side processing. They are an integral part of almost all J2EE applications

  What are the types of Servlet?

There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides http protocl specific functionality.

What are the differences between HttpServlet and Generic Servlets?

GenericServlet defines a generic, protocol-independent servlet whereas HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site that uses the Http Protocol.

What are the differences between a Servlet and an Applet?
  •  Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser.
  •   Applets have GUI interface but there is no GUI interface in case of Servlets.
  •   Applets have limited capabilities whereas Servlets are very poweful and can support a wide variety of operations
  •   Servlets can perform operations like interacting with other servlets, JSP Pages, connect to databases etc while Applets cannot do all this.

  What are the differences between the doGet and doPost methods?
  •   Get sends information from the browser to the Servlet as contents appended to the query string in the URL while Post uses hidden variables
  •   Because of the above point, post is a lot safer than get
  •   Get has a size limitation - i.e., we can send only approximately 1 Kb of data while Post can send a singnificantly higher amount of data
  •   Get is the most common type of sending data from a browser to a servlet, while Post is gaining popularity because of its size and safety which is better than the get.

  What are the different methods present in a HttpServlet?

The methods of HttpServlet class are :

* doGet() - To handle the GET, conditional GET, and HEAD requests
* doPost() - To handle POST requests
* doPut() - To handle PUT requests
* doDelete() - To handle DELETE requests
* doOptions() - To handle the OPTIONS requests and
* doTrace() - To handle the TRACE requests

Apart from these, a Servlet also contains init() and destroy() methods that are used to initialize and destroy the servlet respectively. They are not any operation specific and are available in all Servlets for use during their active life-cycle.


  What are the advantages of Servlets over CGI programs?

Java Servlets have a number of advantages over CGI and other API's. Some are:

1. Platform Independence - Java Servlets are 100% pure Java, so it is platform independent. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server without modification code. Platform independency of servlets provide a great advantages over alternatives of servlets.

2. Performance - Anyone who has used CGI would agree that Servlets are much more powerful and quicker than CGI. Because the underlying technology is Java, it is fast and can handle multiple request simultaneously. Also, a servlet gets initialized only once in its lifetime and then continues to serve requests without having to be re-initialized again, hence the performance is much higher than CGIs.

3. Extensibility - Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.

Also, in terms of Safety & Security Servlets are superior when compared to CGI.

  What are the lifecycle methods of Servlet?

The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:

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

The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps:

1. If an instance of the servlet does not exist, the web container
* Loads the servlet class.
* Creates an instance of the servlet class.
* Initializes the servlet instance by calling the init method.
2. The container invokes the service method, passing request and response objects.
3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.

What are the type of protocols supported by HttpServlet?

It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

  What is ServletContext?

ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.

What is meant by Pre-initialization of Servlet?

When servlet container is loaded, all the servlets defined in the web.xml file do not get initialized by default. When the container receives a request to hit a particular servlet, it loads that servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In this case, the servlet is loaded when context is loaded. You can specify 1 in between the tag in the Web.xml file in order to pre-initialize your servlet

What mechanisms are used by a Servlet Container to maintain session information?

Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.

What do you understand by servlet mapping?

Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url patterns. For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.

What interface must be implemented by all Servlets?

The Servlet Interface must be implemented by all servlets (either the GenericServlet or the HttpServlet)

What are the uses of Servlets?
  •   Servlets are used to process the client requests.
  •   A Servlet can handle multiple request concurrently and be used to develop high performance system
  •   A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.

What are the objects that are received when a servlets accepts call from client?

The objects are:
ServeltRequest and
ServletResponse

The ServeltRequest encapsulates the communication from the client to the
server. While ServletResponse encapsulates the communication from the Servlet back to the client. All the passage of data between the client and server happens by means of these request and response objects.

Wednesday, July 13, 2011

How to Read File in Java

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* This program reads a file line by line and print to the console.
*
*/
public class FileRead {
public static void main(String[] args) {
File file = new File("C:\\MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;

try {
fis = new FileInputStream(file);

//BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {

// Reads the line from the file and print it to the console.
System.out.println(dis.readLine());
}

// close all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Monday, June 27, 2011

Singleton Pattern


Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!

A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]“.
The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.

Strategy for Singleton instance creation

We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it.Factory design pattern can be used to create the singleton instance.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance;
    private Singleton() {}
  public static Singleton getSingleInstance() {
    if (singleInstance == null) {
      synchronized (Singleton.class) {
        if (singleInstance == null) {
          singleInstance = new Singleton();
        }
      }
    }
    return singleInstance;
  }
You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is threadsafe.

Early and lazy instantiation in singleton pattern

The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance = new Singleton();
  private Singleton() {}
  public static Singleton getSingleInstance() {
    return singleInstance;
  }
}

Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.
ANY-ACCESS-MODIFIER Object readResolve() throwsObjectStreamException;

Usage of Singleton Patter in Java API

java.lang.Runtime#getRuntime() java.awt.Desktop#getDesktop()