Pages

Tuesday 8 April 2014

Latest Frequently Asked JSP Interview Question Answer

TO CONTRIBUTE THIS BLOG CLICK ON DISPLAYED ADVERTISEMENT




Q-1) What is JSP and why do we need it?
ANS :-
JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. JSP is extension of Servlet technology to help developers create dynamic pages with HTML like syntax.
We can create user views in servlet also but the code will become very ugly and error prone. Also most of the elements in web page is static, so JSP page is more suitable for web pages. We should avoid business logic in JSP pages and try to use it only for view purpose. JSP scripting elements can be used for writing java code in JSP pages but it’s best to avoid them and use JSP action elements, JSTL tags or custom tags to achieve the same functionalities.
One more benefit of JSP is that most of the containers support hot deployment of JSP pages. Just make the required changes in the JSP page and replace the old page with the updated jsp page in deployment directory and container will load the new JSP page. We don’t need to compile our project code or restart server whereas if we make change in servlet code, we need to build the complete project again and deploy it. Although most of the containers now provide hot deployment support for applications but still it’s more work that JSP pages.

Q-2) What are the JSP lifecycle phases?
ANS :- 
If you will look into JSP page code, it looks like HTML and doesn’t look anything like java classes. Actually JSP container takes care of translating the JSP pages and create the servlet class that is used in web application. JSP lifecycle phases are:
Translation – JSP container checks the JSP page code and parse it to generate the servlet source code. For example in Tomcat you will find generated servlet class files at TOMCAT/work/Catalina/localhost/WEBAPP/org/apache/jsp directory. If the JSP page name is home.jsp, usually the generated servlet class name is home_jsp and file name is home_jsp.java
Compilation – JSP container compiles the jsp class source code and produce class file in this phase.
Class Loading – Container loads the class into memory in this phase.
Instantiation – Container invokes the no-args constructor of generated class to load it into memory and instantiate it.
Initialization – Container invokes the init method of JSP class object and initializes the servlet config with init params configured in deployment descriptor. After this phase, JSP is ready to handle client requests. Usually from translation to initialization of JSP happens when first request for JSP comes but we can configure it to be loaded and initialized at the time of deployment like servlets using load-on-startup element.
Request Processing – This is the longest lifecycle of JSP page and JSP page processes the client requests. The processing is multi-threaded and similar to servlets and for every request a new thread is spawned and ServletRequest and ServletResponse object is created and JSP service method is invoked.
Destroy – This is the last phase of JSP lifecycle where JSP class is unloaded from memory. Usually it happens when application is undeployed or the server is shut down.

Q-3) What are JSP lifecycle methods?
ANS :- 
JSP lifecycle methods are:
jspInit(): This method is declared in JspPage and it’s implemented by JSP container implementations. This method is called once in the JSP lifecycle to initialize it with config params configured in deployment descriptor. We can override this method using JSP declaration scripting element to initialize any resources that we want to use in JSP page.
_jspService(): This is the JSP method that gets invoked by JSP container for each client request by passing request and response object. Notice that method name starts with underscore to distinguish it from other lifecycle methods because we can’t override this method. All the JSP code goes inside this method and it’s overridden by default. We should not try to override it using JSP declaration scripting element. This method is defined in HttpJspPage interface.
jspDestroy(): This method is called by container when JSP is unloaded from memory such as shutting down application or container. This method is called only once in JSP lifecycle and we should override this method to release any resources created in JSP init method.

Q-4) What are advantages of using JSP?
ANS :-
 JSP offer several advantages as listed below:
  • Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself.
  • JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.
  • JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
  • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.


Q-5) What are the advantages of JSP over Active Server Pages (ASP)?
ANS :-
The advantages of JSP are twofold.
First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.

Q-6) What are the advantages of JSP over Pure Servlets?
ANS :-
It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. Other advantages are:
Embedding of Java code in HTML pages.
Platform independence.
Creation of database-driven Web applications.
Server-side programming capabilities.

