SlideShare a Scribd company logo
1 of 11
JSP Interview Questions By Java Training Center:-
1.What is JSP?
Ans:- JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp
files. A JSP compiler is used in the background to generate a Servlet from the JSP page.
2.Explain JSP LifeCycle?
Ans:- JSP’s life cycle can be explained in the following phases.
1. JSP Page Translation:-Jsp never executed directly,first jsp page transalated into servlet. In the
translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The
container interprets the standard directives and actions, and the custom actions referencing tag libraries
used in the page.
2. JSP Page Compilation:-The generated java servlet file is compiled into a java servlet class.
3. Class Loading:-The java servlet class that was compiled from the JSP source is loaded into the
container.
4. Execution phase:-In the execution phase the container manages one or more instances of this class in
response to requests and other events.
The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special
interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().
5. Initialization:-jspInit() method is called immediately after the instance was created. It is called only
once during JSP life cycle.
6. _jspService() execution:-This method is called for every request of this JSP during its life cycle. This is
where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this
phase. It passes the request and the response objects. _jspService() cannot be overridden.
7. jspDestroy() execution:-This method is called when this JSP is destroyed. With this call the servlet
serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.
3.Explain JSP Scripting Tags?
Ans:-We have three Types of Scripting Tags are there in JSP.
1)JSP scriptlet tag :-
JSP scriptlet lets you declare or define any java code that use into the jsp page.
scriptlet tag Start with <% and End with %>
The Code placed inside this tag must end with a semicolon (;).
Syntax:
<% Java Code; %>
EX.
<%
int a = 10;
out.print("a ="+a);
%>
2)JSP Declaration tag:-
JSP declaration lets you declare or define variables and methods (fields) that use into the jsp page.
Declaration tag Start with <%! And End with %>
The Code placed inside this tag must end with a semicolon (;).
Syntax: <%! Java Code; %>
EX:-
<%! private int i = 10; %>
<%!
private int squre(int i)
{
i = i * i ;
return i;
}
%>
3)JSP Expression tag:-
JSP expression is used to insert Java values directly into the output. JSP Expression tag is
use for evaluating any expression and directly displays the output in appropriate web browser.
Expression tag Start with <%= and End with %>
The Code placed inside this tag not end with a semicolon (;).
Syntax:
<%= Java Code %>
For example. the following shows the date/time that the page was requested:
Current time: <%= new java.util.Date() %>
4)What JSP lifecycle methods can I override?
Ans:- You cannot override the _jspService() method within a JSP page. You can however, override the
jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like
database connections, network connections, and so forth for the JSP page. It is good programming
practice to free any allocated resources within jspDestroy().
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and
are typically declared as JSP declarations.
5)Explain about JSP Comments?
Ans:-There is only one type of JSP comment available by JSP specification.
JSP Comment Syntax:
<%-- comment --%>
This JSP comment tag tells the JSP container to ignore the comment part from compilation. That
is, the commented part of source code is not considered for the content parsed for ‘response’.
Example:
<%-- This JSP comment part will not be included in the response object --%>
Note:-
<!-- comment --> is not a JSP comment. This is HTML comment. The JSP container treats this
HTML comment tag as equal as any other HTML tags. When view source is done, the content
given between this tag is visible. This is not anyway related to the JSP container, it is the
expected behaviour of this HTML tag.
Example
<!-- This HTML comment part is included in the response object and can be
seen in view source -->
6)Whst are implicit objects?
Ans:- Implicit objects are objects that are created by the web container and contain information
related to a particular request, page, or application. They are: request, response, pageContext, session,
application, out, config, page, exception.
7)Is there a way to reference the "this" variable within a JSP page?
Ans:-Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference
to the Servlet generated by the JSP page.
8)How do you pass control from one JSP page to another?
Ans:-Use the following ways to pass control of a request from one servlet to another or one jsp to
another.
The RequestDispatcher object ‘s forward method to pass the control.
The response.sendRedirect method.
9) What is the difference between ServletContext and PageContext?
Ans:-ServletContext: Gives the information about the container
PageContext: Gives the information about the Request.
10)Why is _jspService() method starting with an '_' while other life cycle methods
do not?
Ans: main JSP life cycle method are jspInit() jspDestroy() and _jspService() ,bydefault whatever
content we write in our jsp page will go inside the _jspService() method by the container if again will
try to override this method JSP compiler will give error but we can override other two life cycle
method as we have implementing this two in jsp so making this difference container use _ in
jspService() method and shows that we cant override this method.
11) Can you override jspInit() method? If yes, In which cases?
Ans:yes, we can. We do it usually when we need to initialize any members which are to be available for
a servlet/JSP throughout its lifetime.
12)Explain how JSP handle run-time exceptions?
Ans:The errorPage attribute of the page directive can be used to redirects the browser to an error
processing page, when uncaught exception is encountered.
For example: <%@ page errorPage="error.jsp" %> redirects the browser to the JSP page error.jsp if an
uncaught exception is encountered during request processing.
In error.jsp, if it’s indicated that it’s an error-processing page by <%@ page isErrorPage="true" %>
directive, then throwable object describing the exception may be accessed within the error page via the
exception implicit object.
13) Explain how to implement a thread-safe JSP page?
Ans:JSPs can be made thread-safe by having them implement the SingleThreadModel interface by
using <%@ page isThreadSafe="false" %> directive in the page.
By doing this, one will have multiple number of instances (say N) of the servlet loaded and initialized, with
the service method of each instance effectively synchronized.
SingleThreadModel is not recommended for normal use as there are many pitfalls. Hence one should try
the old fashioned way, which is making them thread safe.
14)What's the difference between forward and sendRedirect?
Ans:A forward is server side redirect while sendRedirect is client side redirect.
When a forward request is invoked, the request is sent to another resource on the server. The client is not
informed that a different resource is going to process the request. This process occurs completely within
the web container and then returns to the calling method.
When a sendRedirect method is invoked, it causes the web container to return to the browser indicating
that a new URL should be requested. As a result any object that is stored as a request attribute before
the redirect occurs will be lost. Due to this extra round trip, a sendRedirect is slower than forward.
15)What is the difference between JSP and Servlet life cycles?
Ans:In servlet life cycle, the servlet object is created first. The init() method is invoked by the
servlet container and the servlet is initialized by its arguments. Servlet’s service() method is
invoked next. And at the end, the destroy() method is invoked.
In case of a Java Server Page life cycle, the .jsp is converted into .class file which is a servlet and
then follow the the process of the servlet. In orther words, the .jsp is translated into servlet and
the functionality is same as that of the servlet.
16) Explain the difference between JSP include directive and JSP include action
Ans:When a JSP include directive is used, the included file's code is added into the added JSP page at
page translation time. This happens before the JSP page is translated into a servlet.
However, if any page is included using action tag, the output of the page is returned back to the
added page which happens at runtime
17) Explain JSP Actions in brief?
Ans:JSP actions can be used to print a script expression, create and store a Java Bean and for many
other things. They are used for constructs in XML syntax to control the behavior of the servlet engine.
Dynamic insertion of files, reuse of JavaBeans components, forwarding a user to another page or
generation of HTML for the java plug-in can be done.
Available actions include:
<jsp:include> – Includes a file at the time the page is requested.
<jsp:useBean> - Finds or instantiates a Java Bean.
<jsp:setProperty> - Sets the property of a Java Bean.
<jsp:getProperty> - Inserts the property of a Java Bean into the output.
<jsp:forward> - Forwards the requests to a new page.
jsp:plugin> - used to generate browser specific HTML to specify Java applets. This tag is
replaced by either an <object> or <embed> tag depending on what is more appropriate for Client
Browser.
18) What is difference between custom JSP tags and beans?
Ans:Custom JSP tag is a user defined tag describing the way its attributes and its body are interpreted,
and then the tags are grouped into collections called tag libraries that can be used in any number of JSP
files. Both custom tags and beans encapsulate complex behavior into simple and accessible forms. There
are several differences:
Custom tags can manipulate JSP content but beans cannot.
 Complex operations can be reduced to a much simpler form with custom tags than with beans.
 Custom tags require more work to set up than beans do.
 Custom tags usually defined in relatively self-contained behavior, whereas beans are often
