Monday, November 4, 2013

Servlet JSP Interview Questions

1. What is a servlets?
Java Servlet is server side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.


2. 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 protocol specific functionality.

3. Servlet life cycle 
There are four phases of servlet life cycle.
 

Servlet Class Loading – When container receives request for a servlet, it first loads the class into memory.

Servlet Class Initialization – Once the servlet class is loaded, container initializes the ServletContext object for the servlet and then invoke it’s init  method by passing servlet config object.
  
Request Handling – Once servlet is initialized, its ready to handle the client requests. For every client request, servlet container initiate a new thread and invokes the service() method by passing the request and response object reference.
  
Removal from Service – When container stops or we stop the application, servlet container destroys the servlet class by invoking it’s destroy() method.


4. 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()

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

6. Servlet constructor?
We can put one but. But I don’t think its of any use because we won’t be initialize it.

7. What are the differences between HttpServlet and Generic Servlets?
GenericServlet is protocol independent implementation of Servlet interface. HttpServlet is HTTP protocol specific implementation.

8. What is ServletConfig object?
javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation. We can use getServletConfig() method to get the ServletConfig object of the servlet.

9. What is ServletContext object?
javax.servlet.ServletContext interface provides access to web application parameters to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application,

We can use ServletContext object and define parameters in web.xml using <context-param> element. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.

10. What is difference between ServletConfig and ServletContext?
Some of the differences between ServletConfig and ServletContext are:

ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.

ServletConfig is used to provide init parameters to the servlet whereas ServletContext is used to provide application level init parameters that all other servlets can use.

We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.

11. What is Request Dispatcher?
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.

There are two methods defined in this interface:
    void forward(ServletRequest request, ServletResponse response) – forwards the request from a
    servlet to another resource (servlet, JSP file, or HTML file) on the server.
   
    void include(ServletRequest request, ServletResponse response) – includes the content of a
    resource (servlet, JSP page, HTML file) in the response.

We can get RequestDispatcher in a servlet using ServletContext getRequestDispatcher(String path) method. The path must begin with a / and is interpreted as relative to the current context root.


12. What is difference between PrintWriter and ServletOutputStream?

PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.

We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.

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

14. What is servlet lazy loading?
Lazy servlet loading means – the container does not initialize the servlets as soon as it starts up. Instead it initializes servlets when they receive their first ever request. This is the standard or default behavior. If you want the container to load your servlet at start-up then use pre-initialization using the load-on-startup element in the deployment descriptor.




15. What is the use of servlet wrapper classes?
Servlet HTTP API provides two wrapper classes – HttpServletRequestWrapper and HttpServletResponseWrapper.These wrapper classes are provided to help developers
with custom implementation of servlet request and response.

16. What is SingleThreadModel interface?
SingleThreadModel interface was provided for thread safety and it guarantees that not more then one threads will execute concurrently in the servlets service method. However SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time.

17. How to achieve thread safety in servlets?
HttpServlet init() method and destroy() method are called only once in servlet life cycle, so we don’t need to worry about their synchronization. But service  methods such as doGet() or doPost() are getting called in every client request and since servlet uses multithreading, we should provide thread safety in these methods.

If there are any local variables in service methods, we don’t need to worry about their thread safety because they are specific to each thread but if we have a  shared resource then we can use synchronization to achieve thread safety

18 . Diff between ServletResponse sendRedirect() and RequestDispatcher forward() method?

RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request. The request sent is a   completely new request hence have to use session or url param for message passing.
  
forward() is handled internally by the container whereas sednRedirect() is handled by browser.

We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.

In forward() browser is unaware of the actual processing resource and the URL in address bar remains same whereas in sendRedirect() URL in address bar change to the forwarded resource.
  
forward() can’t be used to invoke a servlet in other context, we can only use sendRedirect() in this case.

19. What is servlet filter?
Servlet Filters are pluggable java components use to intercept and process requests before they are sent to servlets and response before container sends back to the client.

Some common tasks that we can do with filters are:
1. Logging request parameters to log files.
2. Authentication and authorization of request for resources.
3. Formatting of request body or header before sending it to servlet.
4. Compressing the response data sent to the client.

20. what is servlet listener?
Servlet API provides Listener interfaces that we can implement and configure to listen for an event and do certain operations. Servlet API provides different types of Listener interfaces for Context, Session and Request that we can implement and configure in web.xml

21. What are different methods of session management in servlets?
Session is a conversational state between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

 Session management techniques available in servlets are:
1. HTML Hidden Field
2. Cookies
3. URL Rewriting

22. What are different ways for servlet authentication?
Servlet Container provides different ways of login based servlet authentication:

    HTTP Basic Authentication
    HTTP Digest Authentication
    HTTPS Authentication
    Form Based Login:

23. How to invoke servlets in a different application?
 We can’t use RequestDispatcher to invoke servlet from another application because it’s specific for the application. If we have to forward the request to a resource in another application, we can use ServletResponse sendRedirect()

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


25. What are the advantages of Servlets over CGI programs?
Java Servlets have a number of advantages over CGI and other API's. Some are:

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.

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.

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.

26. Which HTTP method is non-idempotent?
A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement our application to make sure these methods always return same result. HTTP method POST is non-idempotent method and we should use post method when implementing something that changes with every request.

27. What is the difference between GET and POST method?

GET is a safe method (idempotent) where POST is non-idempotent method.

We can send limited data with GET method and it’s sent in the header request URL whereas we can send large amount of data with POST because it’s part of the body.

GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can’t bookmark it.

GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.

28 What is MIME Type?
The “Content-Type” response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it’s sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.

29. What is URL Encoding?
URL Encoding is the process of converting data into CGI form so that it can travel across the network.URL Encoding strip the white spaces and replace special characters with escape characters. We can use java.net.URLEncoder.encode(String str, String unicode) to encode a String.

