Saturday 1 August 2015

Jsp interview question and answer

JSP provide excellent server side scripting support for creating database driven web applications. JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy.  JSP pages are efficient, it loads into the web server’s memory on receiving the request very first time and the subsequent calls are served within a very short period of time.

 JSP over HTML

·DB driven applications can be written in JSP. With JDBC all user data can be stored in DB and connectivity can be done in JSP

·Dynamic content is possible in JSP

·Server side scripting language. No need to change data on every page

JSP over Servlets
·We go for JSP to separate the business logic from the presentation logic. But in servlets, we will write both business logic and presentation logic together.

·There problems come into the picture. If we do any modification to the presentation logic, we have to re-deploy the servlet in order to see the result of modified code of the servlet. So for every time we modifying the servlet, we should re-deploy the servlet. But where as in the case of JSP, we will write presentation logic in jsp and business logic inside the java bean and we use that java bean object in our jsp page using <jsp:useBean> tag. So, even if we do any modification to the presentation logic, no need to re-deploy the jsp.

JSP Working
·To process a JSP file, we need a JSP engine that can be connected with a web server or can be accommodated inside a web server.

·Firstly when a web browser seeks a JSP file through an URL from the web server, the web server recognizes the .jsp file extension in the URL requested by the browser and understands that the requested resource is a Java Server Page. Then the web server passes the request to the JSP engine. The JSP page is then translated into a Java class, which is then compiled into a servlet.

·This translation and compilation phase occurs only when the JSP file is requested for the first time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For each additional request of the JSP page thereafter, the request directly goes to the servlet byte code, which is already in memory.

·Thus when a request comes for a servlet, an init () methodis called when the Servlet is first loaded into the virtual machine, to perform any global initialization that every request of the servlet will need.

·Then the individual requests are sent to a service() method, where the response is put together. The servlet creates a new thread to run service() method for each request.

·The request from the browser is converted into a Java object of type HttpServletRequest, which is passed to the Servlet along with an HttpServletResponse object that is used to send the response back to the browser. The servlet code performs the operations specified by the JSP elements in the .jsp file.

JSP Life Cycle

· Translation
· Compilation
·  Loading
·  Instantiation
·  Initialization
·  Request Processing
·  Destruction

JSP Tags

Element data or that part of the JSP which is processed on the server, can be classified into the following categories:
1. Directives
2. Scripting elements
3. Standard actions

Scripting elements are used to include scripting code (Java code) within the JSP.
·They allow declaring variables and methods
·They include arbitrary scripting code and evaluate an expression.
·The three types of scripting element are: Declaration, Scriptlets and Expressions.

A declaration is a block of Java code in a JSP that is used to define class-wide variables and methodsin the generated class file. Declarations are initialized when the JSP page is initializedand have class scope. Anything defined in a declaration is available throughout the JSP, to other declarations, expressions or code.

A scriptlet consists of one or more valid Java statements.
·A scriptlet is a block of Java code that is executed at request-processing time.
.A scriptlet is enclosed between "<%" and "%>".
·Scriptlets like any other Java code block or method, can modify objects inside them as a result of method invocations.

An expression is a shorthand notation for a scriptlet that outputs a value in the response stream back to the client. When the expression is evaluated, the result is converted to a string and displayed. An expression is enclosed within <%= and %> "<%=" and "%>". If any part of expression is an object, the conversion is done using the toString() method of the object.

Standard actions are specific tags that affect the runtime behaviour of the JSP and affect the response sent back to the client. The JSP specification lists some standard action types to be provided by all containers, irrespective of the implementation. Standard actions provide page authors with some basic functionality to exploit

What JSP lifecycle methods can I override?
You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

_jspServeice() is wriiten by container and also in that method all the implicit objects will be created except request and response. If you override that method you can’t get those object.
Whatever we write inside the scriptlet gets converted into _jspService() method into the generated Servlet. So, to override this method, you can simply write the code in scriptlet. But, you cannot manually overridethis method. It will result in compilation failure.

What are implicit objects in JSP?
Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiatedby the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects. The implicit objects available in JSP are as follows:

·  request
·  response
·  pageContext
·  session
·  application
·  out
·  config
·  page
·  exception

The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService() method and not in any declaration.

What are the different types of JSP tags?
The different types of JSP tags are as follows:



What are JSP directives?
·JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page
·They are used to set global values such as a class declaration, method implementation, output content type, etc.
·They do not produce any output to the client.
·Directives are always enclosed within <%@ ….. %> tag.
Ex: page directive, include directive, etc.


What is page directive?
·         A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
·         Typically, the page directive is found at the top of almost all of our JSP pages.
·         There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
·         The syntax of the include directive is: <%@ page attribute="value">
·         Example: <%@ include file="header.jsp" %>

What are the attributes of page directive?
There are thirteen attributes defined for a page directive of which the important attributes are as follows:
import: It specifies the packages that are to be imported.
session: It specifies whether a session data is available to the JSP page.
contentType: It allows a user to set the content-type for a page.
isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.

