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� />