Q-7) What are the advantages of JSP over Server-Side Includes (SSI)?
ANS :-
SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like.

Q-8) What are the advantages of JSP over JavaScript?
ANS :-
JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.

Q-9) What are the advantages of JSP over Static HTML?
ANS :- 
Regular HTML, of course, cannot contain dynamic information.

Q-10) Which JSP lifecycle methods can be overridden?
ANS :-
We can override jspInit() and jspDestroy() methods using JSP declaration scripting element. We should override jspInit() methods to create common resources that we would like to use in JSP service method and override jspDestroy() method to release the common resources.

Q-11) How can we avoid direct access of JSP pages from client browser?
ANS :-
We know that anything inside WEB-INF directory can’t be accessed directly in web application, so we can place our JSP pages in WEB-INF directory to avoid direct access to JSP page from client browser. But in this case, we will have to configure it in deployment descriptor just like Servlets. Sample configuration is given below code snippet of web.xml file.

<servlet>
  <servlet-name>Test</servlet-name>
  <jsp-file>/WEB-INF/test.jsp</jsp-file>
  <init-param>
    <param-name>test</param-name>
    <param-value>Test Value</param-value>
  </init-param>
</servlet>
<servlet-mapping>
  <servlet-name>Test</servlet-name>
  <url-pattern>/Test.do</url-pattern>
</servlet-mapping>

Q-12) What are different types of comments in JSP?
ANS :-
JSP pages provide two types of comments that we can use:
HTML Comments: Since JSP pages are like HTML, we can use HTML comments like <-- HTML Comment -->. These comments are sent to client also and we can see it in HTML source. So we should avoid any code level comments or debugging comments using HTML comments.
JSP Comments: JSP Comments are written using scriptlets like <%-- JSP Comment --%>. These comments are present in the generated servlet source code and doesn’t sent to client. For any code level or debugging information comments we should use JSP comments.

Q-13) What is Scriptlet, Expression and Declaration in JSP?
ANS :-
Scriptlets, Expression and Declaration are scripting elements in JSP page using which we can add java code in the JSP pages.
A scriptlet tag starts with <% and ends with %>. Any code written inside the scriptlet tags go into the _jspService() method. For example;
<%
Date d = new Date();
System.out.println("Current Date="+d);
%>
Since most of the times we print dynamic data in JSP page using out.print() method, there is a shortcut to do this through JSP Expressions. 
JSP Expression starts with <%= and ends with %>.
<% out.print("Pankaj"); %> can be written using JSP Expression as <%= "Pankaj" %>
Notice that anything between <%= %> is sent as parameter to out.print() method. Also notice that scriptlets can contain multiple java statements and always ends with semicolon (;) but expression doesn’t end with semicolon.
JSP Declarations are used to declare member methods and variables of servlet class. JSP Declarations starts with <%! and ends with %>.
For example we can create an int variable in JSP at class level as <%! public static int count=0; %>.

Q-14) What are JSP Directives?
ANS :- 
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>

Q-15) What are the types of directive tags?
ANS :-
The types directive tags are as follows:
<%@ page ... %> : Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include ... %> : Includes a file during the translation phase.
<%@ taglib ... %> : Declares a tag library, containing custom actions, used in the page.

Q-16) What are JSP actions?
ANS :-
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
Its syntax is as follows:
<jsp:action_name attribute="value" />

Q-17) Name some JSP actions.
ANS :- 
jsp:include, jsp:useBean,jsp:setProperty,jsp:getProperty, jsp:forward,jsp:plugin,jsp:element, jsp:attribute, jsp:body, jsp:text, etc.

Q-18) What are JSP literals?
ANS :- 
Literals are the values, such as a number or a text string, that are written literally as part of a program code. The JSP expression language defines the following literals:
Boolean: true and false
Integer: as in Java
Floating point: as in Java
String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
Null: null

Q-19) What is a page directive?
ANS :-
The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page.