defined in one servlet and used in a different servlet or JSP page.
 Custom tags are available only in JSP 1.1 and later versions, but beans are available in all JSP 1.x
versions.
19) Explain how to perform browser redirection from a JSP page?
Ans:The response implicit objects can be used in the following manner:
response.sendRedirect(http://www.abc.com/path/error.html);
The Location HTTP header attribute can be physically altered, as shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>
You can also use the: <jsp:forward page="/newpage.jsp" />
Note: This can be used only before any output has been sent to the client. Same is the case with
the response.sendRedirect() method as well. If you want to pass any paramateres then you can
pass using <jsp:forward page="/servlet/login"> <jsp:param name="username" value="jsmith" />
</jsp:forward>>
20)What is the page directive is used to prevent a JSP page from automatically
creating a session?
Ans:<%@ page session="false">
21)How do you delete a Cookie within a JSP?
Ans:
Cookie mycook = new Cookie("name","value");
response.addCookie(mycook);
Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
killmycook.addCookie(killmycook);
22)Can we implement an interface in a JSP?
Ans:No
23)How to pass information from JSP to included JSP?
Ans:Using <%jsp:param> tag.
24)How is JSP include directive different from JSP include action. ?
Ans:When a JSP include directive is used, the included file's code is added into the added JSP page at
page translation time, this happens before the JSP page is translated into a servlet. While if any page is
included using action tag, the page's output is returned back to the added page. This happens at
runtime.
25) Can JSP be multi-threaded? How can I implement a thread-safe JSP page?
Ans: By default the service() method of all the JSP execute in a multithreaded fashion. You can make a
page “thread-safe” and have it serve client requests in a single-threaded fashion by setting the page
tag’s is Thread Safe attribute to false:
<%@ page is ThreadSafe=”false” %>
26) Invoking a Servlet from a JSP page? Passing data to a Servlet invoked from a
JSP page?
Ans: Use <jsp:forward page="/relativepath/YourServlet" />
(or)
response.sendRedirect("http://path/YourServlet").
Variables also can be sent as:
<jsp:forward page=/relativepath/YourServlet>
<jsp:param name="name1" value="value1" />
<jsp:param name="name2" value="value2" />
</jsp:forward>
You may also pass parameters to your servlet by specifying
response.sendRedirect("http://path/YourServlet?param1=val1").
27)How do you pass an InitParameter to a JSP?
Ans:<%!
ServletConfig cfg =null;
public void jspInit(){
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();)
{
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+"="+value);
}
}
%>
28) How to view an image stored on database with JSP?
Ans:<%@ page language="java" import="java.sql.*,java.util.*"%>
<%
String image_id = (String) request.getParameter("ID");
if (image_id != null){
try
{
Class.forName("interbase.interclient.Driver");
Connection con =
DriverManager.getConnection("jdbc:interbase://localhost/D:/examp/Database/employee.gdb","java","j
ava");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM IMMAGINE WHERE IMMAGINE_ID = " + image_id);
if (rs.next())
{
String dim_image = rs.getString("IMMAGINE_DIMENSIONE");
byte [] blocco = rs.getBytes("IMMAGINE_IMMAGINE");
response.setContentType("image/jpeg");
ServletOutputStream op = response.getOutputStream();
for(int i=0;i<Integer.parseInt(dim_image);i++)
{
op.write(blocco[i]);
}
}
rs.close();
stmt.close();
con.close();
} catch(Exception e) {
out.println("An error occurs : " + e.toString());
}
}
%>
29) What are the different scope values or what are the different scope values for
"jsp:usebean"?
Ans)
Scope Object Comment
Page PageContext Available to the handling JSP
page only.
Request Request Available to the handling JSP
page or Servlet and forwarded
JSP page or Servlet.
Session Session Available to any JSP Page or
Servlet within the same session.
Application Application Available to all the JSP pages
and Servlets within the same
Web Application.
30) Is JSP variable declaration thread safe?
Ans) No. The declaration of variables in JSP is not thread-safe, because the declared variables
end up in the generated Servlet as an instance variable, not within the body of the _jspservice()
method.
The following declaration is not thread safe: because these are declarations, and will only be
evaluated once when the page is loaded
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside the scriplets have
the local scope and not shared.
<% int a = 5 %>;
31) What are custom tags? Explain how to build custom tags?
Ans) Custom JSP tag is a tag you define. You define how a tag, its attributes and its body are
interpreted, and then group your tags into collections called tag libraries that can be used in any
number of JSP files. So basically it is a reusable and extensible JSP only solution. The pre-built
tags also can speed up Web development.
Step 1
Create a Custom tag class using only doStartTag()
package myTagPkg;
public class MyTag extends TagSupport
{
int attr = null;
public int setAttr(int a ttr){this.attr = a ttr}
public int getAttr(){return attr;}
public int doStartTag() throws JspException {
.......
return 0;
}
public void release(){.....}
}
Step 2 The Tag library descriptor file (*.tld) maps the XML element names to the tag
implementations. The code sample MyTagDesc.tld is shown below:
<taglib>
<tag>
<name>tag1</name>
<tagclass>myTagPkg.MyTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>attr</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
Step 3
The web.xml deployment descriptor maps the URI to the location of the *.tld (Tag Library
Descriptor) file. The code sample web.xml file is shown below:
<web-app>
<taglib>
<taglib-uri>/WEB-INF/MyTagURI</taglib-uri>
<taglib-location>/WEB-INF/tags/MyTagDesc.tld</taglib-location>
</taglib>
</web-app>
STEP: 4
The JSP file declares and then uses the tag library as shown below:
<%@ taglib uri="/WEB-INF/ MyTagURI" prefix="myTag" %>
< myTag:tag1 attr=�abc� />
<taglib>
<tag>
<name>tag1</name>
<tagclass>myTagPkg.MyTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>attr</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
.

