Saturday, June 21, 2014

JSP Interview Questions


JSP Interview Questions




1.      List of client side web technologies
      Html-------àfrom w3c
            java script--------àfrom netscape+sun microsystem
            VB script------àform Microsoft
            AJAX-----------àfrom adaptive path

2. List of server side web technologies?
Servlets--------àfrom sun ms(oracle corp)java based
Jsp--------àfrom sun ms(oracle corp)java based
Asp-------àfrom microsoft(non java based)
Asp.net-------àfrom Microsoft(non java based)
PHP---------àfrom apache(non java)

3. Drawbacks of servlets?
--------àstrong programming knowledge is required. so it is not suitable for non java programmers
-------àIf any modifications are done in servlet program we need to recompile and reload the web application
--------àIn servlets  both presentation and business logics are mixed
---àProgrammer must take care of Exception Handling
---àconfiguration of servlet in web.xml file is mandatory
------àIt doesn’t support tags based technology
---àless implicit objects are there more ever we need to write code access them

4.What is page compailation?
The process of converting jsp program into an equivalent servlet program  is called as page compailation.for this we need page compailer every web server gives one jsp page compailer

5.Features of jsp?
----àIt supports tags based programming so it is suitable for both java and non java programmers
-àAny modification are done no compilation and no need of reloading jsp program
--àjsp gives 9 implict objects and we can use directly without writing the code
àtakes care of Exception Handling
--àIt supports all the features of servlets
-àAllows to write presentation logic(html code) seperatly from business logic (java code)
--àconfiguration of jsp in web.xml is optional
--àgives predefinded tags and also allows to develop user defined tags

5.How to decide a web resource is At client side and server side?
It is not based on where web resource resides it is based on where it is executes 

         6. What is diff b/w servlets and jsp?
Servlets
1.It is java style programming
2. Configuration of servlet program is web.xml is mandatory
3. Modifications will be reflected after recompailation and reloading of application
4. Exception Handling is mandatory
5.suitable for java programmers
6.Needs sevlet container for execution of servlet programs
7. Servlet container excutes servlet programs directly
8. page compilations is not required
Jsp
1. It is tag style programming
2. Configuration of servlet program is web.xml is optional
3. Modifications will be reflect directly
4. Exception Handling is optional
5. suitable for java and non-java programmers
6. Needs jsp container for execution of jsp programs
7. jsp container excutes jsp  programs  ofter converting an equivalent servlet
8.Page compilation is required

7.How many types of objects can be there in jsp program?
            1.implict objects(automatically created in jsp equivalent servlet program)
            2.explict objects (created by programmer manually)

8.How many implicit objects are there in jsp?
Object name                                                               Type
1. out                                                               javax.servlet.jsp.JspWriter(abstract class)
2. Request                                                       javax.servlet.http.HttpServletRequest (interface)
3. Response                                                     javax.servlet.http.HttpServletResponse (interface)
4. Application                                                 javax.servlet.ServletContext (interface)
5. Config                                                         javax.servlet.ServletConfig (interface)
6.page                                                              this
7. PageContext                                                           javax.servlet.jsp.PageContext (abstract class)
8. Session                                                        javax.servlet.http.Session (interface)
9. Exception                                                    java.lang.Throwable (class)
----à The out object of a jsp container supplied  java class that extends from javax.sevlet.jsp.JspWriter  this class is changed server to server .in tomcat server this class name is org.apache.Jasper.runtime.JspWriterImpl

9. How many implicit objects are there in every java class?
We have two implicit objects are there in every java class
            1. This
            2. Super

10 What is the name of jsp container in  tomcat server?
Jsp container name is jasper . It comes as tomcat ------lib--------jasper.jar file

11 .Why jsps configuration is optional in web.xml?
The programmers placed in out side of the WEB-INF folder (like html ,jsp)will be recognized by the server  
automatically. So there configuration is optional in web.xml or not required
-àIn side WEB-INF folder web.xml configuration is mandatory

12 .Do u have any command prompt compilation for jsp and why?
No there is no command prompt level compilations for jsp.becoz   every web server having its own jsp compilers that’s why jsps are page compilers’

13.What are the life cycle methods of jsp?
Init-),Service(-,-) ,destroy() methods.becoz container directly calls  these methods
JspInit(),JspService(),JspDestroy() are not life cycle methods container never calls these methods directly .internally life cycle methods calls these methods

