Tuesday, September 9, 2014

JSP Major Interview Questions and Answers

Q : Explain include Directive and include Action of JSP
Ans:  This is a very popular interview question on JSP, which has been asked from long time and still asked in various interview. This question is good to test some fundamental concept like translation of JSP and difference between translation time and runtime kind of concept.

Syntax for include Directive is <%@ include file="fileName" %> which means we are including some file to our JSP Page when we use include directive contents of included file will be added to calling JSP page at translation time means when the calling JSP is converted to servlet ,all the contents are added to that page .one important thing is that any JSP page is complied if we make any changes to that particular page but if we have changed the included file or JSP page the main calling JSP page will not execute again so the output will not be according to our expectation, this one is the main disadvantage of using the include directive that why it is mostly use to add static  resources, like Header and footer .

Syntax for include action is <jsp:include page=”relativeURL” /> it’s a runtime procedure means the result of the JSP page which is mentioned in relative URL is appended  to calling JSP at runtime on their response object at the location where we have used this tag
So any changes made to included page is being effected every time, this is the main advantage of this action but only relative URL we can use here ,because request and response object is passed between calling JSP and included JSP .

 2: Difference Between include Directive and include Action of JSP

Include Directive
Include Action
include directive is processed at the translation time
Include action is processed at the run time.
include directive can use relative or absolute path
Include action always use relative path
Include directive can only include contents of resource it will not process the dynamic resource
Include action process the dynamic resource and result will be added to calling JSP
We can not pass any other parameter
Here we can pass other parameter also using JSP:param
We cannot  pass any request or response object to calling jsp to included file or JSP or vice versa
In this case it’s possible.


Q  3: Is it possible for one JSP to extend another java class if yes how?

Ans: Yes it is possible we can extends another JSP using this <%@ include page extends="classname" %> it’s a perfectly correct because when JSP is converted to servlet its implements javax.servlet.jsp.HttpJspPage interface, so for jsp page its possible to extend another java class . This question can be tricky if you don’t know some basic fact J, though its not advisable to write java code in jsp instead its better to use expression language and tag library.

Q  4: What is < jsp:usebean >tag why it is used.



JSP Interivew questions Answers
Ans: This was very popular JSP interview question during early 2000, it has lost some of its shine but still asked now and then on interviews.

JSP Syntax
<jsp:useBean
        id="beanInstName"
        scope="page | request | session | application"
     
            class="package.class"    type="package.class"

           </jsp:useBean>

This tag is used to create a instance of java bean first of all it tries to find out the bean if bean instance already exist assign stores a reference to it in the variable. If we specified type, gives the Bean that type.otherwise instantiates it from the class we specify, storing a reference to it in the new variable.so jsp:usebean is simple way to create a java bean.
Example:
     
<jsp:useBean id="stock" scope="request" class="market.Stock" />
<jsp:setProperty name="bid" property="price" value="0.0" />
a <jsp:useBean> element contains a <jsp:setProperty> element that sets property values in the Bean,we have <jsp:getProperty>element also to get the value from the bean.

Explanation of Attribute

 id="beanInstanceName"
A variable that identifies the Bean in the scope we specify. If the Bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used in the original <jsp:useBean> element.
scope="page | request | session | application"
The scope in which the Bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:
  • page – we can use the Bean within the JSP page with the <jsp:useBean> element
  • request – we can use the Bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another file.
  • session – we can use the Bean from any JSP page in the same session as the JSP page that created the Bean. The Bean exists across the entire session, and any page that participates in the session can use it..
  • application – we can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean.
class="package.class"
Instantiates a Bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor.
type="package.class"
If the Bean already exists in the scope, gives the Bean a data type other than the class from which it was instantiated. If you use type without class or beanName, no Bean is instantiated.

Q  5: How can one Jsp Communicate with Java file.

Ans:we have import tag <%@ page import="market.stock.*” %> like this we can import all the java file to our jsp and use them as a regular class another way is  servlet can send  the instance of the java class to our  jsp and we can retrieve that object from the request obj and use it in our page.

Q 6: what are the implicit Object

Ans: This is a fact based interview question what it checks is how much coding you do in JSP if you are doing it frequently you definitely know them. Implicit object are the object that are created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.they are bydefault available in JSP page.

They are: request, response, pageContext, session, and application, out, config, page, and exception.

Q  7: In JSP page how can we handle runtime exception?

Ans: This is another popular JSP interview question which has asked to check how candidate used to handle Error and Exception in JSP. We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.