30. What is different between web server and application server?
A web server responsibility is to handler HTTP request and response. Application Servers is web server with additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc.

31. What are common tasks performed by Servlet Container
Communication Support: Servlet Container provides easy way of communication between web client (Browsers) and the servlets and JSPs. Because of  container, we don’t need to build a server socket to listen for any request from web client, parse the request and generate response. All these important and complex tasks are done by container and all we need to focus is on business logic for the applications.
                             
Lifecycle and Resource Management: Servlet Container takes care of managing the life cycle of servlet. From the loading of servlets into memory, initializing servlets, invoking servlet methods and to destroy them. Container also provides utility like JNDI for resource pooling and management

Multi-threading Support: Container creates new thread for every request to the servlet and provide them request and response objects to process. So servlets are not initialized for each request and saves time and memory.       
   
JSP Support: JSP compiled by container and converted to Servlet and then  container manages them like other servlets.

Deployment and Other : provides security configurations,support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.

32. How can we achieve transport layer security for our web application?
We can configure our servlet container to use SSL for message communication over the network..

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

34. What are important features of Servlet 3?
Servlet Annotations : java annotations to define a servlet, filter and listener servlets and init parameters

Web Fragments : we can have multiple modules in a single web application, all these modules should have web-fragment.xml file in META-INF directory.

Adding Web Components dynamically:  We can use ServletContext object to add servlets, filters and listeners programmatically.

Asynchronous Processing: Delegate the request processing to another thread rather than keeping the servlet thread busy.

35. What is JSP
Java Server Pages are an extension to the Java servlet technology. A JSP is translated into Java servlet before being run, and it processes HTTP requests and generates responses like any servlet.

A JSP page can have two types of data one is Template Data it is the static part of a jsp page other one is JSP Elements it is the dynamic part of a jsp page translated and executed by the server.

36. what is JSPF
JSP Fragments can be compared to server side includes. These fragments are not compiled on their own, They're designed to be statically included in another JSP file,

37. What is JSP Element :

There are three type of element Scripting,Directive,Standard Action.

Scripting Elements:
    JSP declaration tag: Define variables and Method. Statements should end with semi-colon
            Syntax:
             <%!  statement;  %>   or <jsp:declaration> statement; </jsp:declaration>    

    JSP Scriptlet tag : Declare or define any java code into jsp.
                Syntax:
                <% statement; %>  or <jsp:scriptlet>  Java code; </jsp:scriptlet>

    JSP expression tag : Use to display java values to the browser.
                  Syntax:
                  <%= statement %> or <jsp:expression> statement < /jsp:expression>

     Comment : Hidden comment <%-- --%>or HTML comment <!-- -->

Directive Element:
    Page Directive : used to specify attributes for the JSP page. Some attributes are language, import,
     session, pageEncoding.
     Syntax:
       <%@ page import="java.util.*" %> or <jsp:directive.page import="java.util.*" />

     Include Directive :   It allows to include source code (static resource) of a file inside a jsp file at
     the specified place at a translation time.Typically include files are used for headers, footers, tables
     and navigation that are common to multiple pages
                            Syntax:
                                    <%@ include file="/folder_name/file_name"%>
    TagLib directive : The taglib directive makes custom actions available in the page through the use
    of tag library.
Standard Action :
Actions are create, modify or use other objects. Unlike directives and scripting elements, JSP actions are coded using strict XML syntax form.
The standard action types are:

                (1)<jsp:param>

                (2)<jsp:include>

                (3)<jsp:forward>

                (4)<jsp:fallback>

                (5)<jsp:plugin>

                (6) <jsp:useBean>

                (7)<jsp:setProperty>

                (8)<jsp:getProperty>

38. What is the difference between < jsp : include page = ... > and < % @ include file = ... >? 

The jsp:include element is processed when a JSP page is executed.
The include directive is a static include is processed at compile time,no support for parameter pasing.

39.What are implicit Objects available to the JSP Page?

Implicit objects are the objects available to the JSP page. These objects are injected by web container and contain information related to a particular request, page, and application.

The JSP implicit objects are:

application
config
exception
out
page
pageContext
request
response and
session

40. What are all the different scope values for the < jsp : useBean > tag?

Scopes are following:
a) page
b) request
c) session and
d) application

41. What are the life-cycle phases of a JSP?

Page translation: -  Page is parsed, and a java file which is a servlet is created.
Page compilation:  Page is compiled into a class file
Page loading :       This class file is loaded.
Create an instance :- Instance of servlet is created
jspInit() method is called
_jspService is called to handle service calls
_jspDestroy is called to destroy it when the servlet is not required.



42. What are the life-cycle methods of JSP?

Life-cycle methods of the JSP are:

a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.

b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.

c) jspDestroy(): The container calls this when its instance is about to destroyed.

The jspInit() and jspDestroy() methods can be overridden within a JSP page.



43. What do you understand by JSP translation?

JSP translation is an action that refers to the conversion of the JSP page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.


44. What is EL ?
expression language systax ${}

45. how does EL search for an attribute ?
EL parser searches the attribute in following order:
Page
Request
Session (if it exists)
Application
If no match is found for then it displays empty string.

46. What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. every time you click on any link in the website URL rewriting require data transfer from and to the
server

47. What is session hijacking?
Session hijacking refers to the act of taking control of a user session with authentication. to prevent this use SSL/HTTPS or regeneration of session token or  session regenerate technique.

48. What is Session Migration?
Session Migration is a mechanism of moving the session from one server to another in case of server failure. we can achieve this by
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.

4 comments:

AWS Services

      1.         Identity Access Management (IAM): Used to control Identity (who) Access (what AWS resources).                   1....