JSP
1: What is the difference
between <jsp:include page = ... > and <%@ include file = ... >?
A: Both the tag includes the
information from one page in another. The differences are as follows:
<jsp:include page = ... >: This is like a function call from one
jsp to another jsp. It is executed (the included page is executed and the generated html content is included in
the content of calling jsp) each time the client page is accessed by the
client. This approach is useful to for modularizing the web application. If the
included file changed then the new content will be included in the output.
<%@ include file = ... >: In this case the content of the
included file is textually embedded in the page that have <%@ include file="..">
directive. In this case in the included file changes, the changed content will
not included in the output. This approach is used when the code from one jsp
file required to include in multiple jsp files.
2: What is the difference
between <jsp:forward page = ... > and response.sendRedirect(url),?.
A: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. The
response.sendRedirect kills the session variables.
3: What do you understand by JSP
Actions?
A: JSP actions are XML tags
that direct the server to use existing components or control the behavior of
the JSP engine. JSP Actions consist of a typical (XML-based) prefix of
"jsp" followed by a colon, followed by the action name followed by
one or more attribute parameters.
There are six JSP Actions:
<jsp:include/>
<jsp:forward/>
<jsp:plugin/>
<jsp:usebean/>
<jsp:setProperty/>
<jsp:getProperty/>
4: Identify the advantages of
JSP over Servlet.
a) Embedding of Java code in HTML pages
b) Platform independence
c) Creation of database-driven Web applications
d) Server-side programming capabilities
5. Difference Between include Directive and
include Action of JSP.
Include Directive <%@
include file="fileName" %>
|
Include Action <jsp:include
page=”relativeURL” />
|
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 cannot 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
|
Request and Response object is passed between calling JSP and
included JSP.
|
6: Is it possible for one JSP to
extend another java class if yes how?
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 it’s possible to extend another java class . This
question can be tricky if you don’t know some basic fact, though it’s not advisable
to write java code in JSP instead it’s better to use expression language and
tag library.
7: What is < jsp:usebean
>tag why it is used.
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" />
<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.
8: How can one Jsp Communicate
with Java file.
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 object and use it in our page.
9: what are implicit Objects?
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
and by default available in JSP page.
We have 9 implicit objects that we can directly use in
JSP page. Seven of them are declared as local variable at the start of
_jspService() method whereas two of them are part of _jspService() method
argument that we can use.
They are: out, request, response, pageContext, session,
application, config, page, and exception.
out
Object
JSP out implicit object is instance of
javax.servlet.jsp.JspWriter implementation and it’s used to output
content to be sent in client response. This is one of the mostly used JSP
implicit object and that’s why we have JSP Expression to easily invoke out.print()
method.
request
Object
JSP request implicit object is instance
of javax.servlet.http.HttpServletRequest
implementation and it’s one of the argument of JSP service method. We can use
request object to get the request parameters, cookies, request attributes,
session, header information and other details about client request.
response
Object
JSP response implicit object is instance
of javax.servlet.http.HttpServletResponse
implementation and comes as argument of service method. We can response object
to set content type, character encoding, header information in response, adding
cookies to response and redirecting the request to other resource.
config
Object
JSP config implicit object is instance of
javax.servlet.ServletConfig
implementation and used to get the JSP init params configured in deployment
descriptor.
application
Object
JSP application implicit object is
instance of javax.servlet.ServletContext implementation and it’s used to
get the context information and attributes in JSP. We can use it to get the
RequestDispatcher object in JSP to forward the request to another resource or
to include the response from another resource in the JSP.
session
Object
JSP session implicit object is instance
of javax.servlet.http.HttpSession
implementation. Whenever we request a JSP page, container automatically creates
a session for the JSP in the service method.
Since session management
is heavy process, so if we don’t want session to be created for JSP, we can use
page directive to not create the session for JSP using <%@ page
session="false" %>. This is very helpful when our login page or
the index page is a JSP page and we don’t need any user session there.
pageContext
Object
JSP pageContext implicit object is
instance of javax.servlet.jsp.PageContext abstract class implementation. We
can use pageContext to get and set attributes with different scopes and to
forward request to other resources. pageContext object also hold reference to
other implicit object.
page
Object
JSP page implicit object is instance of java.lang.Object
class and represents the current JSP page. page object provide reference to the
generated servlet class. This object is very rarely used.
exception
Object
JSP exception implicit object is instance
of
java.lang.Throwable class and used to provide exception details in JSP
error pages. We can’t use this object in normal JSP pages and it’s available
only in JSP error pages.
JSP Implicit Objects Example:
<%@ page
language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%@ page
import="java.util.Date" %>
<!DOCTYPE html PUBLIC
"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html;
charset=US-ASCII">
<title>Index JSP
Page</title>
</head>
<body>
<%-- out object example
--%>
<h4>Hi There</h4>
<strong>Current Time
is</strong>: <%
out.print(new Date()); %><br><br>
<%-- request object example
--%>
<strong>Request
User-Agent</strong>: <%=request.getHeader("User-Agent")
%><br><br>
<%-- response object example
--%>
<%response.addCookie(new
Cookie("Test","Value")); %>
<%-- config object example
--%>
<strong>User init param
value</strong>:<%=config.getInitParameter("User")
%><br><br>
<%-- application object
example --%>
<strong>User context param
value</strong>:<%=application.getInitParameter("User")
%><br><br>
<%-- session object example
--%>
<strong>User Session
ID</strong>:<%=session.getId()
%><br><br>
<%-- pageContext object
example --%>
<% pageContext.setAttribute("Test",
"Test Value"); %>
<strong>PageContext
attribute</strong>: {Name="Test",Value="<%=pageContext.getAttribute("Test")
%>"}<br><br>
<%-- page object example
--%>
<strong>Generated Servlet
Name</strong>:<%=page.getClass().getName()
%>
</body>
</html>
web.xml
<?xml version="1.0"
encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
mlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>JSPImplicitObjects</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>User</param-name>
<param-value>Admin</param-value>
</context-param>
<servlet>
<servlet-name>home</servlet-name>
<jsp-file>/index.jsp</jsp-file>
<init-param>
<param-name>User</param-name>
<param-value>Pankaj</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home.do</url-pattern>
<url-pattern>/home.jsp</url-pattern>
</servlet-mapping>
</web-app>
10: In JSP page how can we
handle runtime exception?
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" %>
11: Why is _jspService() method
starting with an '_' while other life cycle methods do not?
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 can’t override this method.
12: How can you pass information
form one jsp to included jsp?
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"/>
13: what is the need of tag
library?
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.
13: What are all the different
scope values for the <jsp:useBean> tag?
<jsp:useBean> tag is used to use any java object in the jsp page.
Here are the scope values for <jsp:useBean> tag:
a) page
b) request
c) session and
d) application
14: What is expression in JSP?
Answer: Expression tag is used to insert Java values directly into the
output. Syntax for the Expression tag is:
<%= expression %>
An expression tag contains a scripting language expression that is
evaluated, converted to a String, and inserted where the expression appears in
the JSP file. The following expression tag displays time on the output:
<%=new java.util.Date()%>
15: What is JSP declaration?
JSP Declaratives are the JSP tag used to declare variables.
Declaratives are enclosed in the <%! %> tag and ends in semi-colon. You can
declare variables and functions in the declaration tag and can use anywhere in
the JSP. Here is the example of declaratives:
<%@page contentType="text/html" %>
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
</body>
</html>
16: What is JSP Scriptlet?
JSP Scriptlet is jsp tag which is used to enclose java code in the JSP
pages. Scriptlets begins with <% tag and ends with %> tag. Java code
written inside scriptlet executes every time the JSP is invoked.
Example:
<%
//java codes
String
userName=null;
userName=request.getParameter("userName");
%>
17: What types of comments are
available in the JSP?
There are two types of comments are allowed in the JSP. These are
hidden and output comments. A hidden comment does not appear in the generated
output in the html, while output comments appear in the generated output.
Example of hidden comment:
<%-- This is hidden comment --%> JSP Comment
Example of output comment:
<!-- This is output comment --> HTML Comment
18: 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 can't
be overridden.
c) jspDestroy(): The container calls this when servlet instance is
about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP
page.
19: What is JSP Custom tags?
JSP Custom tags are user defined JSP language element. JSP custom tags
are user defined tags that can encapsulate common functionality. For example
you can write your own tag to access the database and performing database
operations. You can also write custom tag for encapsulate both simple and complex
behaviors in an easy to use syntax and greatly simplify the readability of JSP
pages.
20: What is JSP?
Answer: Java Server Pages (JSP) technology is the Java platform
technology for delivering dynamic content to web clients in a portable, secure
and well-defined way. The JavaServer Pages specification extends the Java
Servlet API to provide web application developers.
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.
21: What is the role of JSP in
MVC Model?
JSP is mostly used to develop the user interface, It plays are role of
View in the MVC Model.
22: What do you understand by
context initialization parameters?
The context-param element contains the declaration of a web
application's servlet context initialization parameters.
<context-param>
<param-name>name</param-name>
<param-value>value</param-value>
</context-param>
The Context Parameters page lets you manage parameters that are
accessed through the ServletContext.getInitParameterNames
and ServletContext.getInitParameter
methods.
23: Can you extend JSP
technology?
JSP technology lets the programmer to extend the JSP to make the
programming more easier. JSP can be extended and custom actions and tag
libraries can be developed.
24: What do you understand by
JSP translation?
JSP translators generate standard Java code for a JSP page
implementation class. This class is essentially a servlet class wrapped with
features for JSP functionality.
25: What you can stop the
browser to cash your page?
Answer: Instead of deleting a cache, you can force the browser not to
catch the page.
<%
response.setHeader("pragma","no-cache");//HTTP
1.1
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.addDateHeader("Expires", -1);
response.setDateHeader("max-age", 0);
//response.setIntHeader ("Expires", -1);
//prevents caching at the proxy server
response.addHeader("cache-Control", "private");
%>
put the above code in your page.
26: Advantages of JSP over
Servlets
Servlets use println statements for printing an HTML document which is
usually very difficult to use. JSP has no such tedius task to maintain. JSP
needs no compilation, CLASSPATH setting and packaging. In a JSP page visual
content and logic are separated, which is not possible in a servlet. There is
automatic deployment of a JSP, recompilation is done automatically when changes
are made to JSP pages. Usually with JSP, Java Beans and custom tags web
application is simplified.
27: What are different ways of
managing session in JSP?
We have 4 ways to manage a session.
1.
Cookies
2.
URL rewriting
3.
Hidden form fields
4.
HTTP session
The fourth one is powerful and mostly used now-a-days.
28: What is the difference
between
Object foo = "something";
String bar = String.valueOf(foo);
and
Object foo = "something";
String bar = (String) foo;
Casting to string only works when the object actually is a string:
Object reallyAString = "foo";
String str = (String) reallyAString; // works.
It won't work when the object is
something else:
Object notAString = new Integer(42);
String str = (String) notAString; // will throw a
ClassCastException
String.valueOf() however will try to convert whatever you pass into it
to a String. It handles both primitives (42) and objects (new Integer(42),
using that object's toString()):
String str;
str = String.valueOf(new Integer(42)); // str will hold
"42"
str = String.valueOf("foo"); // str will hold
"foo"
str = String.valueOf(null); // str will hold
"null"
Note especially the last example: passing null to String.valueOf() will
return the string "null"
29: How to use foreach loop to
read values from session map in JSP?
//Java
List<String> cityList = new
ArrayList<String>();
cityList.add("Washington DC");
cityList.add("Delhi");
request.setAttribute("cityList", cityList);
//JSP
<c:forEach var="city"
items="cityList">
<b>
${city} </b>
</c:forEach>
30: What are the JSP lifecycle phases?
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:
A.
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 atTOMCAT/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
B.
Compilation – JSP container compiles the jsp class source code and
produce class file in this phase.
C.
Class Loading – Container loads the class into memory in this phase.
D.
Instantiation – Container invokes the no-args constructor of generated
class to load it into memory and instantiate it.
E.
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.
F.
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.
G.
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.
31: How can we avoid direct
access of JSP pages from client browser?
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>
32: Can we use JSP implicit
objects in a method defined in JSP Declaration?
No we can’t because JSP implicit objects are local to service method
and added by JSP Container while translating JSP page to servlet source code.
JSP Declarations code goes outside the service method and used to create class
level variables and methods and hence can’t use JSP implicit objects.
33: Which implicit object is not
available in normal JSP pages?
JSP exception implicit
object is not available in normal JSP pages and it’s used in JSP error pages
only to catch the exception thrown by the JSP pages and provide useful message
to the client.
34: What are the benefits of
PageContext implicit object?
JSP pageContext implicit object is instance of
javax.servlet.jsp.PageContext abstract class implementation. We can use
pageContext to get and set attributes with different scopes and to forward
request to other resources. pageContext object also hold reference to other
implicit object.
This is the only object that is common in both JSP implicit objects and
in JSP EL implicit objects.
35: How do we configure init
params for JSP?
We can configure init params for JSP similar to servlet in web.xml
file, we need to configure JSP init params with servlet and servlet-mapping
element. The only thing differs from servlet is jsp-file element where we need to provide the JSP page location.
36: Why use of scripting
elements in JSP is discouraged?
JSP pages are mostly used for view purposes and all the business logic
should be in the servlet or model classes. We should pass parameters to JSP
page through attributes and then use them to create the HTML response in JSP
page.
Most part of the JSP page contains HTML code and to
help web designers to easily understand JSP page and develop them, JSP
technology provides action elements, JSP EL, JSP Standard Tag Library and
custom tags that we should use rather than scripting elements to bridge the gap
between JSP HTML part and JSP java part.
37: How can we disable java code
or scripting in JSP page?
We can disable scripting elements in JSP pages through deployment
descriptor configuration like below.
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
Above url-pattern will disable scripting for all the JSP pages but if
you want to disable it only for specific page, you can give the JSP file name
itself.
38: Explain JSP Action Elements or Action Tags?
JSP action elements or action tags are HTML like tags that provide
useful functionalities such as working with Java Bean, including a resource,
forwarding the request and to generate dynamic XML elements. JSP action
elements always starts with jsp: and we can use them in JSP page directly
without the need to import any tag libraries or any other configuration
changes. Some of the important action elements are jsp:useBean,
jsp:getProperty, jsp:setProperty, jsp:include and jsp:forward.
39: What is JSP Expression
Language and what are it’s benefits?
Most of the times we use JSP for view purposes and all the business
logic is present in servlet code or model classes. When we receive client
request in servlet, we process it and then add attributes in request/session/context
scope to be retrieved in JSP code. We also use request params, headers, cookies
and init params in JSP to create response views.
We can use scriptlets and JSP expressions to retrieve
attributes and parameters in JSP with java code and use it for view purpose.
But for web designers, java code is hard to understand and that’s why JSP Specs
2.0 introduced Expression Language (EL) through which we can get attributes and
parameters easily using HTML like tags.
Expression language syntax is ${name} and we can use EL implicit objects and EL operators to
retrieve the attributes from different scopes and use them in JSP page.
40: What are JSP EL implicit objects and how it’s different from JSP
implicit Objects?
JSP Expression Language provides many implicit objects that we
can use to get attributes from different scopes and parameter values. Note that
these are different from JSP implicit objects and contains only the attributes
in given scope. The only common implicit object in JSP EL and JSP page is pageContext object.
Below
table provides list of implicit object in JSP EL.
JSP EL Implicit Objects
|
Type
|
Description
|
pageScope
|
Map
|
A map that
contains the attributes set with page scope.
|
requestScope
|
Map
|
Used to get the
attribute value with request scope.
|
sessionScope
|
Map
|
Used to get the
attribute value with session scope.
|
applicationScope
|
Map
|
Used to get the
attributes value from application scope.
|
param
|
Map
|
Used to get the
request parameter value, returns a single value
|
paramValues
|
Map
|
Used to get the
request param values in an array, useful when request parameter contain
multiple values.
|
header
|
Map
|
Used to get
request header information.
|
headerValues
|
Map
|
Used to get
header values in an array.
|
cookie
|
Map
|
Used to get the
cookie value in the JSP
|
initParam
|
Map
|
Used to get the
context init params, we can’t use it for servlet init params
|
pageContext
|
pageContext
|
Same as JSP
implicit pageContext object, used to get the request, session references etc.
example usage is getting request HTTP Method name.
|
41: How to use JSP EL to get HTTP method name?
We can use pageContext JSP EL
implicit object to get the request object reference and use dot operator to get
the HTTP method name in JSP page. The JSP EL code for this will be ${pageContext.request.method}.
JSP Standard Tag Library or JSTL is more versatile than JSP EL
or Action elements because we can loop through a collection or escape HTML tags
to show them like text in response.
JSTL is part of the Java EE API
and included in most servlet containers. But to use JSTL in our JSP pages, we
need to download the JSTL jars for your servlet container. Most of the times,
you can find them in the example projects and you can use them. You need to
include these libraries in the project WEB-INF/lib directory. These jars are
container specific, for example in Tomcat, we need to include jstl.jar and standard.jar jar files in project build path.
43: What are the types of JSTL tags?
Based
on the JSTL functions, they are categorized into five types.
A. Core
Tags –
Core tags provide support for iteration, conditional logic, catch exception,
url, forward or redirect response etc.
<%@
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
%>
B. Formatting
and Localization Tags –
These tags are provided for formatting of Numbers, Dates and i18n support
through locales and resource bundles.
<%@
taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"
%>
C. SQL
Tags –
JSTL SQL Tags provide support for interaction with relational databases such as
Oracle, MySql etc.
<%@
taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"
%>
D. XML
Tags –
XML tags are used to work with XML documents such as parsing XML, transforming
XML data and XPath expressions evaluation.
<%@
taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"
%>
E. JSTL
Functions Tags –
JSTL tags provide a number of functions that we can use to perform common
operation, most of them are for String manipulation such as String
Concatenation, Split String etc.
<%@
taglib uri="http://java.sun.com/jsp/jstl/functions"
prefix="fn" %>
44. What is JSP Custom Tag and what
are its components?
Sometimes
JSP EL, Action Tags and JSTL tags are not enough and we might get tempted to
write java code to perform some operations in JSP page. Fortunately JSP is
extendable and we can create our own custom tags to perform certain operations.
We
can create JSP Custom Tags with following components:
a.
JSP Custom Tag Handler
b.
Creating Tag Library Descriptor (TLD) File
c.
Deployment Descriptor Configuration for TLD
We
can add custom tag library in JSP page using taglib directive and then use it.
45. Why don’t we need to
configure JSP standard tags in web.xml?
We don’t need to configure JSP standard tags in web.xml because the TLD
files are inside the META-INF directory of the JSTL jar files. When container
loads the web application and find TLD files inside the META-INF directory of
JAR file, it automatically configures them to be used directly in the
application JSP pages. All we need to do it to include it in the JSP page using
taglib directive.
46. How can we handle exceptions
thrown by JSP service method?
To handle exceptions thrown by the JSP page, all we need is an error
page and define the error page in JSP using page directive.
To create a JSP error page, we need to set page directive attribute
isErrorPage value to true, then we can access exception implicit object in the
JSP and use it to send customized error message to the client.
We need to define exception and error handler JSP pages in the
deployment descriptor like below.
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
47. How do we catch exception
and process it using JSTL?
We can use JSTL Core tags c:catch and c:if to catch exception inside
the JSP service method and process it. c:catch tag catches the exception and
wraps it into the exception variable and we can use c:if condition tag to
process it. Below code snippet provide sample usage.
<c:catch var ="exception">
<% int x = 5/0;%>
</c:catch>
<c:if test = "${exception ne null}">
<p>Exception is :
${exception} <br />
Exception Message:
${exception.message}</p>
</c:if>
48. What is jsp-config in
deployment descriptor?
jsp-config element is used to configure different parameters for JSP
pages. Some of it’s usage are:
Configuring tag libraries for the web application like below.
<jsp-config>
<taglib>
<taglib-uri>http://journaldev.com/jsp/tlds/mytags</taglib-uri>
<taglib-location>/WEB-INF/numberformatter.tld</taglib-location>
</taglib>
</jsp-config>
We can control scripting elements in JSP pages.
We can control JSP Expression Language (EL) evaluation in JSP pages.
We can define the page encoding for URL pattern.
To define the buffer size to be used in JSP page out object.
To denote that the group of resources that match the URL pattern are
JSP documents, and thus must be interpreted as XML documents.
49. How to ignore the EL
expression evaluation in a JSP?
We can ignore EL evaluation in JSP page by two ways.
Using page directive as <%@ page isELIgnored="true" %>
Configuring in web.xml – better approach when you want to disable EL
evaluation for many JSP pages.
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
</jsp-property-group>
</jsp-config>
50. When will Container
initialize multiple JSP/Servlet Objects?
If we have multiple servlet and servlet-mapping elements in deployment
descriptor for a single servlet or JSP page, then container will initialize an
object for each of the element and all of these instances will have their own
ServletConfig object and init params.
For example, if we configure a single JSP page in web.xml like below.
<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>
<servlet>
<servlet-name>Test1</servlet-name>
<jsp-file>/WEB-INF/test.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Test1</servlet-name>
<url-pattern>/Test1.do</url-pattern>
</servlet-mapping>
Then if we can access same JSP page with both the URI pattern and both
will have their own init params values.
51. How can we prevent implicit
session creation in JSP?
By default JSP page creates a session but sometimes we don’t need
session in JSP page. We can use JSP page directive session attribute to
indicate compiler to not create session by default. It’s default value is true
and session is created. To disable the session creation, we can use it like
below.
<%@ page session ="false" %>
52. What is difference between
JspWriter and Servlet PrintWriter?
PrintWriter is the actual object responsible for writing the content in
response. JspWriter uses the PrintWriter object behind the scene and provide
buffer support. When the buffer is full or flushed, JspWriter uses the
PrintWriter object to write the content into response.
53.How can we extend JSP
technology?
We can extend JSP technology with custom tags to avoid scripting
elements and java code in JSP pages.
54.Provide some JSP Best
Practices?
Some of the JSP best practices are:
A.
Avoid scripting elements in JSP pages. If JSP
EL, action elements and JSTL not serve your needs then create custom tags.
B.
Use comment properly, use JSP comments for code
level or debugging purpose so that it’s not sent to client.
C.
Avoid any business logic in JSP page, JSP pages
should be used only for response generation for client.
D.
Disable session creation in JSP page where you
don’t need it for better performance.
E.
Use page, taglib directives at the start of JSP
page for better readability.
F.
Proper use of jsp include directive or include
action based on your requirements, include directive is good for static content
whereas include action is good for dynamic content and including resource at
runtime.
G.
Proper exception handling using JSP error pages
to avoid sending container generated response incase JSP pages throw exception
in service method.
H.
If you are having CSS and JavaScript code in JSP
pages, it’s best to place them in separate files and include them in JSP page.
I.
Most of the times JSTL is enough for our needs,
if you find a scenario where it’s not then check your application design and
try to put the logic in a servlet that will do the processing and then set
attributes to be used in JSP pages.
How can we declare third party classes and interfaces inside our jsp
page?
How can we declare and definr global variables and methods inside our
jsp page?
If we are declaring global variables and methods inside the jsp
page.Where the global variables are going into generated servlet?
Can we print the messages by using the expressions in case of jsp?
Is it possible to incorporate local members using scriplets(Y/N)?
While developing any jsp page, server can develop a .java file for a
particular jsp page or not?
What are the different types of directives in jsp?
While developing any jsp page inside the tomcat server where the server
generates the generated servlet?
If server is generating the servlet for every particular jsp page ,that
generated servlet is final (Y/N)?
Every generated servlet by the server for a particular jsp is subclass
to HttpJspBase?
Every generated servlet by the server for a particular jsp is subclass
to HttpJspBase.Here HttpJspBase is from which package?
HttpJspBase is subclass to HttpServlet(Y/N)?
All over rided methods from the HttpServlet to the HttpJspBase are
final methods (Y/N)?
In case of jsp what could be the default executable method inside the
generated servlet?
If we are developing jsp pages inside eclipse in which location server
is generating the servlets for particular jsp pages?
If we want to develop any jsp pages using eclipse where we can develop
under web application?
Is it Possible to include text file to jsp pages(Y/N)?
Is it Possible to include html pages to jsp pages(Y/N)?
No comments:
Post a Comment