Advanced Java Interview Questions -2

Advanced Java Interview Questions -2

1.If a servlet is not properly initialized, what exception may be thrown?
 

During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.

2.Given the request path below, which are context path, servlet path and path info?
 

/bookstore/education/index.html
context path: /bookstore
servlet path: /education
path info: /index.html

3.What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

4.Explain the life cycle of Servlet.
Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.

5.When is the servlet instance created in the life cycle of servlet? What is the importance of configuring a servlet?
An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.

6.Why don't we write a constructor in a servlet?
Container writes a no argument constructor for our servlet.

7.When we don't write any constructor for the servlet, how does container create an instance of servlet?

Container creates instance of servlet by calling Class.forName(className).newInstance().

8.Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time?

Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.

9.What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext?

We can give relative URL when we use ServletRequest and not while using ServletContext.

10.What is servlet context ?

The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial).

11.Which interface must be implemented by all servlets?

Servlet interface.

12.What is Servlet?

A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request\/response paradigm.

13.Why is Servlet so popular?

Because 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.

14.What is filter? Can filter be used as request or response?

A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

15.When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?

I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.

16.What is new in ServletRequest interface ? (Servlet 2.4)

The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()

17.What is servlet container?

The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.

18.When a client request is sent to the servlet container, how does the container choose which servlet to invoke?

The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.

19.Request parameter How to find whether a parameter exists in the request object?

1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)

20.How can I send user authentication information while making URL Connection?

You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

21.Can we use the constructor, instead of init(), to initialize servlet?

Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.

22.How can a servlet refresh automatically if some new data has entered the database?

You can use a client-side Refresh or Server Push

23.The code in a finally clause will never fail to execute, right?

Using System.exit(1); in try block will not allow finally code to execute.

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

Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

25.Difference between GET and POST ?

In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.

26.What is session?

The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.

27.Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()?

Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.

28.What’s the difference between servlets and applets?

Servlets are to servers; applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

29. What’s the advantages using servlets than using CGI?

Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with Java Servlet API, a standard Java extension.

30.What are the uses of Servlets?

A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

31.What’s the Servlet Interface?

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet. Servlets–>Generic Servlet–>HttpServlet–>MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

32.When a client request is sent to the servlet container, how does the container choose which servlet to invoke?

The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.

33.When a servlet accepts a call from a client, it receives two objects. What are they?

ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

34.Why is Servlet so popular?

Because 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.

35.What is servlet container?

The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.

36.What is Java Servlet?

A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request/response paradigm.

37.If a servlet is not properly initialized, what exception may be thrown?

During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.

38. What is filter? Can filter be used as request or response?

A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

39.When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?

I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.

40.What is new in ServletRequest interface?(Servlet 2.4)

The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()

41.The code in a finally clause will never fail to execute, right?

Using System.exit(1); in try block will not allow finally code to execute.

42.How can I send user authentication information while makingURLConnection?

You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

43.Can we use the constructor, instead of init(), to initialize servlet?

Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.

44.Request parameter How to find whether a parameter exists in the request object?

1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);
(which works in Servlet 2.3+)

45.How can a servlet refresh automatically if some new data has entered the database?

You can use a client-side Refresh or Server Push

46.What is Java Servlet session?

The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.

47.What is servlet mapping?

The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

48.What is servlet context ?

The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial).

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

Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

50.Difference between GET and POST in Java Servlets?

In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.

51.What are the uses of Servlet?

Typical uses for HTTP Servlets include:
Processing and/or storing data submitted by an HTML form.
Providing dynamic content, e.g. returning the results of a database query to the client.
A Servlet can handle multiple request concurrently and be used to develop high performance system
Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

52.What are the advantages of Servlet over CGI?

Servlets have several advantages over CGI:
A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
Several web.xml conveniences
A handful of removed restrictions
Some edge case clarifications

53.What are the phases of the servlet life cycle?

The life cycle of a servlet consists of the following phases:
Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.

Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.

Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.

Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.

Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.


