Google News
logo
JSP Interview Questions
Java Server Pages (JSP) technology, is a server-side programming language used to create a dynamic web page in the form of HyperText Markup Language (HTML). It is an extension to the servlet technology.
 
A JSP page is internally converted into the servlet. JSP has access to the entire family of the Java API including JDBC API to access enterprise database. Hence, Java language syntax has been used in the java server pages (JSP). The JSP pages are more accessible to maintain than Servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tags, etc.
The JSP container has a special servlet called the page compiler. All HTTP requests with URLs that match the .jsp file extension are forwarded to this page compiler by the configuration of the servlet container. The servlet container is turned into a JSP container with this page compiler. When a .jsp page is first called, the page compiler parses and compiles the .jsp page into a servlet class. The JSP servlet class is loaded into memory on the successful compilation. For the subsequent calls, the servlet class for that .jsp page is already in memory. Hence, the page compiler servlet will always compare the timestamp of the JSP servlet with the JSP page. If the .jsp page is more current, recompilation is necessary. With this process, once deployed, JSP pages only go through the time-consuming compilation process once.
When a container loads a JSP, it invokes the jspInit() method before servicing any requests.
public void jspInit(){
  // Initialization code...
}

 

Earlier, Common Gateway Interface (CGI) was the only tool for developing dynamic web content and was not very efficient. The web server has to create a new operating system process, load an interpreter and a script, execute the script, and then tear it all down again, for every request that comes in. This is taxing for the server and doesn’t scale well when the number of traffic increases.
 
Alternatives such as ISAPI from Microsoft, and Java Servlets from Sun Microsystems, offer better performance and scalability. However, they generate web pages by embedding HTML directly in programming language code. JavaServer Pages (JSP) changes all of that.
* Better performance.

* JSP has access to all-powerful enterprises.

* JSP can also be used in combination with servlets.

* The compilation of JSP is done before it is processed by the server which eradicates the need for loading of interpreter and code script each time.

* Easy to maintain : JSP can be easily managed because we can easily separate our business logic with presentation logic. In Servlet technology, we mix our business logic with the presentation logic.

 
Objects created by web container and contain information regarding a particular request, application or page are called Implicit Objects. They are :
 
* response
* exception
* application
* request
* session
* page
* out
* config
* pageContext
JSP action tags are HTML-like tags that provide useful functionalities such as JSP:useBean is to work with Java Bean, JSP:include a resource, JSP:forward is to forward the request or response, JSP:setProperty is to set a property value in bean object. JSP action tag always starts with JSP : and we can use them in the JSP page directly without any need for configuration changes or importing any library.
Any JSP file goes through 7 stages and that is called life cycle phases :
 
* Translation: JSP first goes to the Container, where it is parsed to generate servlet code. If the servlet class is older than JSP, then the Container parses it again. Else it is skipped.

* Compilation: After translation, Container compiles JSP source code to create a class file.

* Loading: The Container loads the compiled class into memory.

* Instantiation: Container invokes constructor that has zero arguments to instantiate it. 

* Initialization: Container Calls the jspInit() method to initialize the servlet instance. After this, JSP can handle the client request.

* Request Processing: After initialization, new threads are created with the _jspService() method. This method will have request and response object parameters. Each thread will process client requests the same as the servlet.

* Destroy: After the processing is over, the JSP class is unloaded from memory using the jspDestroy() method.
JSP makes use of Java language for server-side scripting; they are secure, platform-independent, and simplifies dynamic web page creation and management.
A Java servlet template engine is a technology for separating presentation from processing. Template engines have been developed as open-source products to help get HTML out of the servlets. These template engines are intended to be used together with pure code components (servlets) and use only web pages with scripting code for the presentation part.
JSP is a server-side scripting language as it runs on the server. Whereas, JavaScript runs on the client. Commonly, JSP is more used to change the content of a webpage, and JavaScript for the presentation. Both are quite commonly used on the same page.
No. The exception implicit object can only be used in the error page which defines it with the isErrorPage attribute of page directive.
JSP is usually used for presentation in the MVC pattern (Model View Controller ), i.e., it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, and this data is then presented to the JSP for rendering on to the client.
14 .
What are the different scope values for the <jsp:useBean> tag?
There are 4 values :
 