More Related Content

What's hot (20)

Jsp(java server pages)
Jsp(java server pages)Jsp(java server pages)
Jsp(java server pages)
 
Jsp lecture
Jsp lectureJsp lecture
Jsp lecture
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Implicit object.pptx
Implicit object.pptxImplicit object.pptx
Implicit object.pptx
 
Jsp Slides
Jsp SlidesJsp Slides
Jsp Slides
 
Jsp
JspJsp
Jsp
 
Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]
 
C:\fakepath\jsp01
C:\fakepath\jsp01C:\fakepath\jsp01
C:\fakepath\jsp01
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
JSP Processing
JSP ProcessingJSP Processing
JSP Processing
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
JSP Scope variable And Data Sharing
JSP Scope variable And Data SharingJSP Scope variable And Data Sharing
JSP Scope variable And Data Sharing
 
Java server pages
Java server pagesJava server pages
Java server pages
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
JSP Directives
JSP DirectivesJSP Directives
JSP Directives
 
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSINGINTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 

Viewers also liked

Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answersiimjobs and hirist
 
Top 9 jsp servlet interview questions answers
Top 9 jsp servlet interview questions answersTop 9 jsp servlet interview questions answers
Top 9 jsp servlet interview questions answersjonhmart036
 
3 project profie-logistics park
3 project profie-logistics park3 project profie-logistics park
3 project profie-logistics parkrhkumarmech
 
