What is JSP and why it is different than Servlet

Q:What is JSP?
A:JavaServer Pages (JSP) is a server side technology for developing web pages that support static as well as dynamic content.
JSP has 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:Can you explain What is JSP page life cycle? 
A:JSP lifecycle phases are:
Translation and Compilation– JSP container checks the JSP page code and parse it to generate the servlet source code and compile that to generate class file.After this same will get loaded in memory.
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.
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 – It 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:Why do I need JSP technology if I already have servlets? 
A:JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets. 
Q:What are JSP lifecycle methods?
A:JSP lifecycle methods are:
jspInit(): 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(): It 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
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:What are different types of comments in JSP?
A:JSP pages provide two types of comments that we can use:
HTML Comments:<-- HTML Comment -->
JSP Comments:<%-- JSP Comment --%>
Q:What is Scriptlet, Expression and Declaration in JSP?
A:A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet:
<% code fragment %>
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file.
<%! declaration;  declaration1; ... %>
A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.
Its syntax is:
<%= expression %>
Q:What are JSP Directives? 
A:JSP Directives are the messages to JSP page.
It usually has the following form:
<%@ directive attribute="value" %>
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:What are implicit objects in JSP?
A:JSP page has 9 implicit object which are local to service method:
out:out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response.
request: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: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.
config:JSP config implicit object is instance of javax.servlet.ServletConfig implementation and used to get the JSP init params configured in deployment descriptor.
application: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:JSP session object is an instance of javax.servlet.http.HttpSession and is used to track client session between client requests
pageContext:JSP 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.
page: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.
exception: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. 
Q:What are JSP actions?
A: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.
Its syntax is as follows:
<jsp:action_name attribute="value" />
Some of the important action elements: 
jsp:useBean:To create object of bean class.
<jsp:useBean id="bean name" class="bean class" scope = "page | request | session |application "/>
jsp:getProperty: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.
jsp:setProperty:The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action.
jsp:include:This action lets you insert files into the page being generated.
<jsp:include page="relative URL" flush="true" />
jsp:forward:It forwards the current request to another JSP page.
< jsp:forward page="...url..." />
Q:How can we disable java code or scripting in JSP page?
A:We can disable scripting elements in JSP pages through deployment descriptor configuration like below.
Q:How do we prevent browser from caching output of my JSP pages?
A:We can prevent pages from caching JSP pages output using the below code snippet. <%response.setHeader("Cache-Control","no-cache");%>
Q:What is the difference between <jsp:forward page = ... > and response.sendRedirect(url)?
A:<jsp:forward> 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:what is JSTL?
A:JSTL is also called as JSP tag libraries. They are collection of custom actions which can be accessed as JSP tags.
Tags are classified in to four groups:-
Core Tags – Core tags provide support for iteration, conditional logic, catch exception, url, forward or redirect response etc.
Formatting and Localization Tags – These tags are provided for formatting of Numbers, Dates and i18n support through locales and resource bundles.
SQL Tags – JSTL SQL Tags provide support for interaction with relational databases such as Oracle, MySql etc.
XML Tags – XML tags are used to work with XML documents such as parsing XML, transforming XML data and XPath expressions evaluation.
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.
Q:How do you implement the auto refresh in JSP?
A:setIntHeader("Refresh",60) in sec.
Q:What is difference between include directive and jsp:include action?
A:The difference between JSP include directive and include action is that in include directive the content to other resource is added to the generated servlet code at the time of translation whereas with include action it happens at runtime.
We can pass params to be used in the included resource with jsp:param action element but in JSP include directive we can’t pass any params.
When included resource is static such as header, footer, image files then we should use include directive for faster performance but if the included resource is dynamic and requires some parameters for processing then we should use include action tag.
Q:What is JSP Expression Language?
A: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 :
We can disable using isELIgnored attribute of the page directive:
<%@ page isELIgnored ="true|false" %>
JSP Expression Language provides many implicit objects that we can use to get attributes from different scopes and parameter values.
The only common implicit object in JSP EL and JSP page is pageContext object.
Q:In JSP page how can we handle runtime exception?
A: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" %>
Q:Can I create XML pages using JSP technology? 
A:Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output.

Leave a Reply

Your email address will not be published. Required fields are marked *