* page
* request
* session
* application
request.getRequestDispatcher(path) is used to create it we need to give the relative path of the resource whereas context.getRequestDispatcher(path) to create it we need to give the absolute path of the resource.
The Literals used in JSP are as follows :
 
* Null
* Boolean
* String
* Integer
* Float
The major difference between ServletContect and PageContext is, the ServletContext is designed to provide information about the Container and on the other hand, the PageContext is designed to provide information about the Request.
Custom Tags in JSP are created using the following steps :
 
* Creating the Tag Handler Class
* Creating the TLD File
* Creating the JSP File

Creating the Tag Handler Class : To create a Tag Handler Class, we need to inherit the TagSupport Class and then override doStartTag() method. To write the data for JSP, we need to use the JspWriter class. The PageContext class provides getOut() method which returns the instance of the JspWriter class. Later, the TagSupport class provides an instance of pageContext by default.
 
Creating the TLD File : TLD stands for Tag Library Descriptor file. It contains the information related to the tag and Tag Hander classes. It must be held inside the WEB-INF directory.
 
Creating the JSP File : We will be specifying the path of the TLD file directly. It is recommended to use the URI name instead of full a path of the TLD file. It uses taglib directive to use the tags defined in the TLD file.
Using a Post/Redirect/Get or a PRG pattern, this problem can be solved.
 
1) A form filled by the user is submitted to the server using POST or GET method. The state in the database and business model are updated.
 
2) A redirect response is used to reply by the servlet for a view page.
 
3) A view is loaded by the browser using the GET command and no user data is sent. This is safe from multiple submits as it is a separate JSP page.
20 .
Differentiate between response.sendRedirect(url) and <jsp:forward page = …>.
<jsp.forward> element forwards the request object from 1 JSP file to another. Target file can be HTML, servlet or another JSP file, but it should be in the same application context as forwarding JSP file.
 
sendRedirect send HTTP temporary redirect response to the browser. The browser then creates a new request for the redirected page. It kills the session variables.
It can be done by having them implemented by the SingleThreadModel Interface. Add <%@page isThreadSafe=”false” %> directive in the JSP page.
They are XML tags, which direct the server to using existing components or control behavior of JSP Engine. They consist of a typical prefix of “jsp:” and action name.
 
<jsp:include/>
<jsp:getProperty/>
<jsp:forward/>
<jsp:setProperty/>
<jsp:usebean/>
<jsp:plugin/>
We can place the file inside the WEB-INF directory as the WEB-INF directory can not be accessed in a web browser. We will also have to configure file details in web.xml. Following is the syntax to configure such JSP.
<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>
Syntax to disable java code :
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
Both include directive and include action tag are used to add a file into existing jsp. The difference is in the way they include the file.
 
* Include directive includes the file during translation stage of life cycle whereas, the include action includes the file at runtime.

* If the included file is changed but not the JSP which is including it then the changes will not reflect if the include directive is used. Because jsp is not changed and that means it will not be translated for the request. For such a station an action tag has to be used.

Syntax difference : 
Include directive : <%@ include file=”file_name” %> and 
 
include action : <jsp:include page=”file_name” />.
 
We can use the action tag with or without parameters. The same can not be done in the include directive.
There are two types of comments in JSP :
 
HTML Comments : These comments are visible in the HTML source code. 
Syntax for HTML comment : <!–Comment–>.
 
JSP Comments : These comments are not visible in HTML source code. That is why they are also called hidden comments. For code-level debugging information, these are suitable options.
Syntax for JSP comment : <%–Comment–%>.
Expression Language (EL) was introduced in jsp 2.0 primarily to simplify the accessibility of data stored in java beans. To get attributes or parameters with the help of HTML tags. It can also be used for arithmetic, relational or logical operations.
 
