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.
JSP Interview Questions for Freshers
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:
- 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.
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. What are some benefits of using JSP?
- JSP provides a simple, yet powerful, way to create dynamic web pages.
- JSP pages are compiled into Java bytecode, which improves performance and enables them to run on any Java-enabled web server.
- JSP tags provide a convenient way to create reusable components that can be shared among multiple pages.
- JSP pages can be integrated with Java code, allowing you to create custom components and extensions.
- JSP pages can be easily customized and configured to meet the needs of your application.
8. 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.
9. What is the difference between include directive and include action tag?
Both include directives and include action tags are used to add a file into the 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.
- We can use the action tag with or without parameters. The same can not be done in the include directive.
10. What are Servlets?
Servlets are a Java technology that enables web developers to create dynamic content for web servers. Servlets are typically used to process or store information from a request from a client, such as a web browser, and return a response to the client.
11. 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.
<h3 id="scope-values-for-the–tag”>12. List down all the scope values for the <jsp.useBean> tag
There are four scope values for the given tag.
- Page
- Request
- Session
- Application.
13. List down all the Literals used in JSP
- Boolean
- Integer
- Floating Point
- String
- Null
14. What are JSP Operators?
The JSP Operators are the symbols that are made to use for the manipulation of data. The operators are used for creating, comparing, and manipulating the data. These operators can be divided into 3 parts: arithmetic, logical, and string operators.
15. What is the difference between JSP and Javascript?
Javascript is a language that is used to create interactivity on web pages. JSP is a Java servlet that helps in the development of web pages.
16. Is JSP technology extensible?
JSP technology is extensible. It can be extended with JavaBeans components and JavaServer Faces components.
17. 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.
18. 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 to the client.
JSP Interview Questions for Experienced
19. 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>.
20. 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>
21. 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 %>.
22. 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"); %>
23. Mention the types of comments that can be used in JSP
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–%>.
24. 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.
25. Write syntax for Expression Language to get the HTTP method name
Syntax: ${pageContext.request.method}.
26. Mention some of the predefined implicit objects in EL
Following are the available implicit objects in EL:
- 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.
- param: It is used to map parameters to a single value.
- applicationScope: It is used to map values from the application scope.
- header: It is used to map request header name to the single value
- 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
- cookie: It is used to cookie name to the cookie value
27. List down attributes on page directives
Following are the attributes of the Page Directives
- Session: To show if any session data is available to the page or not.
- Import: It is declared to show a list of packages that are imported
- isELIgnored: It is used when jsp transforms into servlet to show whether EL expressions are ignored or not.
- contentType: To allow the user to specify the content-type of the page.
28. 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.
29. 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.
30. 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.
31. 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.
32. How do you delete session data?
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.
33. 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 );
34. 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.
35. List down different types of JSTL tags
JSTL tags are categorized into 5 types:
- Core Tags: These tags are used to support Iteration, conditional logic, catch an exception, URL, forward, or redirect response.
- Formatting and Localization Tags: These tags are used for the formatting of numbers or dates.
- SQL Tags: These tags are used to support interaction with relational databases like MySql or Oracle.
- XML Tags: These tags are used to work with XML documents to perform functions such as Parsing XML or transforming XML data.
- JSTL functions tag: JSTL tags provide some functions to perform common operations like string concatenation or split.
36. List down JSTL core tags
- <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.
37. 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:
- 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.
- 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.
- 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
38. What are the differences between the JSP custom tag and java beans?
- JSP content can be manipulated using custom tags. The same can not be done by java beans.
- In custom tags, we can simplify complex operations. The same can not be done by java beans.
- The custom tag requires some amount of work to set up as compared to java beans.
39. List down the tags used in JSP bean development
- jsp:useBean
- jsp:setProperty
- jsp:getProperty
40. 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:
- getParameter(): this method is used when there is a single parameter to read.
- getParameterValues(): This method is used when there the parameter appears more than once and returns multiple values.
- getParameterNames(): This method is used to fetch the list of all parameters in the current request.
- getInputStream(): This method is used to read binary data streams coming from the client.
41. What would you prefer between JSP pages and applets to design web-based client programs?
Between two JSP pages is 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.
42. 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.
The syntax for warning on statement object:
SQLWarning warning = stmt.getWarnings();
String Warning= warning.getMessage();
43. 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 the 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" /
44. Write syntax to disable Expression language (EL) on JSP
To disable EL in one file using the 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>
45. 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 its ServletConfig object and initialization parameters.
The 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>.
Summing Up
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 at Great Learning Academy.
0 Source: GreatLearning Blog