JSP Interview Questions

In the early days, there were various tools to develop dynamic web content such as Common Gateway Interface (CGI), mod_perl from Apache, ISAPI from Microsoft. All of them tried to generate web pages by embedding HTML directories into a programming language. Because of this, the creation of dynamic web pages is pushed into the realm of programmers. Java Server Pages, however, changes all that. JSP is a text-based program, which includes both HTML and Java code. JSP lets you embed specialized code, also known as a script, into HTML pages. By default, Java is used as a scripting language in JSP.  But the JSP specification can include other scripting languages as well, such as JavaScript, Perl, and VBScript. Even with all the latest technology available, many companies use Java as a Base language. These companies also use JSP to develop dynamic web pages and web applications. Hence it is expected that the ideal candidate for Java must know about JSP. Having known the importance of JSP, let’s begin with the top JSP Interview Questions that are asked frequently in interviews.

Top JSP Interview Questions in 2021

1. What is JSP and why do we need it?

JSP stands for Java Server Pages. JSP is server-side technology to create dynamic web pages. JSP is an extension of servlet technology to help developers create dynamic web pages with HTML-like syntax.

JSP is less error-prone and easy to maintain than servlet. Most of the elements on a web page are static, so the JSP page is more suitable for the web page. There are JSP scripting elements that allow one to write java code in JSP pages. We can also use JSP action tags, JSTL tags, or custom tags to achieve the same functionalities.

One more benefit of JSP is that most of the containers support the hot development of JSP pages. We can make the required changes in JSP and replace the old JSP page with the updated JSP page in the development directory, and the container will load the new JSP page. There is no need to compile project code or restart the server, but if the changes are made in servlet code changes, we need to build the complete project again and deploy it. Nowadays, almost all containers provide hot deployment support for the application, but it is more work than JSP pages.

2. What are JSP action tags?

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.

3. Explain the jsp life cycle.

Any JSP file goes through 7 stages and that is called life cycle phases:

  1. 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.
  2. Compilation: After translation, Container compiles JSP source code to create a class file.
  3. Loading: The Container loads the compiled class into memory.
  4. Instantiation: Container invokes constructor that has zero arguments to instantiate it. 
  5. Initialization: Container Calls the jspInit() method to initialize the servlet instance. After this, JSP can handle the client request.
  6. 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.
  7. Destroy: After the processing is over, the JSP class is unloaded from memory using the jspDestroy() method.

4. What is a JSP container?

A JSP container is an entity that is used to translate, execute, and process JSP pages and deliver requests to them. The exact make-up of a JSP container depends on the implementation, but it will consist of a servlet or collection of servlets. Hence, the JSP container is executed by a servlet container.

5. Can you override any of the life cycle methods mentioned above?

jspInit() and jspDestory() methods can be overridden if required. jspInit()  can be overridden to create common resources that can be used in service methods such as database connections in the same way jspDestroy() is used to release common resources that are created using jspInit().

6. What are the context initialization parameters?

The parameters used for initialization for the whole application. They are not specific to any servlet or JSP. These parameters are specified in web.xml using <context-param> tag.

7. How can you avoid direct access to any jsp from the client browser?

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>.

8. How will you disable java code(Scriplet) in JSP

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>

9. What are the implicit objects in JSP? Can you name them?

The objects that do not require declaration first are known as implicit objects. Following are the implicit objects in JSP:

Out, request, response, session, config, exception, page, pageContext, application. 

10. What is the purpose of the PageContext implicit object?

JSP PageContext implicit object is an instance from java.servlet.jsp.PageContext abstract class implementation. It is used to get and set attributes, forward requests to other resources and hold references to other implicit objects.

11. What is the difference between include directive and include action tag?

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.

  1. Include directive includes the file during translation stage of life cycle whereas, the include action includes the file at runtime.
  2. 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.
  3. Syntax difference: 

Include directive: <%@ include file=”file_name” %> and 

include action: <jsp:include page=”file_name” />.

  1. We can use the action tag with or without parameters. The same can not be done in the include directive.

12. How do you use JSP in the MVC model?

JSP is usually used for presentation in the MVC. It acts as a 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.

13. What is the purpose of the JSP declaration tag?

Any method or variable that we want to use can be declared using the JSP declaration tag.

Syntax:

<%! variable/method name %>.

14. How will you disable caching on the back button?

Syntax:

