Top 50 JSP Interview Questions and Answers
What is JSP?
JSP stands for JavaServer Pages. JSP is Java server-facet generation to create dynamic web pages. JSP is an extension of Servlet era to assist builders create dynamic pages with HTML-like syntax.
The person creates user perspectives in servlets as nicely, however the code becomes ugly and mistakes-prone. Moreover, as maximum of the factors on a web web page are static, consequently JSP web page is suitable for internet pages. Business good judgment in JSP pages need to be averted and should be used for view functions handiest.
JSP Interview Questions and Answers
Let us now see famous JSP Interview Questions and Answers.
Question: What are the advantages of JSP?
Answer: Using JSP scripting elements for writing Java code in JSP pages need to be averted, and JSTL tags, JSP motion elements, or custom tags must be used as an alternative to reap the identical functionalities.
Another advantage of JSP is that most of the boxes aid the hot deployment of JSP pages. Make the changes inside the JSP web page and replace the vintage page with the updated JSP page inside the deployment directory, and the container hundreds the new JSP page. We aren't required to collect our project code or restart the server, unlike when making adjustments in servlet code, in which we want to construct the entire task once more and set up. Although maximum of the containers offer hot deployment help for applications nevertheless, it’s greater paintings than JSP pages.
Question: Explain the lifecycle stages of JSP
Life cycle of JSP
A usual JSP page code looks like HTML and doesn’t look anything like java classes. The JSP field looks after translating the JSP pages and create the servlet elegance this is utilized in internet packages. Following are the phases of a JSP lifecycle:
Translation: JSP code is checked and parsed to generate the servlet supply code. For example, in Tomcat, made servlet elegance documents are determined at listing named TOMCAT/paintings/Catalina/localhost/WEBAPP/org/apache/JSP. If domestic.Jsp is the JSP page call, then usually the generated servlet magnificence name is home_jsp, and the home_jsp.Java is the report call.
Compilation: In this phase, the JSP field compiles the JSP elegance supply code, and a category report is produced.
ClassLoading: In this segment, the field hundreds the elegance into reminiscence.
Instantiation: The no-args constructor of the generated class is invoked by the container to load it into reminiscence and instantiate it.
Initialization: The init method of the JSP class object is invoked by using the box, and the servlet config is initialized with init params configured inside the deployment descriptor. JSP is ready to handle patron requests after this segment. Usually, translation to the initialization of JSP takes place while the first request for JSP comes. Still, we will configure it to be loaded and initialized on the time of deployment, like servlets using a load-on-startup detail.
Request Processing: This is the maximum extended lifecycle of the JSP page when the purchaser requests are processed. The processing is multi-threaded, just like servlets, and a new thread is spawned for each application. Servlet requests and ServletResponse gadgets are created, and the JSP service approach is invoked.
Destroy: It is the remaining section of the JSP lifecycle, in which the JSP class is unloaded from reminiscence. Usually, it takes place while the application is undeployed, or the server is shut down.
Question: Discuss JSP lifecycle
Answer: JSP lifecycle includes the following techniques:
jspInit(): It is a way that is declared in JspPage, and it’s carried out through JSP container implementations. The technique is called once in the JSP lifecycle to initialize it with config params configured within the deployment descriptor. We can override this method the use of the JSP assertion scripting detail to initialize any assets that we want to apply in the JSP web page.
_jspService(): It is the JSP approach that receives invoked through JSP field for every purchaser request bypassing request and reaction item. Notice that the method name begins with an underscore to distinguish it from different lifecycle methods as this approach can not be overridden. All the JSP code is going in the approach and is changed by default. We must now not attempt to update it using the JSP assertion scripting detail. The technique is described inside the HttpJspPage interface.
JspDestroy(): This method is known as by using the box whilst JSP is unloaded from memory, which include shutting down programs or box. The method is known as handiest as soon as within the JSP lifecycle, and this technique is overridden to launch sources created in JSP init approach.
Question: Is it feasible to override the JSP lifecycle strategies? If sure, which of the strategies can be overridden?
Answer: Yes, we will override JSP lifecycle techniques.Methods consisting of jspInit() and jspDestroy() can be overridden through the use of JSP announcement scripting element. We override jspInit() methods to create common assets that we would like to apply inside the JSP provider technique and override the jspDestroy() approach to launch the common assets.
Question: Mention the literals used in JSP
Answer: JSP makes use of the subsequent literals;
Question: List 3 vital tags used within the development of JSP Bean
Answer: The JSP Bean development makes use of the following three tags as follows:
Question: What are the unique varieties of feedback in JSP?
Answer: There are two styles of comments provided through JSP pages that we are able to use:
HTML Comments: We can use HTML comments like <!-- HTML Comment --> due to the fact that JSP pages are like HTML. These remarks are despatched to the customer as properly and may be seen inside the HTML source. So we must avoid debugging comments or code level feedback using HTML feedback.
JSP Comments: Scriptlets like <%-- JSP Comment --%> are used for writing JSP comments. These comments are not sent to the client an are present within the generated servlet source code. We must use JSP remarks for any code degree or debugging records remarks.
Question: Describe the scripting elements in JSP
Expression, Scriptlets, and Declaration are scripting factors in the JSP web page the use of which upload java code inside the JSP pages.
Any code written in the scriptlet tags goes into the _jspService() method. A scriptlet tag starts offevolved with <% and ends with %>.For instance;
<% Date dt = new Date( ); System.out.println("Current Date=" +dt); %>
There is a shortcut to printing dynamic information inside the JSP web page the use of the out.Print( ) technique via JSP Expressions. JSP Expression starts with <%= and ends with %>.
<% out.print("John"); %> can be written using JSP Expression as <%= "John" %>
Make a be aware that some thing within <%= %> is despatched as a parameter to the out.Print() approach. Also, note that scriptlets can include multiple java statements and continually ends with a semicolon (;), but the expression doesn’t stop with a semicolon.
Declaration of member variables and techniques of the servlet elegance are made the usage of JSP Declarations. JSP Declarations starts offevolved and ends with " <%! " , " %>" respectively.
For instance, we create an int variable in JSP on the magnificence stage as <%! Public static int count=0; %>.
Question: Differentiate between hiding comment and output remark.
Answer: The JSP comment is referred to as conceal comment, whereas the HTML remark is known as the output remark. The JSP remark will not be proven inside the case if a person views the supply of the page, while HTML remarks may be displayed.
Question: Why using scripting factors in JSP discouraged?
Answer: JSP pages are used for view functions, and all of the commercial enterprise good judgment need to be within the servlet or version classes. We need to bypass parameters to the JSP web page through attributes and then use them to create the HTML response within the JSP web page.
Most of the JSP web page contains HTML code and to assist net designers to apprehend JSP web page and broaden them quickly, JSP technology offers movement elements, JSP Standard Tag Library, JSP EL, and custom tags that we use as opposed to scripting elements to bridge the gap among JSP HTML and JSP java part.
Question: What are the five types of JSTL tags?
Answer: They are labeled into 5 types based totally at the JSTL functions:
Core Tags: Provides support for iteration, conditional good judgment, catch the exception, URL, forward or redirect reaction, and greater.
Formatting and Localization Tags: Provided for the formatting of Dates, Numbers, and i18n help thru aid bundles and locales.
SQL Tags: Provide support for interplay with relational databases consisting of Oracle, MySql, and extra.
XML Tags: Used to work with XML files such as parsing XML, transforming XML facts and XPath expression assessment.
JSTL Functions Tags: JSTL tags offer numerous functions that we can use to carry out the standard operation; most of them are for String manipulation including String Concatenation, Split String, and more.
Question: What is JSP Custom Tag, and what are the additives of a JSP custom tag?
Answer: Action Tags, JSP EL, and JSTL tags aren't enough every now and then, and it'd tempt us to put in writing code in Java to carry out a few operations at the JSP web page. Luckily, JSP is extendable, and we will create custom tags to deliver sure offerings.
We can create JSP Custom Tags with the following additives:
JSP Custom Tag Handler
Creating Tag Library Descriptor (TLD) File
Deployment Descriptor Configuration for TLD
We can upload a custom tag library within the JSP page using a taglib directive and then use it.
Question: What are JSP implicit objects?
Answer: Objects created by way of the internet box whilst translating the JSP page to Servlet source to help developers are JSP implicit items. We use those items immediately in scriptlets that pass in the carrier approach. However, they can't be utilized in JSP Declaration because that code will pass at the elegance stage.
We have 9 implicit gadgets that we are able to at once use on the JSP web page. Seven of them are declared as a nearby variable on the start of the _jspService() approach, whereas two of them are a part of the _jspService() method argument that we are able to use.
Question: We can use JSP implicit objects in a method described within the JSP Declaration? True or False? Justify
Answer: False! Because these gadgets are local to provider approach, as nicely those JSP implicit Objects are brought by JSP Container. Also it's far translating JSP web page to servlet supply code. JSP Declarations code went outside the carrier technique, and It is used to create elegance level variables and techniques. Hence can’t use JSP implicit items.
Question: How to include static documents in a JSP?
Answer: Static pages can be protected in a JSP using the consist of directive. The inclusion is carried out once this way within the translation section. A relative URL need to be supplied for the file attribute. Though static assets can be included, it isn't always desired as every request calls for inclusion.
Question: Explain Client-Side and Server-Side Validation.
Server-facet validation is trusted to execute without fail on all enter. The customer is supposed to look ahead to a response from the server before showing any achievement or blunders message to the person because the server can’t execute its validation until it’s acquired an HTTP request. In the case of validation failure, an additional community experience is needed to resend the form to fill out the shape with the appropriate statistics by way of the client.
Question: Explain JSP statement
Answer: Declaration fields and strategies are accomplished using the JSP announcement tag. The code is wrapped internal <%!%> tag and is placed outside of the provider( ) technique of the car-generated servlet. Therefore, it does no longer get memory at every request.
<%! field or method %> Example <html> <body> <%! int val=50; %> <%= "Value of the variable is:"+val %> </body> </html>
Question: Distinguish between JSP Scriptlet and JSP Declaration.
|JSP Scriptlet||JSP Declaration|
|It can only declare variables and not methods.||It can declare both methods and variables.|
|It is placed inside _jspService( ) method.||It is placed outside _jspService( ) method.|
Question: What are the advantages of JSP over ASP?
It is strong and less complicated to use as the dynamic part of the code is written in Java, now not Visual Basic or the Microsoft-particular language.
It is transportable to Non-Microsoft Web servers and different operating systems.
Question: Define the JSP custom tag and its additives.
Answer: Custom tags are person-described tags; we can outline our tags with our capability and use those tags inside the JSP page.
It offers the subsequent blessings:
It eliminates the need for the scriptlet tag.
Separation of business good judgment from the JSP page
Reusability of the JSP page.
It consists of the subsequent components:
Custom tag handler magnificence.
Create a TLD (Tag Library Descriptor) report.
Deployment Descriptor Configuration for TLD
We can add a custom tag library inside the JSP web page the use of a taglib directive after which use it.
Question: How to configure init params for JSP?
Answer: We can configure init params for JSP similar to the servlet in web.Xml file; Also it is vital to configure JSP init params with servlet and servlet-mapping element. The most effective issue that differs from the servlet is a jsp-document detail, wherein we want to provide the JSP web page location.
Question: Distinguish between which includes Directive and encompass Action in JSP
|Include Directive||Include Action|
|It is processed at translation time.||It is processed at run time.|
|It uses a relative or absolute path||It uses a relative path.|
|No other parameters can be passed.||Other parameters can be passed.|
|It includes the contents of resources only and will not process the dynamic resource.||It processes the dynamic resource, and the result will be added to calling JSP|
|Passing any request or response object to calling jsp to included file or JSP or vice versa is not allowed.||Passing any request or response object to calling jsp to included file or JSP or vice versa is allowed.|
Question: What are JSP Action Elements or Action Tags? Explain
Answer: Tags offer beneficial functionalities like which includes assets, working with Java Bean, forwarding the request, and to generate dynamic XML factors. Action factors begin with jsp: and can be utilized in JSP pages immediately without the want to import any tag libraries or some other configuration changes. The JSP tags are:
|jsp:forward||forwards the response and request to another resource.|
|jsp:include||includes another resource|
|Jsp: use of bean||Locates or creates bean objects|
|jsp:setProperty||value of the property is set in the bean object|
|jsp:getProperty||prints the value of the property of the bean|
|jsp:plugin||embeds another component like an applet|
|jsp:param||sets the parameter value. It is used in forward and includes mostly.|
|jsp:fallback||can be used to print the message if the plugin is working. It is used in jsp: plugin.|
Question: What is JSP Expression Language(EL)?
Answer: JSP EL simplifies the accessibility of information stored in Java bean additives and different items like request, software, and consultation.
Question: How to use JSP EL to get the HTTP method call?
Answer: pageContext JSP EL implicit object is used to get the request object reference, and the dot operator is used to get the HTTP technique call within the JSP web page.
Below is the code snippet for the identical:
Question: Can a JSP expand every other java magnificence? If sure, how?
Answer: Yes, JSP can increase any other JSP using this
<%@ include page extends="classname" %>
it’s a accurate because while JSP is transformed to servlet its implements javax.Servlet.Jsp.HttpJspPage interface, so jsp page extends some other java class.
Question: How does JSP communicate with Java documents?
Answer: The import tag
<%@ page import="market.stock.*” %>
like this, we import all of the java documents to jsp and use them as a everyday class. The other way is servlet can send the instance of the java class to jsp, and that object may be retrieved from the request item and apply it to the page.
Question: Which directive is used within the JSP custom tag?
Answer: JSP taglib directive.
Question: Name the 3 tags used in JSP development.
Question: What is the syntax for JSP comments?
<%-- Comment --%>
Question: Is JSP technology extensible? How?
Answer: Yes, JSP technology may be extensible thru the development of tags or custom moves which can be encapsulated in tag libraries.
Question: How can a thread-secure JSP web page be implemented?
Answer: By having JSPs put into effect the SingleThreadModel interface, we will make them thread-safe. This may be completed with the aid of adding the directive <%@ page isThreadSafe="false" %> in the JSP page.
Question: Define JSP expressions
Answer: Scripting language expression contained internal a JSP expression detail is first evaluated, then transformed to a String, and then inserted wherein the expression appears in the JSP document.
The expression element can also include any expression this is legitimate consistent with the Java Language Specification, however semicolon can not be used to end an expression.
<% expression %>
Question: Define the JSP directive?
Answer: The basic shape of the servlet class is laid low with a JSP directive. It has the subsequent shape:
<%@ directive attribute = "value" %>
Question: State the kinds of directive tags?
|<% @page … %>||Defines page dependent attributes.|
|<% @include … %>||File is included during the translation phase.|
|<% @taglib ... %>||Declares a tag library, containing custom actions, used in the page.|
Question: Define JSP literals
Answer: Literals are described as the values, which include a text string or a range of, which can be written as a part of the code.
JSP literals are:
|Boolean||True or false|
|String||with single and double quotes; " is escaped as \," ' is escaped as \,' and \ is escaped as \\.|
|Integer||As in Java|
|Floating Point||As in Java|
Question: How are JSP runtime exceptions dealt with?
Answer: Exception is defined as an abnormality thrown at runtime, and the technique managing the runtime errors is known as exception dealing with.
In JSP the exceptions are handled in ways:
By errorPage and isErrorPage attributes of web page directive
By <error-page> element in internet.Xml file
Question: What is the page directive?
Answer: The page directive gives commands to the field that pertain to the current JSP web page. Page directives may be coded anywhere on the JSP web page.
Question: Why does the _jspService() method starts with an '_' whilst different lifestyles cycle methods do not?
Answer: jspInit() jspDestroy() and _jspService() are essential JSP life cycle method, by means of default something content is written in JSP web page goes in the _jspService() approach with the aid of the container if once more attempts to override this method JSP compiler will supply an blunders however we can override other lifestyles cycle method as implementing this two in JSP so making this distinction box use _ in jspService() method and indicates that the method can not be overridden.
Question: How is JSP used inside the MVC model?
Answer: JSP is used for presentation in the Model View Controller sample (MVC ); it approach it performs the function of the view. The controller calls the model and the business training, which in turn get the facts, and this records is then provided to the JSP for rendering directly to the consumer.
Question: Can the jspInit(), _jspService() and jspDestroy() techniques be overridden?
Answer: We cannot override _jspService() method but jspinit() and jspDestroy() techniques can be overriden.
Question: When to use application scope?
Answer: It is used whilst we need to make information to be had to the whole utility.
Question: Differentiate between JavaBeans and taglib directives
Answer: JavaBeans and taglib were brought for reusability. The following are the major differences between them −
JavaBeans are properly for storing information and country, while Taglibs are for producing presentation factors.
Use custom tags to enforce actions and JavaBeans to provide facts.
Question: How is statistics is exceeded from JSP to blanketed JSP?
Question: Define the auto-refresh feature
Answer: Imagine a webpage showing stay game rating or stock marketplace status or currency trading ratio. The web site wishes to be refreshed frequently the usage of the refresh or reload button with your browser for all such varieties of pages.
JSP makes this activity easy via providing a mechanism where a website can be made in this kind of way that it'd refresh routinely after a given interval.
Question: How is the auto-refresh implemented in JSP?
Answer: The only manner of fresh a Web Page is the use of the method setIntHeader() of the reaction item. Following is the signature of this method −
public void setIntHeader(String header, int header value)
This method sends back header "Refresh" to the browser along with an integer cost, which indicates the time c programming language in seconds.
Question: Define JSTL SQL tags?
Answer: The JSTL SQL tag library affords tags for interacting with relational databases (RDBMSs) along with Oracle, MySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP −
<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
Question: What kind of mistakes can a JSP code come upon?
Checked exceptions: An exception that could be a person blunders or a problem that can not be foreseen through the programmer. For example, if a document is to be opened, but the record can't be found, an exception takes place. These exceptions are difficult to disregard.
Runtime exceptions: An exception that occurs may want to possibly had been avoided with the aid of the programmer. Runtime exceptions are ignored at the time of compilation.
Errors: These are not taken into consideration as exceptions, but the troubles that rise up past the control of the person or the programmer. Errors are overlooked for your code because you may hardly ever do some thing approximately an blunders. For example, if a stack overflow happens, an blunders will arise. They are also omitted on the time of compilation.
Question: How to disable scripting?
Answer: We can disable scripting by using putting the scripting-invalid detail of the deployment descriptor to proper. It is a subelement of the jsp-property-organization. Its valid values are genuine and false. The syntax for disabling scripting is:
<jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group>
It may be annoying to put together for an interview and so here we present you with the most famous JSP Interview questions with a purpose to crack your JSP interview. Do you've got any extra questions to percentage? Or have any guidelines to crack this interview?