What is the include directive?
·The include directive is used to statically insert the contents of a resource into the current JSP.
·This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
·The syntax of the include directive is as follows:
<%@ include file = "FileName" %>
·This directive has only one attribute called file that specifies the name of the file to be included.

What are the standard actions available in JSP?
The standard actions available in JSP are as follows:
<jsp:include>: It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.

What is the <jsp:useBean> standard action?
The <jsp:useBean> standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist.

What is the <jsp:forward> standard action?
·         The <jsp:forward> standard action forwards a response from a servlet or a JSP page to another page.The execution of the current page is stopped and control is transferred to the forwarded page.
·         The syntax of the <jsp:forward> standard action is : 
<jsp:forward page="/targetPage" />.
What is the <jsp:include> standard action?
·         The <jsp:include> standard action enables the current JSP page to include a static or a dynamic resource at runtime.
·         In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.
·         The syntax of the <jsp:include> standard action is as follows:
<jsp:include page="targetPage" flush="true"/>
Here, targetPage is the page to be included in the current JSP

What the difference is between include directive and include action?
Include directive
Include action
The include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet.
The include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user.
The include directive is used to statically insert the contents of a resource into the current JSP.
The include standard action enables the current JSP page to include a static or a dynamic resource at runtime.
Use the include directive if the file changes rarely. It’s the fastest mechanism.
Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.

What is the jsp:setProperty action?
You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:
<jsp:useBean id="myName" ... />
...
<jsp:setProperty name="myName" property="myProperty" ... />
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.

A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:
<jsp:useBean id="myName" ... >
  ...
  <jsp:setProperty name="myName"
                   property="someProperty" ... />
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.

What is the jsp:getProperty action?
The <jsp:getProperty> action is used to access the properties of a bean that was set using the <jsp:setProperty> action.The syntax of the <jsp:getProperty> method is:

<jsp:getProperty name="Name" property="Property" />

What is the <jsp:param> standard action?
The <jsp:param> standard action is used with <jsp:include> or <jsp:forward> to pass parameter names and values to the target resource. The syntax of the <jsp:param> standard action is as follows:
<jsp:param name="paramName" value="paramValue"/>

What is the jsp:plugin action ?
This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.

How is scripting disabled?
Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false.

The syntax for disabling scripting is as follows:
<jsp-property-group>
   <url-pattern>*.jsp</url-pattern>
   <scripting-invalid>true</scripting-invalid>
</jsp-property-group>

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

Syntax: <!-- This is a comment sent to client on <%= (new java.util.Date()).toLocaleString() %> -->

What is a Hidden Comment/ JSP 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 --%\>.

Syntax: <%-- comment --%>

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 completely within 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 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.

How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

Life cycle of Servlet:
·         Servlet class loading
·         Servlet instantiation
·         Initialization (call the init method)
·         Request handling (call the service method)
·         Removal from service (call the destroy method)

Why do we need constructor in servlet if we use the init()?
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.

How servlet is loaded?
The servlet is loaded by:
·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.

When the servlet is unloaded?
Servlet gets unloaded when:
·Server shuts down.
·Administrator manually unloads.

Different types of Servlet

·Generic servlet:GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface.  It is protocol independent servlet. It has only init() and destroy() method of ServletConfig interface in its life cycle. It may be directly extended by the servlet, also implements the log method declared in the ServletContext interface.
·Http Servlet - HttpServlet is HTTP specific servlet. It provides an abstract class HttpServlet for the developers for extend to create there  own HTTP specific servlets

What is the difference between the doGet () and doPost ()?
·In doGet() the parameters are appended to the URL and sent along with header information. In doPost (), send the information through a socket back to the webserver and it won't show up in the URL bar.
·The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. You can send much more information to the server by using post and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
·doGet() is a request for information. It does not change anything on the server. doPost () provides information that the server is expected to remember.

What is the ServletContext?
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.

What is the preinitialization of 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.

What is the <load-on-startup> element?
The <load-on-startup> element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded.

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

What is the need of session tracking in web application?
HTTP is a stateless protocol. 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 referred as "state". To keep track of this state we need session tracking.

What are the different types of session tracking?
·  URL rewriting
·   Hidden Form Fields
·   Cookies
·   Secure Socket Layer (SSL) Sessions

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.

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.

Are Servlets thread safe?
Servlet is not thread safe but we can make it as a thread safe by implementing that servlet class to SingleThreadModel

public class SurveyServlet extends HttpServlet                            implements SingleThreadModel
{
servlet code here..
...
}

Servlet containers usually manage concurrent requests by creating a new Java thread for each request. The new thread is given an object reference to the requested servlet, which issues the response through the same thread. This is why it is important to design for concurrency when you write a servlet, because multiple requests may be handled by the same servlet instance

What is the purpose of RequestDispatcher Interface?
The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp


No comments:

Post a Comment