Q-20) What are various attributes Of page directive?
ANS :-
Page directive contains the following 13 attributes.
language
extends
import
session
isThreadSafe
info
errorPage
isErrorpage
contentType
isELIgnored
buffer
autoFlush
isScriptingEnabled

Q-21) What is a buffer attribute?
ANS :-
The buffer attribute specifies buffering characteristics for the server output response object.

Q-22) What happens when buffer is set to a value “none”?
ANS :-
When buffer is set to “none”, servlet output is immediately directed to the response output object.

Q-23) What is autoFlush attribute?
ANS :-
The autoFlush attribute specifies whether buffered output should be flushed automatically when the buffer is filled, or whether an exception should be raised to indicate buffer overflow.
A value of true (default) indicates automatic buffer flushing and a value of false throws an exception.

Q-24) What is contentType attribute?
ANS :-
The contentType attribute sets the character encoding for the JSP page and for the generated response page. The default content type is text/html, which is the standard content type for HTML pages.

Q-25) What is errorPage attribute?
ANS :-
The errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL.

Q-26) What is isErrorPage attribute?
ANS :-
The isErrorPage attribute indicates that the current JSP can be used as the error page for another JSP.
The value of isErrorPage is either true or false. The default value of the isErrorPage attribute is false.

Q-27) What is extends attribute?
ANS :-
The extends attribute specifies a superclass that the generated servlet must extend.

Q-28) What is import attribute?
ANS :-
The import attribute serves the same function as, and behaves like, the Java import statement. The value for the import option is the name of the package you want to import.

Q-29) What is info attribute?
ANS :-
The info attribute lets you provide a description of the JSP.

Q-30) What is isThreadSafe attribute?
ANS :-
The isThreadSafe option marks a page as being thread-safe. By default, all JSPs are considered thread-safe. If you set the isThreadSafe option to false, the JSP engine makes sure that only one thread at a time is executing your JSP.

Q-31) What is language attribute?
ANS :-
The language attribute indicates the programming language used in scripting the JSP page.

Q-32) What is session attribute?
ANS :-
The session attribute indicates whether or not the JSP page uses HTTP sessions. A value of true means that the JSP page has access to a builtin session object and a value of false means that the JSP page cannot access the builtin session object.

Q-33) What is isELIgnored Attribute?
ANS :-
The isELIgnored option gives you the ability to disable the evaluation of Expression Language (EL) expressions. The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.

Q-34) Q: What is isScriptingEnabled Attribute?
ANS :-
The isScriptingEnabled attribute determines if scripting elements are allowed for use.
The default value (true) enables scriptlets, expressions, and declarations. If the attribute's value is set to false, a translation-time error will be raised if the JSP uses any scriptlets, expressions (non-EL), or declarations.

Q-35) What is a include directive?
ANS :-
The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="relative url" >

Q-36) What is a taglib directive?
ANS :-
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag">
uri attribute value resolves to a location the container understands
prefix attribute informs a container what bits of markup are custom actions.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >

Q-37) What do the id and scope attribute mean in the action elements?
ANS :-
Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext
Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.

Q-38) what is the function of <jsp:include> action?
ANS :-
This action lets you insert files into the page being generated. The syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Where page is the the relative URL of the page to be included.
Flush is the boolean attribute the determines whether the included resource has its buffer flushed before it is included.

Q-39) What is the difference between include action and include directive?
ANS :-
 Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, include action inserts the file at the time the page is requested.

Q-40) What is <jsp:useBean> action?
ANS :-
The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows:
<jsp:useBean id="name" class="package.class" />

Q-41) What is <jsp:setProperty> action?
ANS :-
The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action.

Q-42) What is <jsp:getProperty> action?
ANS :-
The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.

Q-43) What is <jsp:forward> Action?
ANS :-
The forward action terminates the action of the current page and forwards the request to another resource such as a static page, another JSP page, or a Java Servlet.
The simple syntax of this action is as follows:
<jsp:forward page="Relative URL" />

Q-44) What is <jsp:plugin> Action?
ANS :- 
The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the <object> or <embed> tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean.

