Explain the life cycle methods of a JSP?
JSP Life Cycle
1. Page translation: - The page is parsed and a Java file containing the corresponding servlet is created.
2. Page compilation: - The Java file is compiled.
3. Page loading: - The compiled class is loaded.
4. Create instance: - An instance of the servlet is created.
5. Call jspInit():-This method is called before any other method to allow initialization.
6. Call _jspService ():-Services the client requests. Container calls the _jspService () method for each request.
1. Page translation: - The page is parsed and a Java file containing the corresponding servlet is created.
2. Page compilation: - The Java file is compiled.
3. Page loading: - The compiled class is loaded.
4. Create instance: - An instance of the servlet is created.
5. Call jspInit():-This method is called before any other method to allow initialization.
6. Call _jspService ():-Services the client requests. Container calls the _jspService () method for each request.
7. Call jspDestroy():-This method is called when the servlet container decides to take the servlet out of service.
What are the main elements of JSP?
There are three types of dynamic elements. (TIP: remember SAD as an abbreviation for
Scripting elements,
Action elements and
Directive elements.
Scripting Elements: A JSP element that provides embedded Java statements. There are three types of scripting elements.
They are
1.Declaration
2.Expression
3.Scriplet elements.
1. Declaration Element: is the embedded Java declaration statement, which gets inserted at the Servlet class level.
<%! Calendar c = Calendar.getInstance(); %>
Declaring variables via this element is not thread-safe, because this variable ends up in the generated Servlet as an instance variable, not within the body of the _jspService() method. Ensure their access is either read-only or synchronized. You can make your JSP generated servlets implement the SingleThreadModel with the directive
<%@ page isThreadSafe=”false” %>
2. Expression Element: is the embedded Java expression, which gets evaluated by the service method.
<%= new Date() %>
There is no semicolon (;) at the end of the expression.
Expression become the argument to an out.print();
Ex :-<%= counter.getCount()%> turn into out.print(counter.getCount());
3. Scriptlet Element: are the embedded Java statements, which get executed as part of the service method.
<%
String username = null;
username = request.getParameter("userName");
//”request” is a JSP implicit object
%>
Important: Not recommended to use Scriptlet elements because they don’t provide reusability and maintainability. Use custom tags like JSTL, JSF tags, etc or beans instead.
Action Elements: A JSP element that provides information for execution phase.
<jsp:useBean id="object_name" class="class_name"/>
<jsp:include page="scripts/login.jsp" />
<jsp:forward/>
<jsp:plugin/>
<jsp:setProperty/>
<jsp:getProperty/>
Directive Elements: A JSP element that provides global information for the translation phase. There are three types of directive elements. They are page, include and taglib.
<%-- page directives examples: --%>
<%@ page
[ language="java" ]
[ extends="package.class" ]
[ import="{package.class | package.*}, ..." ]
[ session="true | false" ]
[ language="java" ]
[ extends="package.class" ]
[ import="{package.class | package.*}, ..." ]
[ session="true | false" ]
[ errorPage="relativeURL" ]
[ isErrorPage="true | false" ]
[ isThreadSafe="true | false" ]
[ buffer="none | 8kb | sizekb"]
[ autoFlush="true | false" ]
[ info="text" ]
[ contentType="mimeType [ ;charset=characterSet ]" | "text/html ; charset=ISO-8859-1" ]
%>
[ buffer="none | 8kb | sizekb"]
[ autoFlush="true | false" ]
[ info="text" ]
[ contentType="mimeType [ ;charset=characterSet ]" | "text/html ; charset=ISO-8859-1" ]
%>
<%@ page import=”java.util.Date” %> //to import
<%@ page contentType=”text/html” %> //set content type
<%-- include directive example: --%>
<%@ include file=”myJSP” %> // to include another file
<%-- taglib directive example: --%>
<%@ taglib uri=”tagliburi” prefix=”myTag”%>
Is exception implicit object visible to all jsp pages?
No, it will available to a jsp page through <%@ page isErrorPage =”true”%>
What are the differences between static and a dynamic include?
Static include<%@ include %>
|
Dynamic include<jsp:include……>
|
During the translation or compilation phase all the included JSP pages are compiled into a single Servlet.
|
The dynamically included JSP is compiled into a separate Servlet.It is a separate resource, which gets to process the request, and the content generated by this resource is included in the JSP response.
|
No run time performance overhead.
|
Has run time performance overhead.
|
<%@ include file=”abc.jsp” %>
|
<jsp:include page=”abc.jsp” flush=”true”/>
|
Which one to use: Use “static includes” when a JSP page does not change very often. For the pages, which change frequently, use dynamic includes.
Dynamic includes generate a separate JSP Servlet for each included file.
Note: The “dynamic include” (jsp: include) has a flush attribute. This attribute indicates whether the buffer should be flushed before including the new content. In JSP 1.1 you will get an error if you omit this attribute. In JSP 1.2 you can omit this attribute because the flush attribute defaults to false.
How does JSP handle run-time exceptions?
You can use the attribute “errorPage” of the “page” directive to have your uncaught RuntimeExceptions automatically forwarded to an error processing page. Example:
<%@ page errorPage=”error.jsp” %>
Note: You must always use a relative URL as the “errorPage” attribute value.
The above code redirects the browser client to the error.jsp page. Within your error.jsp page, you need to indicate that it is an error processing page with the “isErrorPage” attribute of the “page” directive as shown below.
“exception” is an implicit object accessible only within error pages (i.e. pages with directive <%@ page isErrorPage=”true” %>
<%@ page isErrorPage=”true” %>
<body>
<%= exception.gerMessage() %>
</body>
What are the different scope values for <jsp:usebean>?
Scope
|
Object
|
Comment
|
Page
|
PageContext
|
Available to the handling JSP page only.
Page is the default Scope.
|
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.
|
What are implicit objects and list them?
Implicit objects are the objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated Servlet. The implicit objects are:
Implicit Object
|
Scope
|
Comment
| |
Request
|
Request
|
Refers to the current request from the client.
| |
Response
|
Page
|
Refers to the current response to the client.
| |
Session
|
Session
|
Refers to the user’s session.
| |
Application
|
Application
|
Same as ServletContext. Refers to the web application’s environment.
| |
Config
|
Page
|
same as ServletConfig. Refers to the servlet’s configuration.
| |
Page
|
Page
|
Refers to the page’s Servlet instance.
| |
pageContext
|
Page
|
Refers to the page’s environment.
| |
Out
|
Page
|
Refers to the outputstream.
| |
Exception
|
Page
|
exception created on this page. Used for error handling. Only available if it is an
errorPage with the following directive:
<%@ page isErrorPage="true" %>
The “exception” implicit object is not available for global error pages declared through
web.xml. You can retrieve the java.lang.Throwable object as follows:
<%=request.getAttribute("javax.servlet.error.exception") %>
|
<%
String username = null;
username = request.getParameter("userName"); //”request” is an implicit object
out.print(username); //”out” is an implicit object
%>
Note: Care should be taken not to name your objects the same name as the implicit objects. If you have your own object with the same name, then the implicit objects take precedence over your own object.
Explain hidden and output comments?
A: An output comment is a comment that is sent to the client where it is viewable in the browser’s source.
<!-- This is a comment which is sent to the client -->
A hidden comment documents a JSP page but does not get sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags.
<%-- This comment will not be visible to the client --%>
Is JSP variable declaration thread safe?
A : 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 declarations end up in the generated servlet as instance variables.
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside the scriplets end up in the generated servlet within the body of the _jspService() method as local variables.
<% int a = 5 %>
Can you declare a method within your JSP page?
You can declare methods within your JSP pages as declarations, and your methods can be invoked from within your other methods you declare, expression elements or scriptlets. These declared methods do not have direct access to the JSP implicit objects like session, request, response etc but you can pass them to your methods you declare as parameters.
Example:
<%!
//JSP method where implicit session object as method argument
public String myJspMethod(HttpSession session) {
String str = (String)session.getAttribute("someAttrName");
return str.substring(0,3);
}
%>
Note: Declaring methods within a JSP page is a bad practice because it will make your JSP page hard to read, reuse and maintain.
How would you invoke a Servlet from a JSP? Or invoke a JSP form another JSP?
You can invoke a Servlet from a JSP through the jsp:include and jsp:forward action tags.
<jsp:include page=”/servlet/MyServlet” flush=”true” />
How do you forward a request to another resource (e.g. another Servlet) from within your JSP?
//Without passing any parameters
<jsp:forward page=”/anotherPage.jsp” />
Can we implements interface or extends class in JSP?
We cannot implement an interface in a jsp but we can extend a class in JSP by using extends attribute of the page directive.
< @ page extends="package.class" >
Q.Which code line must be set before any of the lines that use the PrintWriter? < @ page extends="package.class" >
Ans: PrintWriter pw=res.getWriter();
How can you prevent the automatic creation of a session in a JSP page?
Sessions consume resources and if it is not necessary, it should not be created. By default, a JSP page will automatically create a session for the request if one does not exist. You can prevent the creation of useless
sessions with the attribute “session” of the page directive.
<%@ page session=”false” %>
If it is not a good practice to implement methods within your JSPs then can a JSP page process HTML form data?
Yes. Unlike servlets you do not have to implement HTTP specific methods like doGet(), doPost() etc in your JSPs. In JSPs you can obtain the form data via the “request” implicit object within a scriptlet or expression as follows:
<%
String firstName = request.getParameter(“param1”);
int units = new Integer(request.getParameter(“param2”)).intValue();
%>
Q. How will you perform a browser redirection from a JSP page?
<% response.sendRedirect(“http://www.someAbsoluteAddess.com”); %>
or you can alter the location HTTP header attribute as follows:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader(“Location”, “/someNewPath/index.html”);
%>
Q. How do you prevent the HTML output of your JSP page being cached?
<%
response.setHeader(“Cache-Control”, “no=store”); //HTTP 1.1
response.setDateHeader(“Expires”, 0);
%>
JSP date example
In the JSP Declaratives
<%@page contentType="text/html" import="java.util.*" %>
we are importing the java.util package and following JSP Expression code
<%= new java.util.Date() %>
prints the current date on the page.