Top 50 JSP Interview Questions & Answers to Excel

Top 50 JSP Interview Questions & Answers to Excel

Subscribe to my newsletter and never miss my upcoming articles

Every time you go for a Java web developer interview, there will always be a few questions about JSP. In this article, I have collected some of the most-asked JSP interview questions asked in several interviews. With this article, we'll cover JSP Interview questions ranging from beginner to advanced.

JSP Interview Questions & Answers

1. What is JSP?

Answer: JSP (formerly known as Java Server Pages) stands for Jakarta Server Pages. It is a server-side programming language that allows you to create dynamic web pages through HTML (HyperText Markup Language). They contain embedded Java code. Their role is to extend Servlet technology and generate Servlet from a page. Servlets and JSP pages are commonly used in the same web application.

2. What are the Literals used in JSP?

Answer: JSP uses the following Literals:

  • Boolean
  • Float
  • Integer
  • Null
  • String

3. List out some advantages of using JSP.

Answer: JSP offers the following advantages:

  • Improved performance
  • It is also possible to combine JSP and servlets.
  • JSP has access to all-powerful enterprises.
  • JSP is compiled before it is processed to the server, eliminating the need to load the interpreter and script each time.
  • JSP is easy to manage because we can easily separate our business logic and presentation logic. Our business logic is combined with our presentation logic in Servlet technology.

4. How can you include the results of another page?

Answer: You can include the results of another page by using the following methods:

  • Include Directive
  • Include Action

5. Differentiate between Include Directive and Include Action.

Answer: Here's the key difference between both Include Directive and Include Action:

The syntax for include Directive is <%@ include file="fileName" %>. It means we are adding some files to our JSP Page when we use include directive contents of an included file will be added to calling JSP page at translation time means when the calling JSP is converted to a servlet, all the contents are added to that page.

The syntax for include action is <jsp:include page=”relativeURL” />. It's a runtime procedure that means the result of the JSP page, which is mentioned in the relative URL is appended to calling JSP at runtime on their response object at the location where we have used this tag.

6. Mention the scope values for tag.

Answer: There are four main scope values available for the <jsp.useBean> tag.

  • application
  • page
  • request
  • session

7. Can you disable the caching on the back button of a particular browser?

Answer: Yes, we can disable caching in the back button of the browser. Here is the code we can use to accomplish this:

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

8. How can I use JSP in the MVC model?

Answer: JSP is used in MVC in the presentation tasks. It is used as a view. The controller calls the model and the business classes that receive the data. Upon rendering this data, the JSP renders it to the client.

9. What is the major difference between ServletContext and PageContext?

Answer: The main difference between ServletContext and PageContext is that ServletContext is designed to provide information about the Container, while PageContext is designed to provide information about the Request.

10. How are Custom Tags in JSP created?

Answer: We can create custom tags in JSP by following these 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 the 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 the full path of the TLD file. It uses the taglib directive to use the tags defined in the TLD file.

11. What do you mean by Context Initialization Parameters?

Answer: Context Initialization Parameters are the Initializing Parameters for the entire application. These are not specific to any Servlet or JSP. In a web.xml file, context parameters are specified using the following syntax.

<context-param>  
    <param-name>parametername</param-name>  
    <param-value>parametervalue</param-value>  
</context-param>

12. What are Servlets?

Answer: It is common to combine JSP pages with servlets in the same application. JSP is based on Jakarta servlet specifications. In a nutshell, a servlet adds functionality to a web server, just as CGI and proprietary extensions such as NSAPI and ISAPI. Servlets have several advantages over other technologies:

  • Efficiency
  • Integration
  • Platform and vendor independence
  • Robustness and security
  • Scalability

13. Explain the JSP for a loop.

Answer: The JSP For loop is used for iterating the elements for a specific condition, and it has the following three parameters:

  • The variable counter is initialized.
  • Condition until the loop has to be executed.
  • The counter has to be updated.

Syntax:

for(inti=0;i<n;i++)
{
          //block of statements
}

14. Explain the JSP while loop.

Answer: The JSP While loop is used to iterate the elements that have one parameter of the condition.

Syntax:

While(i<n)
{
     //Block of statements
}

15. What is the difference between JSP and Javascript?

Answer: JSP is a server-side scripting language as it runs on the server. Meanwhile, JavaScript runs on the client. JSP is commonly used to change the content of a webpage, and JavaScript to change the presentation. Both are quite common on the same page.