Q-45) What are the different scope values for the JSP action?
ANS :-
The scope attribute identifies the lifecycle of the Action element. It has four possible values: (a) page, (b)request, (c)session, and (d) application.

Q-46) What are JSP implicit objects?
ANS :- 
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.

Q-47) What implicit objects are supported by JSP?
ANS :-
 request,response,out,session,application,config,pageContext,page, Exception

Q-48) What is a request object?
ANS :-
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.

Q-49) How can you read a request header information?
ANS :-
Using getHeaderNames() method of HttpServletRequest to read the HTTP header infromation. This method returns an Enumeration that contains the header information associated with the current HTTP request.

Q-50) What is a response object?
ANS :- 
The response object is an instance of a javax.servlet.http.HttpServletRequest object. Just as the server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.

Q-51) What is the out implicit object?
ANS :-
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.

Q-52) What is the difference between JspWriter and PrintWriter?
ANS :-
The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.

Q-53) What is the session Object?
ANS :-
The session object is an instance of javax.servlet.http.HttpSession and is used to track client session between client requests

Q-54) What is an application Object?
ANS :-
The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.

Q-55) What is a config Object?
ANS :-
The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.

Q-56) What is a pageContext Object?
ANS :-
The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page.
This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.

Q-57) What is a page object?
ANS :-
This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page.
The page object is really a direct synonym for the this object.

Q-58) What is an exception Object?
ANS :-
The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition.

Q-59) What is difference between GET and POST method in HTTP protocol?
ANS :-
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? Character.
The POST method packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing.

Q-60) How to read form data using JSP?
ANS :-
JSP handles form data parsing automatically using the following methods depending on the situation:
getParameter(): You call request.getParameter() method to get the value of a form parameter.
getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
getParameterNames(): Call this method if you want a complete list of all parameters in the current request.
getInputStream(): Call this method to read binary data stream coming from the client.

Q-61) What are filters?
ANS :-
JSP Filters are Java classes that can be used in JSP Programming for the following purposes:
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.

Q-62) How do you define filters?
ANS :-
Filters are defined in the deployment descriptor file web.xml and then mapped to either servlet or JSP names or URL patterns in your application's deployment descriptor.
When the JSP container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.

Q-63) What are cookies?
ANS :- 
Cookies are text files stored on the client computer and they are kept for various information tracking purpose.

Q-64) How cookies work?
ANS :-
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser).If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.

Q-65) How do you set cookies in the JSP?
ANS :-
Setting cookies with JSP involves three steps:
Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid.
Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header

Q-66) How to read cookies with JSP?
ANS :-
To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.

Q-67) How to delete cookies with JSP?
ANS :-
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing cookie.
Add this cookie back into response header.

Q-68) How is Session Management done in JSP?
ANS :- 
Session management can be achieved by the use of:
Cookies: A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
Hidden Form Fields: A web server can send a hidden HTML form field along with a unique session ID as follows:
<input type="hidden" name="sessionid" value="12345">
This implies that when the form is submitted, the specified name and value will be getting included in GET or POST method.
URL Rewriting: In URL rewriting some extra information is added on the end of each URL that identifies the session. This URL rewriting can be useful where a cookie is disabled.
The session Object: JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

Q-69) How can you delete a session data?
ANS :-
When you are done with a user's session data, you have several options:
Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key.
Delete the whole session: You can call public void invalidate() method to discard an entire session.
Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.

Q-70) How can you upload a file using JSP?
ANS :-
To upload a single file you should use a single <input .../> tag with attribute type="file".To allow multiple files uploading, include more than one input tags with different values for the name attribute.

Q-71) Where will be the uploaded files stored?
ANS :- 
You can hard code this in your program or this directory name could also be added using an external configuration such as a context-param element in web.xml.

Q-72) What is JSP page redirection?
ANS :-
Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization.

Q-73) What is the difference between <jsp:forward page = ... > and response.sendRedirect(url)?
ANS :-
The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page.

