SlideShare a Scribd company logo
1 of 14
Download to read offline
1.What is JSP?
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?
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?
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 Ends with %>
The Code placed inside this tag must end with a semicolon (;).
Syntax:
<% Java Code; %>
Example:
<%
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; %>
Example:-
<%! 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?
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?
There is only one type of JSP comment available by JSP specification.
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)What are implicit objects?
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?
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?
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?
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?
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?
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?
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?
JSP's 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?
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?
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
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?
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?
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?
The response implicit objects can be used in the following manner:
<%
response.sendRedirect(http://www.sunotechnosoft.com);
%>
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?
<%@ page session="false">
21)How do you delete a Cookie within a JSP?
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?
No
23)How to pass information from JSP to included JSP?
Using <%jsp:param> tag.
24)How is JSP include directive different from JSP include action. ?
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?
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?
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?
<%!
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?
<%@ 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","java");
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"?
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?
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?
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)

Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]Lap trinh web [Slide jsp]
Lap trinh web [Slide jsp]
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
JSP
JSPJSP
JSP
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
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
JspJsp
Jsp
 
SCWCD : Java server pages CHAP : 9
SCWCD : Java server pages  CHAP : 9SCWCD : Java server pages  CHAP : 9
SCWCD : Java server pages CHAP : 9
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
JSP Processing
JSP ProcessingJSP Processing
JSP Processing
 
Jsp slides
Jsp slidesJsp slides
Jsp slides
 
JSP Directives
JSP DirectivesJSP Directives
JSP Directives
 
Jsp(java server pages)
Jsp(java server pages)Jsp(java server pages)
Jsp(java server pages)
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Jsp Slides
Jsp SlidesJsp Slides
Jsp Slides
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 

Similar to Jsp

JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESYoga Raja
 
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 BasicIMC Institute
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdfArumugam90
 
Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jspAtul Giri
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorialshiva404
 
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...MathivananP4
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsKaml Sah
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Ayes Chinmay
 
Introduction to JSP pages
Introduction to JSP pagesIntroduction to JSP pages
Introduction to JSP pagesFulvio Corno
 

Similar to Jsp (20)

JSP.pptx
JSP.pptxJSP.pptx
JSP.pptx
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Jsp
JspJsp
Jsp
 
Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
 
Java server pages
Java server pagesJava server pages
Java server pages
 
C:\fakepath\jsp01
C:\fakepath\jsp01C:\fakepath\jsp01
C:\fakepath\jsp01
 
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
 
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
 
Spatial approximate string search Doc
Spatial approximate string search DocSpatial approximate string search Doc
Spatial approximate string search Doc
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdf
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jsp
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorial
 
Jsp session 1
Jsp   session 1Jsp   session 1
Jsp session 1
 
Jsp
JspJsp
Jsp
 
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...
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
 
Introduction to JSP pages
Introduction to JSP pagesIntroduction to JSP pages
Introduction to JSP pages
 

Recently uploaded

Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 

Recently uploaded (20)

Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 

Jsp

  • 1. 1.What is JSP? 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? 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.
  • 2. 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? 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 Ends with %> The Code placed inside this tag must end with a semicolon (;). Syntax: <% Java Code; %> Example: <% 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; %> Example:- <%! private int i = 10; %>
  • 3. <%! 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? 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?
  • 4. There is only one type of JSP comment available by JSP specification. 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)What are implicit objects? 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? 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?
  • 5. 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? 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? 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? 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? 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" %>
  • 6. 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? JSP's 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? 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? 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.
  • 7. 16) Explain the difference between JSP include directive and JSP include action 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? 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? 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.
  • 8.  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? The response implicit objects can be used in the following manner: <% response.sendRedirect(http://www.sunotechnosoft.com); %> 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? <%@ page session="false">
  • 9. 21)How do you delete a Cookie within a JSP? 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? No 23)How to pass information from JSP to included JSP? Using <%jsp:param> tag. 24)How is JSP include directive different from JSP include action. ? 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? 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?
  • 10. 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? <%! 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? <%@ page language="java" import="java.sql.*,java.util.*"%> <% String image_id = (String) request.getParameter("ID"); if (image_id != null){
  • 11. try { Class.forName("interbase.interclient.Driver"); Connection con=DriverManager.getConnection("jdbc:interbase://localhost/D:/examp/Database /employee.gdb","java","java"); 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"? Scope Object Comment Page PageContext Available to the handling JSP page only. Request Request Available to the handling JSP page or Servlet and
  • 12. 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? 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? 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 {
  • 13. 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â€? />