Storage And Transportation Of Art Objects
Storage And Transportation Of Art ObjectsStorage And Transportation Of Art Objects
Storage And Transportation Of Art ObjectsMatthew Wettergreen
 
Top 100 PHP Questions and Answers
Top 100 PHP Questions and AnswersTop 100 PHP Questions and Answers
Top 100 PHP Questions and Answersiimjobs and hirist
 
Role of IT in environment & Human Health
Role of IT in environment & Human HealthRole of IT in environment & Human Health
Role of IT in environment & Human HealthTanvi Potluri
 
China warehousing industry report, 2010 2011
China warehousing industry report, 2010 2011China warehousing industry report, 2010 2011
China warehousing industry report, 2010 2011ResearchInChina
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jspAnkit Minocha
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerTOPS Technologies
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobGaruda Trainings
 
java Project report online banking system
java Project report online banking systemjava Project report online banking system
java Project report online banking systemVishNu KuNtal
 
Art Handling
Art HandlingArt Handling
Art HandlingArtLinks
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answersvijaybusu
 
Project planning and feasibility study
Project planning and feasibility studyProject planning and feasibility study
Project planning and feasibility studyMars Mfyam
 

Viewers also liked (18)

Top 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and AnswersTop 100 SQL Interview Questions and Answers
Top 100 SQL Interview Questions and Answers
 