16. What do you mean by JavaBeans?

Answer: The JavaBeans component is a Java class that follows certain coding conventions. Many JSP elements work with JavaBeans. In terms of information that represents application entities, JavaBeans serve as containers.

17. What is JSP Expression Language (EL)?

Answer: JSP 2.0 introduced Expression Language (EL). It simplifies the access to data stored in Javabean components and other objects, such as requests, sessions, and applications. JSP provides many operators that are also used in EL, such as arithmetic and logical operators.

18. Mention the Implicit Objects in a JSP.

Answer: The Web Container creates objects that include information related to a particular Request, Application, or Page. Objects like these are called Implicit Objects. In the JSP, implicit objects are as follows:

  • Request
  • Response
  • Application
  • Exception
  • Config
  • Page
  • Session
  • PageContext
  • Out

19. What is J2EE?

Answer: J2EE is a compilation of different Java APIs, which were previously available as separate packages. They all can be combined using J2EE Blueprints. Using a test suite, J2EE vendors can test their products for compatibility. J2EE includes the following enterprise-specific APIs:

  • Enterprise JavaBeans (EJB)
  • Jakarta Server Pages ( JSP)
  • Java Servlets
  • Java Database Connection ( JDBC)
  • Java Transaction API ( JTA) and Java Transaction Service ( JTS)
  • Java Naming and Directory Interface ( JNDI)
  • Java Message Service ( JMS)
  • Java IDL and Remote Method Invocation (RMI)
  • Java XML

20. Explain the Life Cycle of a servlet.

Answer: Servlets are Java classes that use the Servlet Application Programming Interface (API). Servlet API consists of many classes and interfaces defining some methods. By using these methods, it is possible to handle HTTP requests in a web server-independent manner.

When a web server receives a request that should be handled by it, a servlet is loaded. Upon initializing a servlet, the same servlet instance (object) is called for subsequent requests. Eventually, the webserver needs to shut down the servlet, usually when the webserver is shut down.

The three life cycle methods are:

  • public void init(ServletConfig config)
  • public void service(ServletRequest req, ServletResponse res)
  • public void destroy( )

These methods define the interactions between the servlet and the webserver.

21. Explain Translation Phase.

Answer: The JSP engine compiles and translates a JSP file into a servlet during the Translation Phase. The servlet proceeds to the execution phase, where all the requests and responses are handled. Initially, they are compiled. Unless they are manually compiled, they cannot be accessed. Manual/explicit compilation is useful for long and convoluted programs.

22. What are the attributes on page directives?

Answer: Page Directives have the following attributes;

  • Session: Indicates whether any session data is available on the page or not.
  • Import: It displays the imported packages.
  • isELIgnored: It shows whether EL expressions get ignored while JSP transforms into a servlet.
  • contentType: It lets the user specify the content type of the page.

23. How can we stop errors on Display in a JSP Page?

Answer: We can stop errors in display in a JSP Page by setting up an “ErrorPage” attribute of the PAGE directory to the name of the error page in the JSP page, and then in the error JSP page set “isErrorpage=”TRUE”.

24. How to include static files in a JSP?

Answer: Static pages can be included in a JSP via the include directive. In this way, inclusion is only performed once during the translation phase. Note that the file attribute must contain a relative URL. Although static resources can be included, it is not preferred since each request requires inclusion.

25. Can a Constructor be used in place of the init() method to initialize a servlet?

Answer: Yes, we can use a constructor in place of the init() method. However, it is not preferred because init() was developed. After all, earlier Java versions could not call constructors with arguments dynamically. Thus, they could not assign a servletConfig. Even so, servlet containers still call only a no-arg constructor. As a result, there is no access to servletContext or servletConfig.

26. Explain Client-Side and Server-Side Validation.

Answer: JavaScript is used for client-side validation. Validation occurs within the browser. When the validation is successful, Javascript is used to submit the data in the form. Validation errors do not require additional network trips because the form cannot be submitted if there are any errors.

After submission of the form, a similar form of data validation is performed on the server-side. When the validation fails, an extra network trip is required to resend the form to the client to fill in the correct data.

27. What is JSTL?

Answer: JSTL stands for Jakarta Server Pages Standard Tag Library. It is a library with a collection of custom JSP tag libraries that provide basic functionality for web development. The following are some of the properties of JSTL:

  • Neat and Clean Code.
  • It is easier for humans to read and simpler for computers to understand.
  • As a Standard Tag, it presents a rich layer of the portable functionality of JSP pages.
  • It has Automatic Javabeans Introspection Support. JSTL Expression handles JavaBean code very well. We don't need to downcast objects that have been retrieved as scoped attributes.