54.Why do we need a constructor in a servlet if we use the init method?

Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven't constructed an object to call it on yet.

55.How the servlet is loaded?

A servlet can be loaded when:
First request is made.
Server starts up (auto-load).
There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
Administrator manually loads.

56.How a Servlet is unloaded?

A servlet is unloaded when:
Server shuts down.
Administrator manually unloads.


57.What is the GenericServlet class?

GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.
Note: This class is known as generic servlet, since it is not specific to any protocol.

58.Why is HttpServlet declared abstract?

the HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.

59.Can servlet have a constructor ?

One can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose,but this type of approch is not so common. You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.

60.What are the types of protocols supported by HttpServlet ?

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

61.What is a servlet context object?

A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. Each Web application in a container has a single servlet context associated with it.

62.What's the use of the servlet wrapper classes??

The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.

63.Should I override the service() method?

We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request.For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.

64.What is preinitialization of a servlet?

A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

65.What is session?

A session refers to all the requests that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables.

66.What is Session Tracking?

Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

67.What is the need of Session Tracking in web application?

HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information which is part of the application is reffered as "state". To keep track of this state we need session tracking.

68.What are the types of Session Tracking ?

Sessions need to work with all web browsers and take into account the users security preferences. Therefore there are a variety of ways to send and receive the identifier:
URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies.

Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.

Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie's value can uniquely identify a client.

Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL's support via HTTPS for generating a unique session key as part of the encrypted conversation.

69.How do I use cookies to store session state on the client?

In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method HttpServlet.service() can be used to create cookies on the client and use cookie information transmitted during client requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom tag code.
To set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies may be set for the same request, and a single cookie name may have multiple values.
To get all of the cookies associated with a single HTTP request, use the getCookies() method of class HttpServletRequest

70.What are some advantages of storing session state in cookies?

Cookies are usually persistent, so for low-security sites, user data that needs to be stored long-term (such as a user ID, historical information, etc.) can be maintained easily with no server interaction.
For small- and medium-sized session data, the entire session data (instead of just the session ID) can be kept in the cookie.

71.What are some disadvantages of storing session state in cookies?

Cookies are controlled by programming a low-level API, which is more difficult to implement than some other approaches.
All data for a session are kept on the client. Corruption, expiration or purging of cookie files can all result in incomplete, inconsistent, or missing information.
Cookies may not be available for many reasons: the user may have disabled them, the browser version may not support them, the browser may be behind a firewall that filters cookies, and so on. Servlets and JSP pages that rely exclusively on cookies for client-side session state will not operate properly for all clients. Using cookies, and then switching to an alternate client-side session state strategy in cases where cookies aren't available, complicates development and maintenance.
Browser instances share cookies, so users cannot have multiple simultaneous sessions.
Cookie-based solutions work only for HTTP clients. This is because cookies are a feature of the HTTP protocol. Notice that the while package javax.servlet.http supports session management (via class HttpSession), package javax.servlet has no such support.


72.A client sends requests to two different web components. Both of the components access the session. Will they end up using the same session object or different session ?

Creates only one session i.e., they end up with using same session .
Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a session.

73.What is servlet lazy loading?

A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.
The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.
The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

74.What is Servlet Chaining?

Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

75.How are filters?

Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows:
Security checks
Modifying the request or response
Data compression
Logging and auditing
Response compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.


76.What is URL rewriting?

URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session.
Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.
E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
Advantages
URL rewriting works just about everywhere, especially when cookies are turned off.
Multiple simultaneous sessions are possible for a single user. Session information is local to each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't foolproof, though, since users can start a new browser instance using a URL for an active session, and confuse the server by interacting with the same session through two instances.
Entirely static pages cannot be used with URL rewriting, since every link must be dynamically written with the session state. It is possible to combine static and dynamic content, using (for example) templating or server-side includes. This limitation is also a barrier to integrating legacy web pages with newer, servlet-based pages.
DisAdvantages
Every URL on a page which needs the session information must be rewritten each time a page is served. Not only is this expensive computationally, but it can greatly increase communication overhead.
URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in awkward restrictions on the page.
URL rewriting does not work well with JSP technology.
If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are lost.