Q-74) What is a hit count for a web page?
ANS :-
A hit counter tells you about the number of visits on a particular page of your web site.

Q-75) How do you impement hit counter in JSP?
ANS :-
To implement a hit counter you can make use of Application Implicit object and associated methods getAttribute() and setAttribute().
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.

Q-76) How can you implement hit counter to avoid loss of count data with each restart of thh application?
ANS :-
You can follow the below steps:
Define a database table with a single count, let us say hitcount. Assign a zero value to it.
With every hit, read the table to get the value of hitcount.
Increase the value of hitcount by one and update the table with new value.
Display new value of hitcount as total page hit counts.
If you want to count hits for all the pages, implement above logic for all the pages.

Q-77) What is auto refresh feature?
ANS :-
Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your web page regularly using refresh or reload button with your browser.
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.

Q-78) How do you implement the auto refresh in JSP?
ANS :-
The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method:
public void setIntHeader(String header, int headerValue)
This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.

Q-79) What is JSTL?
ANS :-
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags.

Q-80) What the different types of JSTL tags are ?
ANS :-
Types of JSTL tags are:
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions

Q-81) What is the use of <c:set > tag?
ANS :-
The <c:set > tag is JSTL-friendly version of the setProperty action. The tag is helpful because it evaluates an expression and uses the results to set a value of a JavaBean or a java.util.Map object.

Q-82) What is the use of <c:remove > tag?
ANS :-
The <c:remove > tag removes a variable from either a specified scope or the first scope where the variable is found (if no scope is specified).

Q-83) What is the use of <c:catch> tag?
ANS :-
The <c:catch> tag catches any Throwable that occurs in its body and optionally exposes it. Simply it is used for error handling and to deal more gracefully with the problem.

Q-84) What is the use of <c:if> tag?
ANS :-
The <c:if> tag evaluates an expression and displays its body content only if the expression evaluates to true.

Q-85) What is the use of <c:choose> tag?
ANS :-
The <c:choose> works like a Java switch statement in that it lets you choose between a number of alternatives. Where the switch statement has case statements, the <c:choose> tag has <c:when> tags. A a switch statement has default clause to specify a default action and similar way <c:choose> has <otherwise> as default clause.

Q-86) What is the use of <c:forEach >, <c:forTokens> tag?
ANS :-
The <c:forEach >, <c:forTokens> tags exist as a good alternative to embedding a Java for, while, or do-while loop via a scriptlet.

Q-87) What is the use of <c:param> tag?
ANS :-
The <c:param> tag allows proper URL request parameter to be specified with URL and it does any necessary URL encoding required.

Q-88) What is the use of <c:redirect > tag?
ANS :-
The <c:redirect > tag redirects the browser to an alternate URL by providing automatically URL rewriting, it supports context-relative URLs, and it supports the <c:param> tag.

Q-89) What is the use of <c:url> tag?
ANS :- 
The <c:url> tag formats a URL into a string and stores it into a variable. This tag automatically performs URL rewriting when necessary.

Q-90) What are JSTL formatting tags ?
ANS :-
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web sites. Following is the syntax to include Formatting library in your JSP:
<%@ taglib prefix="fmt" 
           uri="http://java.sun.com/jsp/jstl/fmt" %>

Q-91) What are JSTL SQL tags?
ANS :-
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql" 
           uri="http://java.sun.com/jsp/jstl/sql" %>

Q-92) What are JSTL XML tags?
ANS  :-
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents. Following is the syntax to include JSTL XML library in your JSP.
<%@ taglib prefix="x" 
           uri="http://java.sun.com/jsp/jstl/xml" %>

Q-93) What is a JSP custom tag?
ANS :-
A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.

Q-94) What is JSP Expression Language?
ANS :-
JSP Expression Language (EL) makes it possible to easily access application data stored in JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b) logical. A simple syntax for JSP EL is :
${expr}
Here expr specifies the expression itself.