28. What are JSTL Core tags used for?

Answer: JSTL Core tags serve the following purposes:

  • Iteration
  • Conditional logic
  • Catch exception
  • URL forward
  • Redirect, etc.

29. Which methods are used for reading form data using JSP?

Answer: JSP is used to handle the form data parsing automatically. Depending on the situation, it dies by using the following methods:

  • getParameter() − To get the value of a form parameter, call the request.getParameter() method.
  • getParameterValues() − If a parameter appears more than once and it returns multiple values, call this method.
  • getParameterNames() − This method is used if, in the current request, you want a complete list of all parameters.
  • getInputStream() − This method is used for reading binary data streams from the client

30. Explain the anatomy of a JSP page?

Answer: The parts of the page that differ for each request are generated using different JSP elements. JSP pages are regular web pages with JSP elements. With JavaServer Pages, there are three types of elements: directive, action, and scripting elements. It is common to use JSP elements to work with JavaBeans.

"Template text" refers to the elements of the page that are not JSP elements. In most cases, the template text is HTML, but it could also be any other text.

As a JSP page request is processed, the template text and the dynamic content generated by the JSP elements are combined, and the result is sent to the browser as a response.

31. How does JSP processing take place?

Answer: The JSP page is turned into a servlet for all the JSP elements to be processed by the server. Then the servlet is executed. The servlet container and the JSP container—are often combined into one package under the name “web container”.

The JSP container is responsible for converting the JSP page into a servlet and compiling the servlet in the translation phase. It is used to automatically initiate the translation phase for a page when it is requested for the first time.

In the “request processing” phase, the JSP container is also responsible for invoking the JSP page implementation class to process each request and generate the response.

32. What is Object Cloning?

Answer: Object cloning is the process of creating an exact copy of an existing object. The clone() method of the Object class is used to create the clone an existing object. The class whose object the user wants to clone should implement the java.lang.Cloneable interface. If it does not implement the Cloneable interface, then the clone() method generates the CloneNotSupportedException.

protected Object clone() throws CloneNotSupportedException

33. Differentiate between JSP Scriptlet tag and Declaration tag.

Answer: The differences between the two are as follows:

JSP Scriptlet tagDeclaration tag
JSP Scriptlet Tag can only declare VariablesDeclaration Tag declares Methods and Variables
Scriptlet Tag is placed within _jspService()Declaration Tag is placed outside _jspService()

Answer: To delete a cookie in JSP, follow the following code snippet.

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

35. How can you make the Finally Clause not fail to execute?

Answer: You can make the Finally Clause not fail by using System.exit(1); in the try block.

36. How to deactivate EL on JSP?

Answer: We can ignore the execution of an Expression Language (EL) expression on a JSP page in two ways.

  1. Using the directive <% @ page isELIgnored = “true”%>.
  2. Configure web.xml (ideal for disabling EL on multiple pages)

37. Can you disable JSP Scripting?

Answer: By setting the scripting-invalid element of the deployment descriptor to true, we can disable JSP scripting. It is a sub-element of the JSP-property group. There are two valid values for this: true and false.

Syntax:

<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>

38. What is Auto-Flush Attribute?

Answer: The autoFlush attribute specifies whether the buffered output should be flushed automatically when it is filled or whether an exception should be raised in the case of buffer overflow. By default, true indicates automatic buffer flushing, while false throws an exception.

39. How are cookies set in JSP?

Answer: To set cookies with JSP, follow these steps:

  • Creating a Cookie object: The cookie constructor is called with a cookie name and a cookie value, both are strings.
  • Setting the maximum age: etMaxAge is used to specify the length of the cookie(in seconds) that a cookie will remain valid.
  • Sending the cookie into the HTTP response headers: response.addCookie is used to add cookies in the HTTP response header.

40. Why are JSP pages preferred for creating web-based client programs?

Answer: JSP is preferred over applet for creating web-based client programs because no plug-ins or security policy files are required on the client systems. Also, JSP pages enable cleaner and more modular application design because they allow you to separate applications programming from web page design. Therefore, web designers personnel do not need to understand Java programming language syntax to do their jobs.

41. Why Does Jcomponent have Add() And Remove() methods but the component does not?