Example: <%@ page errorPage="error.jsp" %>
It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage="true" %>


Q  8: Why is _jspService() method starting with an '_' while other life cycle methods do not?

Ans: main JSP life cycle method are jspInit() jspDestroy() and _jspService() ,bydefault whatever content we write in our jsp page will go inside the _jspService() method by the container if again will try to override this method JSP compiler will give error but we can override other two life cycle method as we have implementing this two in jsp so making this difference container use _ in jspService() method and shows that we cant override this method.


Q  9: How can you pass information form one jsp to included jsp:

Ans: This JSP interview question is little tricky and fact based. Using < Jsp: param> tag we can pass parameter from main jsp to included jsp page

Example:
<jsp:include page="newbid.jsp" flush="true">
<jsp:param name="price" value="123.7"/>
<jsp:param name="quantity" value="4"/>

Q  10: what is the need of tag library?

Ans tag library is a collection of custom tags. Custom actions helps recurring tasks will be handled more easily they can be reused across more than one application and increase productivity. JSP tag libraries are used by Web application designers who can focus on presentation issues rather than being concerned with how to access databases and other enterprise services. Some of the popular tag libraries are Apache display tag library and String tag library. You can also check my post on display tag library example on Spring.

Q 11:  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.
Q12 : What are the JSP standard actions?
  • The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
  • They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
  • Ex: include, forward, useBean,etc. object .

Q13 : What are the scopes available in <jsp:useBean>?
The scopes available in <jsp:useBean> are as follows:
  • page scope:: It specifies that the object will be available for the entire JSP page but not outside the page.
  • request scope: It specifies that the object will be associated with a particular request and exist as long as the request exists.
  • application scope: It specifies that the object will be available throughout the entire Web application but not outside the application.
  • session scope: It specifies that the object will be available throughout the session with a particular client.
Q 14 :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" />
    Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context.
  • If anything is written to the output stream that is not buffered before <jsp:forward>, an IllegalStateException will be thrown.
Note : Whenever we intend to use <jsp:forward> or <jsp:include> in a page, buffering should be enabled. By default buffer is enabled.

Q 15 :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.

Q16 :What is the difference between include directive and include action?
Include directiveInclude 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.

Q17 :What are scripting elements?

JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:
  1. Expressions of the form <%= expression %> that are evaluated and inserted into the output,
  2. Scriptlets of the form <% code %> that are inserted into the servlet's service method,
  3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.
Q 18 :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>
Q 19 :What are JSP declarations?
As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the<%! and %> tags. A declaration is not included in the service() method when a JSP is translated to a servlet.
Q 20 :What is a scriptlet?
A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a servlet, the scriptlet code goes into the service() method. Hence, methods and variables written in scriptlets are local to the service() method. A scriptlet is written between the <% and %> tags and is executed by the container at request processing time.
Q 21 :Differentiate between response.sendRedirect(url) and <jsp:forward page = …> .
<jsp.forward> element forwards the request object from 1 JSP file to another. Target file can be HTML, servlet or another JSP file, but it should be in the same application context as forwarding JSP file. sendRedirect send HTTP temporary redirect response to the browser. The browser then creates a new request for the redirected page. It kills the session variables.

Q 22 :How to include static files in a JSP page?

Static pages are always included using JSP include directive. This way the inclusion is performed in the translation phase once. Note that a relative URL must be supplied for file attribute. Although static resources may be included, it is not preferred as each request requires inclusion.
Q 23 : What are The implicit EL Objects in JSP ?
Following are the implicit EL objects:-

PageContext: The context for the JSP page.Provides access to various objects for instance:-ervletContext: The context for the JSP page's servlet and any web components contained n the same application.

session: The session object for the client.
request: The request triggering the execution of the JSP page.
response: The response returned by the JSP page. See Constructing Responses.n addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single valueparamValues: Maps a request parameter name to an array of valuesheader: Maps a request header name to a single valueheaderValues: Maps a request header name to an array of valuescookie: Maps a cookie name to a single cookieinitParam: Maps a context initialization parameter name to a single valueFinally, there are objects that allow access to the various scoped variables described in Using Scope Objects.pageScope: Maps page-scoped variable names to their valuesrequestScope: Maps request-scoped variable names to their valuessessionScope: Maps session-scoped variable names to their valuesapplicationScope: Maps application-scoped variable names to their valuesBrowser: ${header["user-agent"]}

Q 24 :  How can We Disable EL ?
We can disable using isELIgnored attribute of the page directive:
<%@ page isELIgnored ="true|false" %>