Q-95) What are the implicit EL objects in JSP ?
ANS :-
The JSP expression language supports the following implicit objects:
pageScope: Scoped variables from page scope
requestScope: Scoped variables from request scope
sessionScope: Scoped variables from session scope
applicationScope: Scoped variables from application scope
param: Request parameters as strings
paramValues: Request parameters as collections of strings
headerHTTP: request headers as strings
headerValues: HTTP request headers as collections of strings
initParam: Context-initialization parameters
cookie: Cookie values
pageContext: The JSP PageContext object for the current page

Q-96) How can we disable EL ?
ANS :-
We can disable using isELIgnored attribute of the page directive:
<%@ page isELIgnored ="true|false" %> If it is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container.

Q-97) What type of errors you might encounter in a JSP code?
ANS :-
Checked exceptions: Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Q-98) In JSP page how can we handle runtime exception?
ANS :-
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-99) What is Internationalization?
ANS :-
Internationalization means enabling a web site to provide different versions of content translated into the visitor's language or nationality.

Q-100) What is Localization?
ANS :-
Localiztion means adding resources to a web site to adapt it to a particular geographical or cultural region for example Hindi translation to a web site.

Q-101) What is locale?
ANS :-
This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example "en_US" represents english locale for US.

Q-102) What is difference between <%-- comment --%> and <!-- comment -->?
ANS :-
<%-- comment --%> is JSP comment and is ignored by the JSP engine.
<!-- comment --> is an HTML comment and is ignored by the browser.

Q-103) Is JSP technology extensible?
ANS :-
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

Q-104) How do I include static files within a JSP page?
ANS :-
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

Q-106) Can a JSP page process HTML FORM data?
ANS :-
Yes. However, unlike Servlet, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression.

Q-107) How do you pass control from one JSP page to another?
ANS :-
Use the following ways to pass control of a request from one servlet to another or one jsp to another:
The RequestDispatcher object ‘s forward method to pass the control.
Using the response.sendRedirect method.

Q-108) Can you make use of a ServletOutputStream object from within a JSP page?
ANS :-
No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients.
A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not.

Q-109) What is the page directive is used to prevent a JSP page from automatically creating a session?
ANS :-
<%@ page session="false">

Q-110) How to pass information from JSP to included JSP?
ANS :-
Using <%jsp:param> tag.

Q-111) Can we override the jspInit(), _jspService() and jspDestroy() methods?
ANS :-
We can override jspinit() and jspDestroy() methods but not _jspService().

Q-112) Why is _jspService() method starting with an '_' while other life cycle methods do not?
ANS :-
_jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page.

Q-113) A JSP page, include.jsp, has a instance variable "int a", now this page is statically included in another JSP page, home.jsp, which also has an instance variable "int a" declared. What happens when the home.jsp page is requested by the client?
ANS :-
It causes compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error.

Q-114) How is scripting disabled?
ANS :-
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-115) When do use application scope?
ANS :-
If we want to make our data available to the entire application then we have to use application scope.

Q-116) What are the options in JSP to include files?
ANS :- In JSP, we can perform inclusion in the following ways:
By include directive: For example:
<%@ include file=”header.jsp” %>
By include action: For example:
<%@ include file=”header.jsp” %>
By using pageContext implicit object For example:
<%
     pageContext.include(“/header.jsp”);
%>
By using RequestDispatcher object: For example:
<%
 RequestDispatcher rd = request.getRequestDispatcher(“/header.jsp”);
  Rd.incliude(request,response);
%>

Q-117) How does JSP engines instantiate tag handler classes instances?
ANS :-
JSP engines will always instantiate a new tag handler instance every time a tag is encountered in a JSP page. A pool of tag instances are maintained and reusing them where possible. When a tag is encountered, the JSP engine will try to find a Tag instance that is not being used and use the same and then release it.

Q-118) What’s the difference between JavaBeans and taglib directives?
ANS : -
JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them:
Taglibs are for generating presentation elements while JavaBeans are good for storing information and state.
Use custom tags to implement actions and JavaBeans to present information.

No comments:

Post a Comment