14.What is the diff b/w HTML and JSP?
HTML
            1.html is client side web technology
            2.html programmes generates static web pages
            3.needs html interpreter for execution
            4.html tags and attributes are not case sensitive
            5.html is not a strictly typed language
            6.does not allow programmer to create custom tags(user defined tags)
JSP
            1.jsp is server side web technology
            2.jsp programmes generates dynamic  web pages
            3.needs jsp container  for execution
            4.jsp tags and attributes are  case sensitive
            5.jsp is strictly typed technology
            6. allow programmer to create custom tags(user defined tags)

15.What are the life cycle and non life cycle methods of jsp?
NOTE:The servlet life cycle and jsp life cycle methods are same but jsp non life cycle mehods are different
The non life cycle methods are
                                                1. JspInit()
                                                2. JspService()
                                                3. JspDestroy()
----àIn JspInit() we are placing intilization logic of jsp program
------àIn JspService (-, -) contains request processing logic
--------àIn JspDestroy () contains Unintilization logic

16.Strcture of jsp program
            ------------------
            ------------------                   Ordinary text
            ------------------
+           ------------------àtemplate text
            -------------------           
            -------------------                        Html code
            -------------------
 

<%------------------                                                                                                                   
            -----------------                       Scriptlet having java code
            ------------------%>

            ---------------------
            ---------------------                  Html code
             --------------------
 

            <%------------------
            -----------------                  Scriptlet having java code
            -----------------%>
            -------------------
            -------------------                        Ordinary text
            -------------------
17.JSP API?
Every class which is generated for the jsp must implement either
1. Javax.servlet.jsp.JspPage or
 2.javax.servlet.jsp.HttpJspPage
Tomcat provided a base class is.org.apache.jasper.runtime.HttpJspBase

.18.Phases of execution process of jsp program?
We have two phases
            1. Translation phase
            2. Request processing phase
In translation phase the page compiler converts jsp program into equivalents servlet program and java compilers converts the compailed code of this servlet program this indicates page compailer and java compailer will be involed in translation phase
---àIn RequestPorcessing phase JspService(-,-) method of compailed jsp equivalent servlet program will executes and generated  output goes to browser window as web page


19..What happens if source file of jsp equivalent servlet  is deleted and the source code of jsp is not modified?

The request given to jsp program directly participate in Request processing phase

20.How does server /jsp container knows whether the source code of jsp program is modified or not?

Every jsp container preserves the source code of Jsp program related to current request until the next request comes to that jsp program and also compares source codes by taking the support of some compariation tools like wdiff(windows difference)

21.What  happens if programmer directly modifies the source code of jsp equivalent servlet?
After modification if the jsp equivalent  servlet is recompiled and its web-application is reloaded then the modifications will be reflected  in the output otherwise the modifications will not be reflected in the output

22.How to enable <load-on-startup> on jsp program and what is the use of it?
                                    OR
What is the meaning of preInstantiation of jsp?
In web.xml
<web-app>
            <servlet>
<servlet-name>x</servlet-name>
<Jsp-file>?ABC.jsp</Jsp-file>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>x</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
</web-app>
When <load-on-startup> is enabled on jsp program the jsp container complete translation phase of jsp program and also creates the objects of equivalent servlet either during server startup or during the deployment web application then it is called preinsatantiation of jsp program
The advantage of this process is the first request is given to jsp program directly participates in Request-processing phase(make sure that the jsp program is not modified before first request)

23.       Tags/Elements of jsp?
1.Scriptlet tags/elements
            a.Scriptlet(<%-------%>)
            b.Expression(<%=-------%>)                   these tags  are designed to place java code
            c.Declaration(<%!---------%>
2.Jsp Comments
            <% --        -------
            ------------     ---%>
3.Directive tags:
            a.page directive(<%@page attribute%>)
            b.include directive(<%@include attribute%>)
            c.taglib directive(<%@taglib attribute%>)
4.standard Action tags
a.<Jsp:forward>
b.<Jsp:include>
c.<Jsp:useBean>
<Jsp:fallback>
<Jsp:setProperty>
<Jsp:getProperty>


<Jsp:plugin>


Q)        Scriptlet?
Scriptlet is a place to allow the java business  logic. this code generates dynamic content  
Any jsp element/tag contains two syntaxes
1.xml syntax
2.standard syntax
The standard syntax for script let is
<%-------------------
---------------------------%>
EX.<%
            int a=10;
            int b=10;
            if(a<b)
            out.println(“a+”is less then “+b);
            out.println(a+ “is greater then  or equal to “+b);
            %>