Q 25 :  What is JSTL ?

JSTL is also called as JSP tag libraries. They are collection of custom actions which can be accessed as JSP tags.

Q 26 : Types of JSTL Tags in JSP ?

Tags are classified in to four groups:- 
Core tags 
Formatting tags 
XML tags 
SQL tags.


Q 27 : How  can we use beans in JSP ?

JSP provides three tags to work with beans:- 
< jsp:useBean id=“bean name” class=“bean class” scope = “page | request | session |application ”/>

Bean name = the name that refers to the bean. Bean class = name of the java class that defines the bean. 
< jsp:setProperty name = “id” property = “someProperty” value = “someValue” / > id = the name of the bean as specified in the useBean tag. property = name of the property to be passed to the bean. value = value of that particular property . 
< jsp:getProperty name = “id” property = “someProperty” />

Here the property is the name of the property whose value is to be obtained from the bean.Below is a code snippet which shows how MyUserClass is used and the values accessed.
< jsp:useBean id="user" class="MyUserClass" scope="session"/>
< HTML>
< BODY>
You entered< BR>
Name: <%= user.getUsername() %>< BR>
Email: <%= user.getEmail() %>< BR>


Q 28 :How do we prevent browser from caching output of my JSP pages?
WE can prevent pages from caching JSP pages output using the below code snippet. <%response.setHeader("Cache-Control","no-cache"); //HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %>.

Q 29 : What are the Page Directives in JSP ?

Page directive is used to define page attributes the JSP file. Below is a sample of the same:- <% @ page language="Java" import="java.rmi.*,java.util.*" session="true" buffer="12kb" autoFlush="true" errorPage="error.jsp" %> 
To summarize some of the important page attributes:-
import :- Comma separated list of packages or classes, just like import statements in usual Java code.
session :- Specifies whether this page can use HTTP session. If set "true" session (which refers to the javax.servlet.http.HttpSession) is available and can be used to access the current/new session for the page. If "false", the page does not participate in a session and the implicit session object is unavailable.
buffer :- If a buffer size is specified (such as "50kb") then output is buffered with a buffer size not less than that value.
isThreadSafe :- Defines the level of thread safety implemented in the page. If set "true" the JSP engine may send multiple client requests to the page at the same time. If "false" then the JSP engine queues up client requests sent to the page for processing, and processes them one request at a time, in the order they were received. This is the same as implementing the javax.servlet.SingleThreadModel interface in a servlet.
errorPage: - Defines a URL to another JSP page, which is invoked if an unchecked runtime exception is thrown. The page implementation catches the instance of the Throwable object and passes it to the error page processing.


Q 30 : What are the different scopes an object can have in a Jsp Page ?

There are four scope which an object can have in a JSP page:-
Page Scope
Objects with page scope are accessible only within the page. Data only is valid for the current response. Once the response is sent back to the browser then data is no more valid. Even if request is passed from one page to other the data is lost. Request Scope
Objects with request scope are accessible from pages processing the same request in which they were created. Once the container has processed the request data is invalid. Even if the request is forwarded to another page, the data is still available though not if a redirect is required. Session Scope
Objects with session scope are accessible in same session. Session is the time users spend using the application, which ends when they close their browser or when they go to another Web site. So, for example, when users log in, their username could be stored in the session and displayed on every page they access. This data lasts until they leave the Web site or log out. Application Scope
Application scope objects are basically global object and accessible to all JSP pages which lie in the same application. This creates a global object that's available to all pages. Application scope variables are typically created and populated when an application starts and then used as read-only for the rest of the application.
 Implict Objects of JSP :
--------------------------------
pageContext :- The PageContext object.
pageScope :- A Map of all the objects that have page scope.
requestScope :- A Map of all the objects that have request scope.
sessionScope :- A Map of all the objects that have session scope.
applicationScope :- A Map of all the objects that have application scope.
param :- A Map of all the form parameters that were passed to your JSP page (for example, the HTML < input name="someName" type="text"/> is passed to your JSP page as a form parameter).
paramValues :- HTML allows for multiple values for a single form parameter. This is a Map of all the parameters, just like param, but in this object the values are an array containing all of the values for a given parameter in the event that there's more than one. header :- A Map of all the request headers.
headerValues :- For the same reasons as paramValues, a headerValues object is provided.
cookie :- A Map of all the cookies passed to your JSP. The value returned is a Cookie object.
initParam :- A Map that maps context initialization parameter names to their parameter values.



4 comments:

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...