<%response.setHeader("Cache-Control","no-store"); response.setHeader("Pragma","no-cache"); 
response.setHeader ("Expires", "0"); %>

15. Is it possible to use the exception implicit object in any JSP page?

No. The exception implicit object is used in the error page, which defines it with the isErrorPage attribute of the page directive.

16. List down all the scope values for the <jsp.useBean> tag.

There are four scope values for the given tag.

  1. Page
  2. Request
  3. Session
  4. Application.

17. List down all the Literals used in JSP.

  1. Boolean
  2. Integer
  3. Floating Point
  4. String
  5. String

18. Mention the types of comments that can be used in JSP. 

There are two types of comments in JSP:

  1. HTML Comments: These comments are visible in the HTML source code. 

Syntax for HTML comment: <!–Comment–>.

  1. 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–%>.

19. What is Expression Language (EL) in jsp?

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.

20. Write syntax for Expression Language to get the HTTP method name. 

Syntax: ${pageContext.request.method}.

21. Mention some of the predefined implicit objects in EL. 

Following are the available implicit objects in EL:

  1. pageScope: It is used to map values from the page scope.
  2. pageContext: It provides access to Object requests, session
  3. sessionScope: It is used to map values from the session scope.
  4. requestScope: It is used to map values from the request scope. Attributes are set by request implicit object.
  5. param: It is used to map parameters to a single value.
  6. applicationScope: It is used to map values from the application scope.
  7. header: It is used to map request header name to the single value
  8. headerValues: It is used to map the request header name to the single values
  9. initParam: It is used to map the Initialization Parameter
  10. paramValues: It is used to map the request parameter to an array of values
  11. cookie: It is used to cookie name to the cookie value

22. List down attributes on page directives.

 Following are the attributes of the Page Directives

  1. Session: To show if any session data is available to the page or not.
  2. Import: It is declared to show a list of packages that are imported
  3. isELIgnored: It is used when jsp transforms into servlet to show whether EL expressions are ignored or not.
  4. contentType: To allow the user to specify the content-type of the page.

23. What are Client-side and server-side validation?

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.

24. Explain Object cloning. 

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.

25. Write an example of the clone method.

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("Karan","Dalal"); 
               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 “Karan Dalal” twice.

26. Explain Auto-Flush attributes.

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.

27. How do you delete session data?

Following are steps to delete session data:

  1. Remove particular attribute:

Syntax: public void removeAttribute(String name)

  1. Discard the whole session:

Syntax: public void invalidate()

  1. Setting individual session timeout:

Syntax: public void setMaxInactiveInterval(int interval)

  1. Logout user: logout user from the web server and invalidate session belonging to the user.

28. Write syntax to delete cookies in JSP.

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 );

29. What is JSTL?

JSTL stands for JSP Standard Tag Library. It is part of Java EE API and is included in most servlet containers. JSTL can use a loop through a collection. It can also be used to escape HTML tags to show them as text in response. Because of this, it is considered more versatile than Expression language. 

30. List down different types of JSTL tags.

JSTL tags are categorized into 5 types:

  1. Core Tags: These tags are used to support Iteration, conditional logic, catch an exception, URL, forward, or redirect response.
  2. Formatting and Localization Tags: These tags are used for the formatting of numbers or dates.
  3. SQL Tags: These tags are used to support interaction with relational databases like MySql or Oracle.
  4. XML Tags: These tags are used to work with XML documents to perform functions such as Parsing XML or transforming XML data.
  5. JSTL functions tag: JSTL tags provide some functions to perform common operations like string concatenation or split.

31. List down JSTL core tags.

  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.
  2. <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.
  3. <c: remove> tag: It is used to remove an attribute from a specified scope, By default removes it from all scopes.
  4. <c: if> tag: This JSTL core tag is used for testing conditions. There are two other optional attributes for this tag, var, and scope.
  5. <c:choose> tag: It is used as a switch case.
  6. <c:when> tag: It’s like a case statement in Java.
  7. <c:otherwise> tag: It is used as the default attribute in switch-case statements.
  8. <c:catch>tag: This tag is used in exception handling.
  9. <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.
  10. <c:forEach> tag: This tag in JSTL works as for look from java 
  11. <c:forTokens> tag: It is used for iteration but it only works with the delimiter.
  12. <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.
  13. <c:url> tag: It is used for URL formatting or URL encoding. It converts a relative URL into an application context’s URL.
  14. <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.