The xml syntax for script let is
            <jsp: scriptlet
            ---------------------------------
            ---------------------------------
</jsp:scriptlet>
Ex:<Jsp:scriptlet>      
            int   a=10;
            int b=100;
            int c=a+b;
out.println(“sum is “+c);
</Jsp: scriptlet>

--------àReal time industry uses standard syntax only
----------àvariables declared in script let becomes local variables of JspService()
Method in jsp equivalent servlet program
---------àAll implic objects are local variables of JspService(-,-)
Method so they are visible in scriptlet directly

Q) Declaration tag?
By using declaration we can define instance variables definition and java method definitions, JspInit (), JspDestroy () method definitions’
Declaration tag standard syntax:
            <%!-----------------
                   ---------------
                                    %>
 

Ex:       <%! Int a=10;
                        Int b=20; %>                 scriptlet tag

                   
<% int c=a+b;
Out.println (“sum is “+c);%>                    declaration tag

Xml syntax for declaration tag
                                                                  <Jsp: scriptlet>
                                                                       Int a=10;
                                                                  </Jsp: scriptlet>
                                                                <Jsp: declaration>
                                                                       Int a=10;
                                                               </Jsp: declaration>
                                                                  <Jsp: scriptlet>
                                                   Out.println (“a local value is:”+a);
                                             Out.println (“a is global value is:”+this.a);
                                                                 </Jsp: Scriptlet>
24.How to differentiate variables declared in a scriptlet, declaration tags while using them in scriptlet and when they have got same name?

We can use either “this” keyword or the implicit object “page” to differentiate member variable (declaration tag) from local variable (scriptlet tag)

25..Expression  tag?
àIt evolutes the given expression and show the generated output of the browser window
Syntax:               <% =---------- %>
àAnything that generates results is called as expression ex.arthimetic operations, ,logical operation method,instantiations-----etc                                      
àthis can also display the variables values and also for instantiation(object creation)
àone expression tag can evaluate one one expression .if we need multiple evaluations we can use multiple expressions
-àexpression tag is to minimize the out.println() operation. That means the expression tag internally uses out.println()  method to display the results generated by the given expression

26.what are the Comments in Jsp?
In jsp program we can keep 3 types of comments
                    1.Jsp comments/Hidden comments(<%--     --------     --%>
                    2.Html comments/text comments(<!--      ------------    -->
                    3.java comments/script comment
                                                            //-------àfor single line
                                                    /*--------------
                                               -----------------------*/ for multiple line

---àJsp comments will be recognized by jsp page compiler and these are given to jsp tags
---àHtml comments will be recognized by html interpreter and these are given to html code
---àjava comments will be reconciled by java compilers and these are given to comment java code

27) which/why comments are called hidden comments?
Jsp comments are called hidden comments.becoz these are not visiable in phase of the execution

28)can you generate jsp equivalent servlet outside the server?
Yes. For this we need  to work with the server supplied tools .
In weblogic tool is: weblogic.jspc                                       page compilers’
In tomcat tool is: org.apache.Jasper.Jspc

29) Jsp communication?
            1.Html to jsp communication
            In this we have to  do this < form action=”ABc.jsp”/>
            2.Jsp to Jsp communication
            3.Jsp to bean  communication

30)What are Directive tags?
Directive tags are gives a direction to jsp equivalent servlet by generating necessary code at transalation phase.these tags are never perform any operations directly
We  have 3 directive tags
            1.page directive
            2.include directive
            3.taglib directive
1.page directive                             
By using this we can pass global information to jsp program like package importing ,buffer size---etc
Standard syntax is:  <%@page attributes %>
We have many attributes like the following
1.language=”java”
Here java allowed only.no other languages are not allowed.java is default language here
2<%@.import=”java.util.*,java.util.sql.*;”%>
Here the default is java.lang.*; package.we can use any packages in side the import
3.<%@page extends=”classname”%>
It is not recommended to use.no default here
4.<%@page contentType=”text/html”%>
Here we can use any mime types.here default is “text/html”
5.<%@page info=”testing jsp page”%>
This tag allows to programmer to write some description of jsp program
6.<%@page isThreadSafe=”true”%>--------ànot a thread safe
The default value is true.jsp equivalent servlet does not implements javax.servlet.SingleThreadModel interface.so it doesnot make jsp equivalent servlet object as a thread safe.
If  we want to make jsp equivalent servlet object as thread safe we need use  above we use false
            <%@page isThreadSafe=”false”%>--------àit is a thread safe