Struts notes
Struts notesStruts notes
Struts notes
 
Top 9 jsp servlet interview questions answers
Top 9 jsp servlet interview questions answersTop 9 jsp servlet interview questions answers
Top 9 jsp servlet interview questions answers
 
3 project profie-logistics park
3 project profie-logistics park3 project profie-logistics park
3 project profie-logistics park
 
Storage And Transportation Of Art Objects
Storage And Transportation Of Art ObjectsStorage And Transportation Of Art Objects
Storage And Transportation Of Art Objects
 
1000+ php questions
1000+ php questions1000+ php questions
1000+ php questions
 
Top 100 PHP Questions and Answers
Top 100 PHP Questions and AnswersTop 100 PHP Questions and Answers
Top 100 PHP Questions and Answers
 
Role of IT in environment & Human Health
Role of IT in environment & Human HealthRole of IT in environment & Human Health
Role of IT in environment & Human Health
 
China warehousing industry report, 2010 2011
China warehousing industry report, 2010 2011China warehousing industry report, 2010 2011
China warehousing industry report, 2010 2011
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Feasibility Study
Feasibility StudyFeasibility Study
Feasibility Study
 
java Project report online banking system
java Project report online banking systemjava Project report online banking system
java Project report online banking system
 
Art Handling
Art HandlingArt Handling
Art Handling
 
Sql queries with answers
Sql queries with answersSql queries with answers
Sql queries with answers
 
Project planning and feasibility study
Project planning and feasibility studyProject planning and feasibility study
Project planning and feasibility study
 
Gdpi (1)
Gdpi (1)Gdpi (1)
Gdpi (1)
 

Similar to Jsp interview questions by java training center

Similar to Jsp interview questions by java training center (20)

Jsp
JspJsp
Jsp
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
 
Spatial approximate string search Doc
Spatial approximate string search DocSpatial approximate string search Doc
Spatial approximate string search Doc
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
Jsp
JspJsp
Jsp
 
Jsp session 1
Jsp   session 1Jsp   session 1
Jsp session 1
 
Unit 4 web technology uptu
Unit 4 web technology uptuUnit 4 web technology uptu
Unit 4 web technology uptu
 
Unit 4 1 web technology uptu
Unit 4 1 web technology uptuUnit 4 1 web technology uptu
Unit 4 1 web technology uptu
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdf
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorial
 
Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jsp
 
The java server pages
The java server pagesThe java server pages
The java server pages
 
Jsp basic
Jsp basicJsp basic
Jsp basic
 
JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...JavaScript, often abbreviated as JS, is a programming language and core techn...
JavaScript, often abbreviated as JS, is a programming language and core techn...
 
Java server pages
Java server pagesJava server pages
Java server pages
 
WEB TECHNOLOGIES JSP
WEB TECHNOLOGIES  JSPWEB TECHNOLOGIES  JSP
WEB TECHNOLOGIES JSP
 