Answer: Because JComponent is a subclass of Container, it can contain other components and JComponents. You can make your JSPs thread-safe by implementing the SingleThreadModel interface. Add the directive *%@ page isThreadSafe="false" % > to your JSP page.

42. How can I declare methods within my JSP page?

Answer: You can invoke methods within any other methods you declare, or within JSP scriptlets and expressions.

Note that you cannot access any of the JSP implicit objects, such as requests, responses, sessions, and so on, from within the JSP method. You can, however, pass any implicit variables from a JSP to the methods you declare.

43. When does a container initialize multiple JSP objects?

Answer: When there are multiple servlets and servlet-mapping elements in the deployment descriptor for a single servlet or JSP page, the container creates an object for each element with its ServletConfig object and initialization parameters.

44. Explain some JSP Life-Cycle methods that can be overridden.

Answer: You can override the jspInit() and jspDestroy() methods within a JSP page. Freeing any allocated resources within jspDestroy() is good programming practice. Each of the jspInit() and jspDestroy() methods is executed only once during the lifecycle of a JSP page, and they are typically declared as JSP declarations.

45. How can we retrieve Warnings?

Answer: An SQLWarning object is a subclass of SQLException that deals with warnings related to database access. As opposed to exceptions, warnings do not stop the execution of an application; they simply alert the user that something went wrong. Warnings can be reported on a Connection object, a Statement object including PreparedStatement and CallableStatement objects, or a ResultSet object. There is a getWarnings method in each of these classes, which must be invoked to see the first warning reported on the calling object.

46. Explain the difference between forward and sendRedirect?

Answer: With a forward request, the request is sent to a different resource on the server without the client being informed that a different resource will process the request. The entire process takes place within the web container.

Invoking a sendRedirect method causes the web container to indicate to the browser that a new URL is required. Any objects stored as request attributes within the browser before the redirect takes place will be lost as the browser issues a completely new request. Compared to forward, this redirect takes longer.

47. What are the options for handling runtime exceptions in a JSP page?

Answer: Another popular JSP interview question tests how candidates handled Errors and Exceptions in JSP. When uncaught runtime exceptions are thrown, the errorPage attribute of the page directive allows you to send them to an error processing page for further handling.

48. What do you mean by isScriptingEnabled Attribute?

Answer: The isScriptingEnabled attribute checks whether scripting elements are allowed to be used. The default value is true, and it enables expressions, scriptlets, and declarations. If the attribute value is set to false, a translation-time error will be triggered, if the JSP uses any scriptlets, expressions/declarations.

49. How do you delete the Session Data?

Answer: The following steps are required to delete the Session Data.

  1. Remove a particular attribute: public void removeAttribute(String name) method is used to remove the value associated with a particular key.

  2. Delete the whole session: public void invalidate() method is used to delete an entire session.

  3. Setting the Session timeout: public void setMaxInactiveInterval(int interval) is called to set the timeout for each session.

  4. Log the user out: This method logs the user out of the Web server and invalidates all of their sessions.

  5. web.xml Configuration: In Tomcat, using the above methods, you can set the session time out in the web.xml file.

50. Mention the JSTL core tags.

Answer: JSTL core tags are as follows.

  • <c:out> tag: It is used for displaying the content on client after escaping XML and HTML markup tags. Main attributes are default and escapeXML.
  • <c:set> tag: This tag is useful for setting up a variable value in a specified scope. It evaluates an expression and sets the result in the given variable.
  • <c:remove> tag: It is used to remove an attribute from a specified scope (page, request, session, or application. By default, it removes the attribute from all scopes.
  • <c: if> tag: This JSTL core tag is used for testing conditions. There are two other optional attributes for this tag which are var and scope, the test is mandatory.
  • <c:choose> tag: It’s like switch statement in Java.
  • <c:when> tag: It’s like case statement in Java.
  • <c:otherwise> tag: It works like default attribute in switch-case statements.
  • <c:catch>tag: This tag is used in exception handling. In this post, we have discussed exception handling using the core tag.
  • <c:import> tag: This JSTL core tag is used for importing the content from another file/page to the current JSP page. Attributes – var, URL, and scope.
  • <c:forEach> tag: This tag in JSTL is used for executing the same set of statements for a finite number of times.
  • <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 and tags. It -adds parameter 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. Optional attributes var, context, and scope.
  • <c:redirect> tag: It is used for redirecting 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.

Did you find this article valuable?

Support Yash Tiwari by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this