77.What are the functions of an intercepting filter?

The functions of an intercepting filter are as follows:
It intercepts the request from a client before it reaches the servlet and modifies the request if required.
It intercepts the response from the servlet back to the client and modifies the request if required.
There can be many filters forming a chain, in which case the output of one filter becomes an input to the next filter. Hence, various modifications can be performed on a single request and response.

78.What are the functions of the Servlet container?

The functions of the Servlet container are as follows:
Lifecycle management : It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
Communication support : It handles the communication between the servlet and the Web server.
Multithreading support : It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
Declarative security : It manages the security inside the XML deployment descriptor file.
JSP support : The container is responsible for converting JSPs to servlets and for maintaining them.

79.How can an existing session be invalidated?

An existing session can be invalidated in the following two ways:
Setting timeout in the deployment descriptor: This can be done by specifying timeout between the <session-timeout>tags as follows:
<session-config>
       <session-timeout>10</session-timeout>
</session-config>
This will set the time for session timeout to be ten minutes.
Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
public void setMaxInactiveInterval(int interval)
The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.
Note :Setting the inactive period as negative(-1), makes the container stop tracking session, i.e, session never expires.

80.How can the session in Servlet can be destroyed?

An existing session can be destroyed in the following two ways:
Programatically : Using session.invalidate() method, which makes the container abonden the session on which the method is called.
When the server itself is shutdown.

81.Can we use the constructor, instead of init(), to initialize servlet?

Yes. But you will not get the servlet specific things from constructor. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

82.What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.

83.What are context initialization parameters?

Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application.

84.What is a Expression?

Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.

85.What is a Declaration?

It 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 semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet.

86.What is a Scriptlet?

A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a . Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet's service method.

87.What is servlet mapping?

The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.

88.What is servlet context ?

The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

89.What is a servlet ?

servlet is a java program that runs inside a web container.

90.What's the Servlet Interface?

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.

91.How do I use a scriptlet to initialize a newly instantiated bean?

A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated (Only at the time of instantiation.) Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.

92.What is the difference between ServletContext and ServletConfig?

The ServletConfig gives the information about the servlet initialization parameters. The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. The ServletContext gives information about the container. The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.

93.How can a servlet refresh automatically?

We can use a client-side Refresh or Server Push

94.What is Server side push?

Server Side push is useful when data needs to change regularly on the clients application or browser, without intervention from client. The mechanism used is, when client first connects to Server, then Server keeps the TCP/IP connection open.

95.What are two different types of Servlets ?

GenericServlet and HttpServlet. HttpServlet is used to implement HTTP protocol, where as Generic servlet can implement any protocol.

96.What is the life cycle of servlet?

Each servlet has the same life cycle: first, the server loads and initializes the servlet by calling the init method. This init() method will be executed only once during the life time of a servlet. Then when a client makes a request, it executes the service method. finally it executes the destroy() method when server removes the servlet.

97. Can we call destroy() method on servlets from service method ?
Yes.

98.What is the need of super.init (config) in servlets ?

Then only we will be able to access the ServletConfig from our servlet. If there is no ServletConfig our servlet will not have any servlet nature.

99.What is the difference between GenericServlet and HttpServlet?

GenericServlet supports any protocol. HttpServlet supports only HTTP protocol. By extending GenericServlet we can write a servlet that supports our own custom protocol or any other protocol.

100.What are the implicit objects?

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 are: request, response, pageContext, session, application, out, config, page, exception

101. What's the difference between forward and sendRedirect?

forward is server side redirect and sendRedirect is client side redirect. 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 completely with in the web container And then returns to the calling method. When a sendRedirect 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 completely 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. Client can disable sendRedirect.