Syntax : ${Expression}
 
Any given expression inside the bracket will be evaluated at runtime.
Following are the available implicit objects in EL :

header : It is used to map request header name to the single value
cookie : It is used to cookie name to the cookie value
param : It is used to map parameters to a single value.
* pageScope : It is used to map values from the page scope.
* pageContext : It provides access to Object requests, session
* sessionScope : It is used to map values from the session scope.
* requestScope : It is used to map values from the request scope. Attributes are set by request implicit object.
* applicationScope : It is used to map values from the application scope.
* headerValues : It is used to map the request header name to the single values
* initParam : It is used to map the Initialization Parameter
* paramValues : It is used to map the request parameter to an array of values
Validations done at the client-side are called client-side validations; similarly, validations done at the server-side are called server-side validations. Both validations are written in JavaScript. If client-side validations are successful, then only data is submitted, whereas on the server-side, all data is submitted, and then the validations are done. In such cases, if there is some error, then the extra network trip is required to resend the form to the client to refill the form with the correct data.
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.
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("Learning"); %> can be written using JSP Expression as <%= "Learning" %>
 
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; %>.
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}.
Based on the JSTL functions, they are categorized into five types :
 
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.
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 finds TLD files inside the META-INF directory of the 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.
Server-side technologies range from server-side scripting languages, database management systems, web server software such as Apache, IIS, node.js, tomcat. Server-side scripting languages like ASP, PHP, ColdFusion, Python, or JSP are used for developing dynamic web pages that can be accessed through state-less Internet protocol such as HTTP, FTP, SMTP, or Telnet.
 
The client machine sends the client’s request to the server, then the server verifies and executes the file and its embedded scripts, and formats resulting files and sends it to the client. The response is displayed on the client via browsers like Chrome, Mozilla, Internet Explorer, Opera, or Safari.
Java Server Pages which is a servlet that maintains status information about web visitors requesting the URL website address during a particular interval of time, is known as session tracking. Information about visitor visiting a website is saved with
 
setAttribute(String name,Object value) method as below :
 
session.setAttribute("user", name);

This session data can be retrieved using getAttribute(String name) method as below :
 
String name= (String)session.getAttribute("user");
Cookies are text files that are created in the client machine and store details of web searches or sites explored using the browser, date, and time of visit, along with IP address. The presence of cookies helps websites identify clients that return to their sites.
 
Cookies are of various types such as Authentication, Tracking, and Session cookies.

* Authentication cookies validate a genuineness of a valid user that revisits the website.

* Session cookies are short-lived until the user explores a particular website, once he leaves the site, session cookies are deleted by browsers.

* Tracking cookies as the name suggests keeps a record of how often a particular website has been visited.
For redirect a page in JSP, we are calling response.sendRedirect(), By using this method, the server return back the response to the client, from where next request comes and it displays that url.
 
Here we are using the implicit object "response" to redirect the browser to a different resource.
 
When calling a sendRedirect method, web container will inform the browser that a new URL is requested. Here browser issues entirely new request so any data that are stored as request attributes will be lost after the redirect happens
 
If we called sendRedirect() from JSP #1 to JSP #2 the browser's location bar is changed to show JSP #2, since a sendRedirect() is a new request,
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
    <title>JSP Redirect Example</title>
</head>
<body>
    <%
        String redirectURL = "http://www.javatips.net/";
        response.sendRedirect(redirectURL);
    %>
</body>
</html>
The advantages of using JSP page API for web-based client programs are as follows :
 