32. What is the JSP custom tag and how are they created?

In JSP, there are multiple predefined tags, but in some cases, these tags may not be sufficient. In such a situation, we can create a tag of our own to satisfy the needs. Such tags are called custom tags.

Following are the steps to create a custom tag:

  1. Create tag handler class: this is the file that will have logic for the custom tag. First, inherit the TagSupport Class after that, override doStartTag() method. Use JspWriter class so that we can write data for jsp. The PageContext class provides getOut() method which returns the instance of the JspWriter class. After this, the TagSupport class provides an instance of pageContext by default.
  2. Creating Tag Library Descriptor (TLD) File: this file is created inside the WEB-INF directory. It has information related to the tag that we want to create and the tag handler class.
  3. Creating the jsp file: this file should specify the path of the TLD file.it uses taglib directive to use tags that are defined in TLD 

33. What are the differences between the JSP custom tag and java beans?

  1. JSP content can be manipulated using custom tags. The same can not be done by java beans.
  2. In custom tags, we can simplify complex operations. The same can not be done by java beans.
  3. The custom tag requires some amount of work to set up as compared to java beans.

34. List down the tags used in JSP bean development.

  1. jsp:useBean
  2. jsp:setProperty
  3. jsp:getProperty

35. What are the methods used to read data from JSP form?

Depending on the situation following functions can be used to read data from JSP:

  1. getParameter(): this method is used when there is a single parameter to read. 
  2. getParameterValues(): This method is used when there the parameter appears more than once and returns multiple values.
  3. getParameterNames(): This method is used to fetch the list of all parameters in the current request.
  4. getInputStream(): This method is used to read binary data streams coming from the client.

36. What would you prefer between JSP pages and applets to design web-based client programs?

Between two JSP pages is more preferable as there is no need for plug-ins or security policy files. JSP application programming and JSP design are done separately providing a more modular approach. 

37. Can you retrieve SQL warnings in JSP?

We can retrieve SQL warnings by using SQLWarning objects. It can be reported on a Connection object, a Statement object including PreparedStatement and CallableStatement objects.

Syntax for warning on statement object:

SQLWarning warning = stmt.getWarnings();
String Warning=   warning.getMessage();


38. Write syntax for the servlet to communicate with JSP.

To communicate with jsp, servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page.

Consider the following servlet to communicate first name and last name to Bean01.jsp.

Servlet syntax to set data before the request is forwarded.

public void doPost (HttpServletRequest request, HttpServletResponse response){
     try {
           govi.FormBean f = new govi.FormBean();
           String id = request.getParameter("id");
           f.setName(request.getParameter("name"));
           f.setAddr(request.getParameter("addr"));
           f.setAge(request.getParameter("age"));
           f.setPersonalizationInfo(info);
           request.setAttribute("fBean",f);
           getServletConfig().getServletContext().getRequestDispatcher
           ("/jsp/Bean01.jsp").forward(request, response);
     }
     catch (Exception ex) {
     }
}

We can use the getProperty function to retrieve forwarded data.

Syntax:

jsp:useBean id="fBean" class="govi.FormBean" scope="request"/ jsp:getProperty name="fBean"
property="name" / jsp:getProperty name="fBean"
property="addr" / jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean"
property="personalizationInfo" /
 
 
 
 

39. Write syntax to disable Expression language (EL) on JSP.

To disable EL in one file use following directive:

<% @ page isELIgnored = “true”%>.

If we want to disable EL on multiple files we can configure the same in web.xml:

<jsp-config>
   <jsp-property-group>
       <url-pattern>*.jsp</url-pattern>
       <el-ignored>true</el-ignored>
   </jsp-property-group>
</jsp-config>

40. Explain conditions in which the container initializes multiple JSP objects.

If there are multiple servlets and if one servlet or JSP page has multiple servlet-mapping elements in the deployment descriptor, then the container initializes an object for each element, and each of these objects has it’s ServletConfig object and initialization parameters. 

Syntax for one JSP page used in web.xml file:

<servlet>
<servlet-name>TestServlet</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>.

This brings us to the end of the blog on the top JSP Interview Questions. We hope that you were able to benefit from these questions and are now better-equipped for your upcoming interview process. To learn more such concepts, check out a pool of Free Online Courses offered by Great Learning Academy.

One such free course is the Java Programming course on Great Learning Academy.

java
0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

15 + 10 =