Recently uploaded

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Jsp interview questions by java training center

  • 1. JSP Interview Questions By Java Training Center:- 1.What is JSP? Ans:- JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page. 2.Explain JSP LifeCycle? Ans:- JSP’s life cycle can be explained in the following phases. 1. JSP Page Translation:-Jsp never executed directly,first jsp page transalated into servlet. In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page. 2. JSP Page Compilation:-The generated java servlet file is compiled into a java servlet class. 3. Class Loading:-The java servlet class that was compiled from the JSP source is loaded into the container. 4. Execution phase:-In the execution phase the container manages one or more instances of this class in response to requests and other events. The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService(). 5. Initialization:-jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle. 6. _jspService() execution:-This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden. 7. jspDestroy() execution:-This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle. jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.
  • 2. 3.Explain JSP Scripting Tags? Ans:-We have three Types of Scripting Tags are there in JSP. 1)JSP scriptlet tag :- JSP scriptlet lets you declare or define any java code that use into the jsp page. scriptlet tag Start with <% and End with %> The Code placed inside this tag must end with a semicolon (;). Syntax: <% Java Code; %> EX. <% int a = 10; out.print("a ="+a); %> 2)JSP Declaration tag:- JSP declaration lets you declare or define variables and methods (fields) that use into the jsp page. Declaration tag Start with <%! And End with %> The Code placed inside this tag must end with a semicolon (;). Syntax: <%! Java Code; %> EX:- <%! private int i = 10; %> <%! private int squre(int i) { i = i * i ; return i; } %> 3)JSP Expression tag:- JSP expression is used to insert Java values directly into the output. JSP Expression tag is use for evaluating any expression and directly displays the output in appropriate web browser. Expression tag Start with <%= and End with %> The Code placed inside this tag not end with a semicolon (;).
  • 3. Syntax: <%= Java Code %> For example. the following shows the date/time that the page was requested: Current time: <%= new java.util.Date() %> 4)What JSP lifecycle methods can I override? Ans:- You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy(). The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations. 5)Explain about JSP Comments? Ans:-There is only one type of JSP comment available by JSP specification. JSP Comment Syntax: <%-- comment --%> This JSP comment tag tells the JSP container to ignore the comment part from compilation. That is, the commented part of source code is not considered for the content parsed for ‘response’. Example: <%-- This JSP comment part will not be included in the response object --%> Note:- <!-- comment --> is not a JSP comment. This is HTML comment. The JSP container treats this HTML comment tag as equal as any other HTML tags. When view source is done, the content given between this tag is visible. This is not anyway related to the JSP container, it is the expected behaviour of this HTML tag. Example <!-- This HTML comment part is included in the response object and can be seen in view source --> 6)Whst are implicit objects? Ans:- Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception.
  • 4. 7)Is there a way to reference the "this" variable within a JSP page? Ans:-Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the Servlet generated by the JSP page. 8)How do you pass control from one JSP page to another? Ans:-Use the following ways to pass control of a request from one servlet to another or one jsp to another. The RequestDispatcher object ‘s forward method to pass the control. The response.sendRedirect method. 9) What is the difference between ServletContext and PageContext? Ans:-ServletContext: Gives the information about the container PageContext: Gives the information about the Request. 10)Why is _jspService() method starting with an '_' while other life cycle methods do not? Ans: main JSP life cycle method are jspInit() jspDestroy() and _jspService() ,bydefault whatever content we write in our jsp page will go inside the _jspService() method by the container if again will try to override this method JSP compiler will give error but we can override other two life cycle method as we have implementing this two in jsp so making this difference container use _ in jspService() method and shows that we cant override this method. 11) Can you override jspInit() method? If yes, In which cases? Ans:yes, we can. We do it usually when we need to initialize any members which are to be available for a servlet/JSP throughout its lifetime. 12)Explain how JSP handle run-time exceptions? Ans:The errorPage attribute of the page directive can be used to redirects the browser to an error processing page, when uncaught exception is encountered. For example: <%@ page errorPage="error.jsp" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. In error.jsp, if it’s indicated that it’s an error-processing page by <%@ page isErrorPage="true" %> directive, then throwable object describing the exception may be accessed within the error page via the exception implicit object. 13) Explain how to implement a thread-safe JSP page? Ans:JSPs can be made thread-safe by having them implement the SingleThreadModel interface by using <%@ page isThreadSafe="false" %> directive in the page. By doing this, one will have multiple number of instances (say N) of the servlet loaded and initialized, with the service method of each instance effectively synchronized. SingleThreadModel is not recommended for normal use as there are many pitfalls. Hence one should try the old fashioned way, which is making them thread safe.
  • 5. 14)What's the difference between forward and sendRedirect? Ans:A forward is server side redirect while sendRedirect is client side redirect. When a forward request is invoked, the request is sent to another resource on the server. The client is not informed that a different resource is going to process the request. This process occurs completely within the web container and then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. As a result any object that is stored as a request attribute before the redirect occurs will be lost. Due to this extra round trip, a sendRedirect is slower than forward. 15)What is the difference between JSP and Servlet life cycles? Ans:In servlet life cycle, the servlet object is created first. The init() method is invoked by the servlet container and the servlet is initialized by its arguments. Servlet’s service() method is invoked next. And at the end, the destroy() method is invoked. In case of a Java Server Page life cycle, the .jsp is converted into .class file which is a servlet and then follow the the process of the servlet. In orther words, the .jsp is translated into servlet and the functionality is same as that of the servlet. 16) Explain the difference between JSP include directive and JSP include action Ans:When a JSP include directive is used, the included file's code is added into the added JSP page at page translation time. This happens before the JSP page is translated into a servlet. However, if any page is included using action tag, the output of the page is returned back to the added page which happens at runtime 17) Explain JSP Actions in brief? Ans:JSP actions can be used to print a script expression, create and store a Java Bean and for many other things. They are used for constructs in XML syntax to control the behavior of the servlet engine. Dynamic insertion of files, reuse of JavaBeans components, forwarding a user to another page or generation of HTML for the java plug-in can be done. Available actions include: <jsp:include> – Includes a file at the time the page is requested. <jsp:useBean> - Finds or instantiates a Java Bean. <jsp:setProperty> - Sets the property of a Java Bean. <jsp:getProperty> - Inserts the property of a Java Bean into the output. <jsp:forward> - Forwards the requests to a new page. jsp:plugin> - used to generate browser specific HTML to specify Java applets. This tag is replaced by either an <object> or <embed> tag depending on what is more appropriate for Client Browser.
  • 6. 18) What is difference between custom JSP tags and beans? Ans:Custom JSP tag is a user defined tag describing the way its attributes and its body are interpreted, and then the tags are grouped into collections called tag libraries that can be used in any number of JSP files. Both custom tags and beans encapsulate complex behavior into simple and accessible forms. There are several differences: Custom tags can manipulate JSP content but beans cannot.  Complex operations can be reduced to a much simpler form with custom tags than with beans.  Custom tags require more work to set up than beans do.  Custom tags usually defined in relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.  Custom tags are available only in JSP 1.1 and later versions, but beans are available in all JSP 1.x versions. 19) Explain how to perform browser redirection from a JSP page? Ans:The response implicit objects can be used in the following manner: response.sendRedirect(http://www.abc.com/path/error.html); The Location HTTP header attribute can be physically altered, as shown below: <% response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); String newLocn = "/newpath/index.html"; response.setHeader("Location",newLocn); %> You can also use the: <jsp:forward page="/newpage.jsp" /> Note: This can be used only before any output has been sent to the client. Same is the case with the response.sendRedirect() method as well. If you want to pass any paramateres then you can pass using <jsp:forward page="/servlet/login"> <jsp:param name="username" value="jsmith" /> </jsp:forward>> 20)What is the page directive is used to prevent a JSP page from automatically creating a session? Ans:<%@ page session="false">
  • 7. 21)How do you delete a Cookie within a JSP? Ans: Cookie mycook = new Cookie("name","value"); response.addCookie(mycook); Cookie killmycook = new Cookie("mycook","value"); killmycook.setMaxAge(0); killmycook.setPath("/"); killmycook.addCookie(killmycook); 22)Can we implement an interface in a JSP? Ans:No 23)How to pass information from JSP to included JSP? Ans:Using <%jsp:param> tag. 24)How is JSP include directive different from JSP include action. ? Ans:When a JSP include directive is used, the included file's code is added into the added JSP page at page translation time, this happens before the JSP page is translated into a servlet. While if any page is included using action tag, the page's output is returned back to the added page. This happens at runtime. 25) Can JSP be multi-threaded? How can I implement a thread-safe JSP page? Ans: By default the service() method of all the JSP execute in a multithreaded fashion. You can make a page “thread-safe” and have it serve client requests in a single-threaded fashion by setting the page tag’s is Thread Safe attribute to false: <%@ page is ThreadSafe=”false” %> 26) Invoking a Servlet from a JSP page? Passing data to a Servlet invoked from a JSP page? Ans: Use <jsp:forward page="/relativepath/YourServlet" /> (or) response.sendRedirect("http://path/YourServlet"). Variables also can be sent as: <jsp:forward page=/relativepath/YourServlet> <jsp:param name="name1" value="value1" /> <jsp:param name="name2" value="value2" /> </jsp:forward> You may also pass parameters to your servlet by specifying response.sendRedirect("http://path/YourServlet?param1=val1"). 27)How do you pass an InitParameter to a JSP? Ans:<%! ServletConfig cfg =null; public void jspInit(){ ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
  • 8. String name=(String)e.nextElement(); String value = cfg.getInitParameter(name); System.out.println(name+"="+value); } } %> 28) How to view an image stored on database with JSP? Ans:<%@ page language="java" import="java.sql.*,java.util.*"%> <% String image_id = (String) request.getParameter("ID"); if (image_id != null){ try { Class.forName("interbase.interclient.Driver"); Connection con = DriverManager.getConnection("jdbc:interbase://localhost/D:/examp/Database/employee.gdb","java","j ava"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM IMMAGINE WHERE IMMAGINE_ID = " + image_id); if (rs.next()) { String dim_image = rs.getString("IMMAGINE_DIMENSIONE"); byte [] blocco = rs.getBytes("IMMAGINE_IMMAGINE"); response.setContentType("image/jpeg"); ServletOutputStream op = response.getOutputStream(); for(int i=0;i<Integer.parseInt(dim_image);i++) { op.write(blocco[i]); } } rs.close(); stmt.close(); con.close(); } catch(Exception e) { out.println("An error occurs : " + e.toString()); } } %> 29) What are the different scope values or what are the different scope values for "jsp:usebean"? Ans) Scope Object Comment Page PageContext Available to the handling JSP page only. Request Request Available to the handling JSP page or Servlet and forwarded
  • 9. JSP page or Servlet. Session Session Available to any JSP Page or Servlet within the same session. Application Application Available to all the JSP pages and Servlets within the same Web Application. 30) Is JSP variable declaration thread safe? Ans) No. The declaration of variables in JSP is not thread-safe, because the declared variables end up in the generated Servlet as an instance variable, not within the body of the _jspservice() method. The following declaration is not thread safe: because these are declarations, and will only be evaluated once when the page is loaded <%! int a = 5 %> The following declaration is thread safe: because the variables declared inside the scriplets have the local scope and not shared. <% int a = 5 %>; 31) What are custom tags? Explain how to build custom tags? Ans) Custom JSP tag is a tag you define. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. So basically it is a reusable and extensible JSP only solution. The pre-built tags also can speed up Web development. Step 1 Create a Custom tag class using only doStartTag() package myTagPkg; public class MyTag extends TagSupport { int attr = null; public int setAttr(int a ttr){this.attr = a ttr} public int getAttr(){return attr;} public int doStartTag() throws JspException { ....... return 0; } public void release(){.....} }
  • 10. Step 2 The Tag library descriptor file (*.tld) maps the XML element names to the tag implementations. The code sample MyTagDesc.tld is shown below: <taglib> <tag> <name>tag1</name> <tagclass>myTagPkg.MyTag</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>attr</name> <required>false</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag> </taglib> Step 3 The web.xml deployment descriptor maps the URI to the location of the *.tld (Tag Library Descriptor) file. The code sample web.xml file is shown below: <web-app> <taglib> <taglib-uri>/WEB-INF/MyTagURI</taglib-uri> <taglib-location>/WEB-INF/tags/MyTagDesc.tld</taglib-location> </taglib> </web-app> STEP: 4 The JSP file declares and then uses the tag library as shown below: <%@ taglib uri="/WEB-INF/ MyTagURI" prefix="myTag" %> < myTag:tag1 attr=â€?abcâ€? /> <taglib> <tag> <name>tag1</name> <tagclass>myTagPkg.MyTag</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>attr</name> <required>false</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag> </taglib>
  • 11. .