* There is no need for any sort of security policy files or plugins on the system of the client. 
* Separating application programs from web design is possible, thus allowing cleaner and more application design.
The method to restrict page error display on the JSP is to set the “Errorpage” attribute of the page directory as the name of the error page. Once you have done that, now you should set “isErrorpage=TRUE” in error JSP page. The reason for doing so is, whenever any error will occur in the JSP page, an error page will be automatically called.
Object cloning is used to create an exact copy of the existing object. The clone() method of the Object class is used to create the clone of an existing object. As a prerequisite, The class whose object the user tries to clone is expected to implement the java.lang.Cloneable interface.
Syntax :
class FullName implements Cloneable{ 
     String Firstname;
     String Lastname; 
     FullName(String Firstname,String Lastname){ 
          this.Firstname=Firstname; 
          this.Lastname=Lastname; 
     } 
    public Object clone()throws CloneNotSupportedException
{ 
          return super.clone(); 
     } 
     public static void main(String args[])
{ 
          Try
{ 
               FullName s1=new FullName("Free Time","Learning"); 
               FullName s2=(FullName)s1.clone(); 
          System.out.println(s1.Firstname+" "+s1.Lastname); 
          System.out.println(s2.Firstname+" "+s2.Lastname); 
          }
          catch(CloneNotSupportedException c)
{
            } 
     } 
}
The above code will print the string “Free Time Learning” twice.
When the buffer is filled or whether an exception should be raised to indicate buffer overflow, The Auto-Flush attribute specifies if a buffered output should be flushed automatically or not. To perform automatic flushing, the attribute is set to true. If it is set to false, then an exception will be raised.
Following are steps to delete session data :
 
Remove particular attribute :
Syntax: public void removeAttribute(String name)
 
Discard the whole session :
Syntax: public void invalidate()
 
Setting individual session timeout :
Syntax: public void setMaxInactiveInterval(int interval)
 
Logout user : logout user from the web server and invalidate session belonging to the user.
Syntax : 
Cookie mycookie = new Cookie("name","value");
response.addCookie(mycookie);
Cookie killcookie = new Cookie("mycookie","value");
killcookie . set MaxAge ( 0 );
killcookie . set Path (" / ");
killcookie . addCookie ( killcookie 1 );​
<c:out> tag : It is used to display the content on client after escaping XML and HTML markup tags. Main attributes are default and escapeXML.
<c:set> tag : This tag is used to set up a variable value in a specified scope. It sets the result for a given expression in the given variable.
<c: remove> tag : It is used to remove an attribute from a specified scope, By default removes it from all scopes.
<c: if> tag : This JSTL core tag is used for testing conditions. There are two other optional attributes for this tag, var, and scope.
<c:choose> tag : It is used as a switch case.
<c:when> tag : It’s like a case statement in Java.
<c:otherwise> tag : It is used as the default attribute in switch-case statements.
<c:catch> tag : This tag is used in exception handling.
<c:import> tag : This is a core JSTL tag. It is used for importing the content from another file or page to the current JSP page. Attributes required are var, URL, and scope.
<c:forEach> tag : This tag in JSTL works as for look from java 
<c:forTokens> tag : It is used for iteration but it only works with the delimiter.
<c:param> tag : This JSTL tag is mostly used with <c:url> and <c:redirect> tags. It adds parameters and their values to the output of these tags.
<c:url> tag : It is used for URL formatting or URL encoding. It converts a relative URL into an application context’s URL.
<c:redirect> tag : It is used, to redirect the current page to another URL, provide the relative address in the URL attribute of this tag and the page will be redirected to the URL.
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>

 

Notice the use of JSP EL in the c:if condition.
The advantages of JSP over ASP are as follows :
 
* The dynamic part of the code is written in Java, not in Visual Basic or the Microsoft-specific language. Hence, it is powerful and easier to use.

* It is portable to other operating systems and Non-Microsoft Web servers.
The jsp:plugin action tag is used to embed an applet in the JSP file. The jsp:plugin action tag downloads plugin at client side to execute an applet or bean.
 
Example of displaying applet in JSP : 
<html>    
    <head>    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
        <title>Mouse Drag</title>    
    </head>    
    <body bgcolor="red">    
<h1>Mouse Drag Example</h1>    
    
 <jsp:plugin align="middle" height="450" width="450"    
     type="applet"  code="mousedrag.class" name="clock" codebase="."/>    
    
    </body>    
</html>