102.Can we write a constructor for servlet ?

Yes. But the container will always call the default constructor only. If default constructor is not present , the container will throw an exception.

103.Question: What are the parameters for service method ?

ServletRequest and ServletResponse

104.What are cookies ?

Cookies are small textual information that are stored on client computer. Cookies are used for session tracking.

105.What is the meaning of response has already been committed error?

You will get this error only when you try to redirect a page after you already have flushed the output buffer. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown. When you try to send a redirect status, your HTTP server cannot send it right now if it hasn't finished to set up the header. Simply it is giving the error due to the specification of HTTP 1.0 and 1.1

106.What is HttpTunneling?

HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intranet is blocked by a firewall and the network is exposed to the outer world only through a specific web server port, that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and send as HttpRequest.

107.How to pass information from JSP to included JSP?

By using jsp:param tag.

108.What is the better way to enable thread-safe servlets and JSPs? SingleThreadModel Synchronization?

The better approach is to use synchronization. Because SingleThreadModel is not scalable. SingleThreadModel is pretty resource intensive from web server's perspective. The most serious issue is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the un serviced requests are queued until something becomes free - which results in poor performance.

109.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 un interpreted 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.

110.What is a Hidden Comment

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.

111.What are the differences between a session and a cookie?

Session is stored in server but cookie stored in client. Session should work regardless of the settings on the client browser. There is no limit on the amount of data that can be stored on session. But it is limited in cookie. Session can store objects and cookies can store only strings. Cookies are faster than session.

112.What is the difference between ServletContext and PageContext?

ServletContext gives the information about the container and PageContext gives the information about the Request

113.Why in Servlet 2.4 specification SingleThreadModel has been deprecated?

SingleThreadModel is pretty resource intensive from web server's perspective. When the number of concurrent requests exhaust the servlet instance pool, all the un serviced requests are queued until something becomes free - which results in poor performance.

114.How can I set a cookie?

Cookie c = new Cookie("name","value");
response.addCookie(c);

115. How will you delete a cookie?

Cookie c = new Cookie ("name", null);
c.setMaxAge(0);
response.addCookie(killCookie);


116.What is the difference between Context init parameter and Servlet init parameter?

Servlet init parameters are for a single servlet only. No body out side that servlet can access that. It is declared inside the tag inside Deployment Descriptor, where as context init parameter is for the entire web application. Any servlet or JSP in that web application can access context init parameter. Context parameters are declared in a tag directly inside the web-app tag. The methods for accessing context init parameter is getServletContext ().getInitParamter (“name”) where as method for accessing servlet init parameter is getServletConfig ().getInitParamter (“name”);

117. What is the difference between setting the session time out in deployment descriptor and setting the time out programmatically?

In DD time out is specified in terms of minutes only. But in programmatically it is specified in seconds. A session time out value of zero or less in DD means that the session will never expire. To specify session will never expire programmatically it must be negative value.

118.How can we set the inactivity period on a per-session basis?

We can set the session time out programmatically by using the method setMaxInactiveInterval() of HttpSession.

119. How can my application get to know when a HttpSession is removed?

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

120.How many cookies can one set in the response object of the servlet? Also, are there any restrictions on the size of cookies?

If the client is using Netscape, the browser can receive and store 300 total cookies and 4 kilobytes per cookie. And the no of cookie is restricted to 20 cookies per server or domain 

------------------------------------
Also Read:
Advanced Java Interview Questions -1

Advanced Java Interview Questions -2

Advanced Java Interview Questions -3

Advanced Java Interview Questions -4

Advanced Java Interview Questions -5

Advanced Java Interview Questions -6

Advanced Java Interview Questions -7

Advanced Java Interview Questions -8

Advanced Java Interview Questions -9

Advanced Java Interview Questions -10

Advanced Java Interview Questions -11

Advanced Java Interview Questions -12

Advanced Java Interview Questions -13

Advanced Java Interview Questions -14        

0 comments:

Post a Comment