7.<%@page buffer=”10kb” autoFlush=”true”%>
Every servlet/jsp maintains at server side to hold the remaining lines temparly until the output from last line is generated.the default minimum size is 8kb. By using auto flushing we can enable or disable autoflushing on this buffer

31) Jsp program buffer size is 5kb.but it is generating more then 5kb.output.can u tell me what happens when this jsp is requested?
The buffer size will be expanded automatically as needed and output of jsp program will be stored in the buffer and it will be flushed to browser window only once
--àflushing buffer is nothing but sending the output  from buffer(server)to browser window

32.What is the difference b/w implicit object page and page Context?
àpage implicit object holds “this”nothing but reference of the currently executing jsp equavalent servlet class object.this object is useful to differenciate declaration tag variable from scriptlet tag variable when they have got same name
àpageContext object holds multiple details of jsp
page.like”this”,”request”,”response” objects, error page name, buffer size, session objects availability…etc

33.Exception Handling in jsp pages?
In jsp we have two  error configuration apporches
            1.Local Error page configuration
àIt is specific to each main jsp program
error.jsp
<%@page isErrorPage=”true”%>
à This can be achived using errorPage and isErrorPage Attributes
            2.Global Error page Configuration
àIt is common for all the jsp programs of web application
àthis can be configured in web.xml using <error-page>tag
34.page Directive tag?
Page directive tag name and its attributes are case sensitive. Invalid attributes are not allowed. Only import attribute can be allowed multiple times. No other attributes are not allowed multiple times
 

Ex.<%@page session=”false”%>                               Invalid
            <%@page session=”true” %>

 

%@import=”java.util.*” %>                            Valid


Note: Except import attribute no other attributes can contain multiple vales separated with comma Symbol
35.What is the difference b/w Print Writer and JspWriter?
PrintWriter
è This class belongs to Java.io.* package
è It generally used in servlets programmer
è Methods doesn’t throw IoExceptions
è The output of the servlet program goes to browser window
è Doesn’t dealing with buffering while writing response
JspWriter
è This class belongs to Javax.servlet.Jsp.* package
è It generally used in jsp programmers as implicit object out
è Methods  throw IoExceptions
è The output of the jsp  program goes to browser window to this class object
è deals with buffereing while writing response

36.How manys to import package in jsp program?
<jsp:directive.page= import=”java.util.*”/>
                        Or
                        Or
37.What is the diff b/w DirectiveInclude and  Action Include tag?
Directive Include
àperforms code inclusion at  translation phase/ page compailation time so it is called static/compaile time binding
àIf destination program is jsp then it doesn’t generate jsp equivalent servlet program for it
àit doesn’t use rd.include() internally
àdoesn’t allow servlet program as destination program
àgives both xml,standard syntaxes
àsuiatable when destination program is static program like html

ActionInclude
àperforms code inclusion a Request processing phase/ runtime  so it is called dynamic/Runtime time binding
àIf destination program is jsp then it  generate jsp equivalent servlet program for it
àIt internally uses rd.include()
à allows servlet program as destination program
àgives only  xml syntaxes
àsuiatable when destination program is dynamic program like servlet,jsp---
38.How to create a bean object in jsp?
By using<jsp:useBean>tag
Syntax is
<jsp:useBean id=”obj1” class=”pack1.TestBean” scope=”page”/>
Here id is object reference and class is fully quqlified name of bean class

39.What are different scopes in jsp?
            1.page
            2.request
            3.session
            4.application
--àleast scope is page because it is default scope in every jsp page
àhighest scope is appliction
àif the scope of bean object is page then it is not sharable with other jsp pages.it is accessable in within that jsp page only
àIf the scope of bean object is  request then it is sharable with other pages when it is same request.It is valid until request is dead
àIf the scope of bean object is session then it will be sharable to within session
One session=one client
If another client is made a request then one more bean object is created.becoz it is new session
àIf the bean scope is application then the object is created one per one application.(like Context object in servlets) 
Q1) What is a JSP? What is it used for? What do you understand by the term JSP translation phase or compilation phase?
Ans) JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println(“….. â€?) statements, where out is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.

The JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file into a JSP Servlet. The translated and compiled JSP Servlet moves to the execution phase (run time) where they can handle requests and send response.

Unless explicitly compiled ahead of time, JSP files are compiled the first time they are accessed. On large production sites, or in situations involving complicated JSP files, compilation may cause unacceptable delays to users first accessing the JSP page. The JSPs can be compiled ahead of time (ie precompiled) using application server tools/settings or by writing your own script.
Q2) Explain the life cycle methods of a JSP?
Ans) Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize theServlet. Called only once per Servlet instance.
Servicing: Services the client requests. Container calls this method for each request.
Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.
Q3) What are different type of scripting elements?
Declaration Element: is the embedded Java declaration statement, which gets inserted at the Servlet class level.
<%! Calendar c = Calendar.getInstance(); %>
Important: 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.

Expression Element: is the embedded Java expression, which gets evaluated by the service method.
<%= new Date()>

Scriptlet Elements: are the embedded Java statements, which get executed as part of the service method.
(Note: 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).
<%
//Java codes
String userName=null;
userName=request.getParameter("userName");
%>


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

Directive Elements: A JSP element that provides global information for the translation phase.
<%@ page import=�java.util.Date� %>
<%@ include file=�myJSP� %>
<%@ taglib uri=�tagliburi� prefix=�myTag�%>
Q4) 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.
Q5) What are the differences between static and a dynamic include?
Ans)
Static <%@include%>
Dynamic include <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.
Q6) 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 %>;

Q7) Explain JSP URL mapping? What is URL hiding or protecting the JSP page?
Ans) The JSP resources usually reside directly or under subdirectories (e.g. myPath) of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files, css (cascading style sheets) files, Java Script files, pdf files, image files, html files etc from direct access. The request should be made to a servlet who is responsible for authenticating and authorising the user before returning the protected JSP page or its resources.
Q8) 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>
Q9) What is the difference between custom JSP tags and JavaBeans?
Ans) In the context of a JSP page, both accomplish similar goals but the differences are:
Custom Tags
JavaBeans
Can manipulate JSP content.
Can't manipulate JSP content.
Custom tags can simplify the complex operations much better than the bean can. But require a bit more work to set up.
Easier to set up.
Used only in JSPs in a relatively self-contained manner.
Can be used in both Servlets and JSPs. You can define a bean in one Servlet and use them in another Servlet or a JSP page.
JavaBeans declaration and usage example:
<jsp:useBean id="identifier" class="packageName.className"/>
<jsp:setProperty name="identifier" property="classField" value="someValue" />
<jsp:getProperty name="identifier" property="classField" />
<%=identifier.getclassField() %>
Q10) What is a Expression?
A: An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression.
Q11) Difference between forward and sendRedirect?
Ans) When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
Q12) What are implicit objects? List them?
Ans) Certain 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 listed below:
request
response
pageContext
session
application
out
config
page
exception
Q13) How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
Ans) You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.

<% response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
Q14) How to implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
Ans) JSPs can be thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive
<%@ page isThreadSafe="false" %>
within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .
Q15) Why to use the HttpServlet Init method to perform expensive operations that need only be done once?
Ans) Because the servlet init() method is invoked when servlet instance is loaded, it is the perfect location to carry out expensive operations that need only be performed during initialization. By definition, the init() method is thread-safe. The results of operations in the HttpServlet.init() method can be cached safely in servlet instance variables, which become read-only in the servlet service method.
Q16) Why is it not a good practice to create HttpSessions in JSPs by default?
Ans) By default, JSP files create HttpSessions. This is in compliance with J2EETM to facilitate the use of JSP implicit objects, which can be referenced in JSP source and tags without explicit declaration. HttpSession is one of those objects. If you do not use HttpSession in your JSP files then you can save some performance overhead with the following JSP page directive:
<%@ page session="false"%>
Q17) What are the standard actions available in JSP?
Ans) The standard actions available in JSP are as follows:
<jsp:include>: It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.


No comments:

Post a Comment