Wednesday 26 June 2013

JSP Interview Question

JSP Interview Question :

Question 1: Explain include Directive and include Action of JSP
Ans:  This is a very popular interview question on JSP, which has been asked from long time and still asked in various interview. This question is good to test some fundamental concept like translation of JSP and difference between translation time and run time kind of concept.

Syntax for include Directive is <%@ include file="fileName" %> which means we are including some file to our JSP Page when we use include directive contents of included file will be added to calling JSP page at translation time means when the calling JSP is converted to servlet ,all the contents are added to that page .one important thing is that any JSP page is complied if we make any changes to that particular page but if we have changed the included file or JSP page the main calling JSP page will not execute again so the output will not be according to our expectation, this one is the main disadvantage of using the include directive that why it is mostly use to add static  resources, like Header and footer .

Syntax for include action is <jsp:include page=”relativeURL” /> it’s a runtime procedure means the result of the JSP page which is mentioned in relative URL is appended  to calling JSP at runtime on their response object at the location where we have used this tag
So any changes made to included page is being effected every time, this is the main advantage of this action but only relative URL we can use here ,because request and response object is passed between calling JSP and included JSP.

Question 2: Difference Between include Directive and include Action of JSP
This JSP interview question is a continuation of earlier question I just made it a separate one to write answer in clear tabular format.

Include Directive
Include Action
include directive is processed at the translation time
Include action is processed at the run time.
include directive can use relative or absolute path
Include action always use relative path
Include directive can only include contents of resource it will not process the dynamic resource
Include action process the dynamic resource and result will be added to calling JSP
We can not pass any other parameter
Here we can pass other parameter also using JSP:param
We cannot  pass any request or responseobject to calling jsp to included file or JSP or vice versa
In this case it’s possible.


Question 3: Is it possible for one JSP to extend another java class if yes how?

Ans: Yes it is possible we can extends another JSP using this <%@ include page extends="classname" %> it’s a perfectly correct because when JSP is converted to servlet its implements javax.servlet.jsp.HttpJspPage interface, so for jsp page its possible to extend another java class . This question can be tricky if you don’t know some basic fact J, though its not advisable to write java code in jsp instead its better to use expression language and tag library.

Question 4: What is < jsp:usebean >tag why it is used.


JSP Interivew questions Answers
Ans: This was very popular JSP interview question during early 2000, it has lost some of its shine but still asked now and then on interviews.

JSP Syntax
<jsp:useBean
        id="beanInstName"
        scope="page | request | session | application"
     
            class="package.class"    type="package.class"

           </jsp:useBean>

This tag is used to create a instance of java bean first of all it tries to find out the bean if bean instance already exist assign stores a reference to it in the variable. If we specified type, gives the Bean that type.otherwise instantiates it from the class we specify, storing a reference to it in the new variable.so jsp:usebean is simple way to create a java bean.
Example:
     
<jsp:useBean id="stock" scope="request" class="market.Stock" />
<jsp:setProperty name="bid" property="price" value="0.0" />
a <jsp:useBean> element contains a <jsp:setProperty> element that sets property values in the Bean,we have <jsp:getProperty>element also to get the value from the bean.

Explanation of Attribute

 id="beanInstanceName"
A variable that identifies the Bean in the scope we specify. If the Bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used in the original <jsp:useBean> element.
scope="page | request | session | application"
The scope in which the Bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:
  • page – we can use the Bean within the JSP page with the <jsp:useBean> element
  • request – we can use the Bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another file.
  • session – we can use the Bean from any JSP page in the same session as the JSP page that created the Bean. The Bean exists across the entire session, and any page that participates in the session can use it..
  • application – we can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean.
class="package.class"
Instantiates a Bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor.
type="package.class"
If the Bean already exists in the scope, gives the Bean a data type other than the class from which it was instantiated. If you use type without class or beanName, no Bean is instantiated.

Question 5: How can one Jsp Communicate with Java file.

Ans:we have import tag <%@ page import="market.stock.*” %> like this we can import all the java file to our jsp and use them as a regular class another way is  servlet can send  the instance of the java class to our  jsp and we can retrieve that object from the request obj and use it in our page.

Question 6: what are the implicit Object

Ans: This is a fact based interview question what it checks is how much coding you do in JSP if you are doing it frequently you definitely know them. Implicit object are the object that are created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.they are bydefault available in JSP page.

They are: request, response, pageContext, session, and application, out, config, page, and exception.

Question 7: In JSP page how can we handle runtime exception?

Ans: This is another popular JSP interview question which has asked to check how candidate used to handle Error and Exception in JSP. We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.

Example: <%@ page errorPage="error.jsp" %>
It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage="true" %>


Question 8: Why is _jspService() method starting with an '_' while other life cycle methods do not?

Ans: main JSP life cycle method are jspInit() jspDestroy() and _jspService() ,bydefault whatever content we write in our jsp page will go inside the _jspService() method by the container if again will try to override this method JSP compiler will give error but we can override other two life cycle method as we have implementing this two in jsp so making this difference container use _ in jspService() method and shows that we cant override this method.


Question 9: How can you pass information form one jsp to included jsp:

Ans: This JSP interview question is little tricky and fact based. Using < Jsp: param> tag we can pass parameter from main jsp to included jsp page

Example:
<jsp:include page="newbid.jsp" flush="true">
<jsp:param name="price" value="123.7"/>
<jsp:param name="quantity" value="4"/>

Question 10: what is the need of tag library?

Ans tag library is a collection of custom tags. Custom actions helps recurring tasks will be handled more easily they can be reused across more than one application and increase productivity. JSP tag libraries are used by Web application designers who can focus on presentation issues rather than being concerned with how to access databases and other enterprise services. Some of the popular tag libraries are Apache display tag library and String tag library. You can also check my post on display tag library example on Spring.

Please contribute any interview questions asked to you guys on JSP Interview or if you are looking for answer of any JSP questions, I will try to help you.


Read more: http://javarevisited.blogspot.com/2011/10/jsp-interview-questions-answers-for.html#ixzz2XKu1PRBY


Common JSP interview questions

  1. What are the 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.
  2. Is JSP technology extensible? - Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
  3. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? - You can make your JSPs 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 <%! DECLARE %>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
  4. How does JSP handle run-time exceptions? - You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %>
    redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
  5. How do I prevent the output of my JSP or Servlet pages from being cached by the browser? - 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
    %>
  6. How do I use comments within a JSP page? - You can use “JSP-style” comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example:
     <%-- the scriptlet is now commented out
     <%
     out.println("Hello World");
     %>
     --%>
    
    You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:
    <!-- (c) 2004 -->
    Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:
     <%
     //some comment
     /**
     yet another comment
     **/
     %>
    
  7. Response has already been commited error. What does it mean? - This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type=”text/html” or “text/xml” or “plain-text” or “image/jpg”, etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn’t finished to set up the header. If not starter to set up the header, there are no problems, but if it ’s already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case it’s like you have a file started with <HTML Tag><Some Headers><Body>some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1
  8. How do I use a scriptlet to initialize a newly instantiated bean? - A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
    The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
    <jsp:useBean id="foo" class="com.Bar.Foo" >
    <jsp:setProperty name="foo" property="today"
    value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >
    <%-- scriptlets calling bean setter methods go here --%>
    </jsp:useBean >
    
  9. How can I enable session tracking for JSP pages if the browser has disabled cookies? - We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
     hello1.jsp
     <%@ page session="true" %>
     <%
     Integer num = new Integer(100);
     session.putValue("num",num);
     String url =response.encodeURL("hello2.jsp");
     %>
     <a href='<%=url%>'>hello2.jsp</a>
    
     hello2.jsp
     <%@ page session="true" %>
     <%
     Integer i= (Integer )session.getValue("num");
     out.println("Num value in session is "+i.intValue());
    
  10. How can I declare methods within my JSP page? - You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example:
     <%!
     public String whereFrom(HttpServletRequest req) {
     HttpSession ses = req.getSession();
     ...
     return req.getRemoteHost();
     }
     %>
     <%
     out.print("Hi there, I see that you are coming in from ");
     %>
     <%= whereFrom(request) %>
     Another Example
     file1.jsp:
     <%@page contentType="text/html"%>
     <%!
     public void test(JspWriter writer) throws IOException{
     writer.println("Hello!");
     }
     %>
    
     file2.jsp
     <%@include file="file1.jsp"%>
     <html>
     <body>
     <%test(out);% >
     </body>
     </html>
    
  11. Is there a way I can set the inactivity lease period on a per-session basis? - Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example:
     <%
     session.setMaxInactiveInterval(300);
     %>
    
    would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.
  12. How can I set a cookie and delete a cookie from within a JSP page? - A cookie, mycookie, can be deleted using the following scriptlet:
     <%
     //creating a cookie
     Cookie mycookie = new Cookie("aName","aValue");
     response.addCookie(mycookie);
     //delete a cookie
     Cookie killMyCookie = new Cookie("mycookie", null);
     killMyCookie.setMaxAge(0);
     killMyCookie.setPath("/");
     response.addCookie(killMyCookie);
     %>
    
  13. How does a servlet communicate with a JSP page? - The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
     public void doPost (HttpServletRequest request, HttpServletResponse response) {
     try {
      govi.FormBean f = new govi.FormBean();
      String id = request.getParameter("id");
      f.setName(request.getParameter("name"));
      f.setAddr(request.getParameter("addr"));
      f.setAge(request.getParameter("age"));
      //use the id to compute
      //additional bean properties like info
      //maybe perform a db query, etc.
      // . . .
      f.setPersonalizationInfo(info);
      request.setAttribute("fBean",f);
      getServletConfig().getServletContext().getRequestDispatcher
                          ("/jsp/Bean1.jsp").forward(request, response);
      } catch (Exception ex) {
     . . .
        }
     }
    
    The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.
    jsp:useBean id="fBean" class="govi.FormBean" scope="request"
    / jsp:getProperty name="fBean" property="name"
    / jsp:getProperty name="fBean" property="addr"
    / jsp:getProperty name="fBean" property="age"
    / jsp:getProperty name="fBean" property="personalizationInfo" /
    
  14. How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default? - One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:
    Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
    • The service() method has to invoke the _jspService() method
    • The init() method has to invoke the jspInit() method
    • The destroy() method has to invoke jspDestroy()
    If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
    Once the superclass has been developed, you can have your JSP extend it as follows:
     <%@ page extends="packageName.ServletName" %>
    
  15. How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values? - You could make a simple wrapper function, like
     <%!
     String blanknull(String s) {
     return (s == null) ? "" : s;
     }
     %>
     then use it inside your JSP form, like
     <input type="text" name="shoesize" value="<%=blanknull(shoesize)% >" >
    
  16. How can I get to print the stacktrace for an exception occuring within my JSP page? - By printing out the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:
     <%@ page isErrorPage="true" %>
     <%
     out.println(" ");
      PrintWriter pw = response.getWriter();
      exception.printStackTrace(pw);
     out.println(" ");
     %>
    
  17. How do you pass an InitParameter to a JSP? - The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
     <%@ page import="java.util.*" %>
     <%!
     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);
     }
     }
     %>
    
  18. How can my JSP page communicate with an EJB Session Bean? - The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:
     <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
     <%!
     //declare a "global" reference to an instance of the home interface of the session bean
     AccountHome accHome=null;
     public void jspInit() {
     //obtain an instance of the home interface
     InitialContext cntxt = new InitialContext( );
     Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
     accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
     }
     %>
     <%
     //instantiate the session bean
     Account acct = accHome.create();
     //invoke the remote methods
     acct.doWhatever(...);
     // etc etc...
     %>
    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Jsp Interview Questions-->2

    26. How can I declare methods within my JSP page?
    We can declare methods by using JSP declarative tag.   <%!  public int add(inti,intj){  return i+j;  %>
    27. What is the difference b/w variable declared inside a declaration  and variable declared in scriplet ?              Variable declared inside declaration part is treated as a instance variable and will be placed directly at class level in the generated servlet.
    <%!  int  k = 10;  %>
    Variable declared in a scriptlet will be placed inside _jspService() method of generated servlet.It acts as local variable.
    <%    int k = 10;
    %>
    28.What are the three  kinds of comments in JSP and what's the difference between them?
    Three types of comments are allowed in JSP
    1.     JSP Comment:
    <%--  this is jsp comment  --%>
    This is also known as hidden comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible.
    1.     HTML Comment:
    <!--  this is HTMl comment -- >
    This is also known as template text comment or output comment. It is visible in all phases of JSP including source code of generated response.
    1.     Java Comments.
    With in the script lets we can use even java comments .
    <%  // single line java comment /* this is multiline comment  */
    %>
    This type of comments also known as scripting comments and these are visible in the generated servlet also.
    29. What is  output comment? 
    The comment which is visible in the source of the response is called output comment.
       <!--  this is HTMl comment -- >
    30. What is a Hidden Comment?       <%--  this is jsp comment  --%>
    This is also known as JSP comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible.
    31. How is scripting disabled?
    Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows:
    <jsp-property-group>    <url-pattern>*.jsp</url-pattern>    <scripting-invalid>true</scripting-invalid> </jsp-property-group>
    32.  What are the JSP implicit objects?
    Implicit objects are by default available to the JSP. Being JSP author we can use these and not required to create it explicitly.
    1.     request
    2.     response
    3.     pageContext
    4.     session
    5.     application
    6.     out
    7.     config
    8.     page
    9.     exception
    33. How does JSP handle run-time exceptions?
    You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.
    For example:  <%@ page errorPage="error.jsp" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.
    Within error.jsp, if you indicate that it is an error-processing page, via the directive:
    <%@ page isErrorPage="true" %>
    In the error pages we can access exception implicit object.              
    34. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
    You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive in the JSP.
    <%@ page isThreadSafe="false" %>
    The generated servlet can handle only one client request at time so that we can make JSP as thread safe. We can overcome data inconsistency problems by this approach.
    The main limitation is it may affect the performance of the system. 
    35.  What is the difference between ServletContext and PageContext?
    ServletContext: Gives the information about the container and it represents an application. PageContext: Gives the information about the Request and it can provide all other implicit JSP objects .
    36 . Is there a way to reference the "this" variable within a JSP page?  Yes, there is. The page implicit object is equivalent to "this", and returns a reference to the generated servlet.
    37 . Can you make use of a ServletOutputStream object from within a JSP page?  Yes . By using getOutputStream() method on response implicit object we can get it.
    38 .What is the page directive is used to prevent a JSP page from automatically creating a session?  session object is by default available to the JSP. We can make it unavailable by using page directive as follows. <%@ page session="false"> 
    39. What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
    Synchronized keyword is recommended to use to get thread-safety.
    40.  What are various attributes Of Page Directive ?
    Page directive contains the following 13 attributes.
    1.     language
    2.     extends
    3.     import
    4.     session
    5.     isThreadSafe
    6.     info
    7.     errorPage
    8.     isError page
    9.     contentType
    10.  isELIgnored
    11.  buffer
    12.  autoFlush
    13.  pageEncoding
    41 . Explain about autoflush? This command is used to autoflush the contents. If a value of true is used it indicates to flush the buffer whenever it is full. In case of false it indicates that an exception should be thrown whenever the buffer is full. If you are trying to access the page at the time of conversion of a JSP into servlet will result in error.
    42.  How do you restrict page errors display in the JSP page?  You first set "errorPage" attribute of PAGE directive  to the name of the error page (ie errorPage="error.jsp")in your jsp page . Then in the error.jsp page set "isErrorpage=TRUE".  When an error occur in your jsp page, then the control will be automatically forward to error page.
    43. What are the different scopes available fos JSPs ?
    There are four types of scopes are allowed in the JSP.
    1.     page - with in the same page
    2.     request - after forward or include also you will get the request scope data.
    3.    session - after senRedirect also you will get the session scope data. All data stored in session is available to end user till session closed or browser closed.
    4.    application - Data will be available throughout the application. One user can store data in application scope and other can get the data from application scope.
    44. when do use application scope?
    If we want to make our data available to the entire application then we have to use application scope.
    45.  What are the different scope valiues for the <jsp:useBean>?               
    The different scope values for <jsp:useBean> are
     1. page   2. request   3.session   4.application
    46. How do I use a scriptlet to initialize a newly instantiated bean?     
    jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
    The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
    <jsp:useBean id="foo" class="com.Bar.Foo" >
    <jsp:setProperty name="foo" property="x"  value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >
    <%-- scriptlets calling bean setter methods go here --%>
    </jsp:useBean >
    47 . Can a JSP page instantiate a serialized bean? No problem! The use Bean action specifies the beanName attribute, which can be used for indicating a serialized bean.  For example: 
    A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INF/jspbeans directory for it to be located by the JSP engine.
    48.How do we include static files within a jsp page ?
    We can include static files in JSP by using include directive (static include)
    <%@ include file=”header.jsp” %>
           The content of the header.jsp will be included in the current jsp at translation time. Hence this inclusion is also known as static include.
    49.In JSPs how many ways are possible to perform inclusion?
    In JSP, we can perform inclusion in the following ways.        
      1.     By include directive:
         <%@ include file=”header.jsp” %>
           The content of the header.jsp will be included in the current jsp at translation time. Hence this inclusion is also known as static include.
    1.     By include action:
      <jsp:include page=”header.jsp” />
    The response of the jsp will be included in the current page response at request processing time(run time) hence it is also known as dynamic include.
    1.     by using pageContext implicit object
    <%        pageContext.include(“/header.jsp”);
    %>
    This inclusion also happened at request processing time(run time).
    1.     by using RequestDispatcher object
     <%  RequestDispatcher rd = request.getRequestDispatcher(“/header.jsp”);   Rd.incliude(request,response);
    %>
    50.In which situation we can use static include and dynamic include in JSPs ?
    If the target resource ( included resource) won’t change frequently, then it is recommended to use static include.    <%@ include file=”header.jsp” %>
    If the target resource(Included page)  will change frequently , then it is recommended to use dynamic include.
     < jsp:include page=”header.jsp” />
    51. What is a Expression?
    JSP Expression can be used to print expression to the JSP.
    Syntax:    <%=  java expression %> Eg:       <%=  new java.util.Date()  %>
     The expression in expression tag should not ends with semi-colon    The expression value will become argument to the out.pritln() method in the generated servlet
    
    
    What is a JSP and what is it used for? Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. 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.
    What is difference between custom JSP tags and beans?  Custom JSP tag is a tag you defined. 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. To use custom JSP tags, you need to define three separate components: 1. the tag handler class that defines the tag\'s behavior 2. the tag library descriptor file that maps the XML element names to the tag implementations  3. the JSP file that uses the tag library  When the first two components are done, you can use the tag by using taglib directive:  <%@ taglib uri="xxx.tld" prefix="..." %> Then you are ready to use the tags you defined. Let's say the tag prefix is test:  MyJSPTag or  JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class.  <%=identifier.getclassField() %> Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences: Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans.  Custom tags usually define 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, but beans can be used in all JSP 1.x versions.
    What are the two kinds of comments in JSP and what's the difference between them ? <%-- JSP Comment --%> <!-- HTML Comment -->
    What is JSP technology?
    Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.
    What is JSP page?  A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.
    What are the 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
    How many JSP scripting elements and what are they?  There are three scripting language elements: --declarations  --scriptlets  --expressions
    Why are JSP pages the preferred API for creating a web-based client program?  Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.
    Is JSP technology extensible?  YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
    Can we use the constructor, instead of init(), to initialize servlet?  Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
    How can a servlet refresh automatically if some new data has entered the database?  You can use a client-side Refresh or Server Push.
    The code in a finally clause will never fail to execute, right? Using System.exit(1); in try block will not allow finally code to execute.
    How many messaging models do JMS provide for and what are they?  JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.
    What information is needed to create a TCP Socket?  The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number.
    What Class.forName will do while loading drivers?  It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
    How to Retrieve Warnings?  SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object  SQLWarning warning = stmt.getWarnings(); if (warning != null) { while (warning != null) { System.out.println(\"Message: \" + warning.getMessage()); System.out.println(\"SQLState: \" + warning.getSQLState()); System.out.print(\"Vendor error code: \"); System.out.println(warning.getErrorCode()); warning = warning.getNextWarning(); } }
    How many JSP scripting elements are there and what are they?  There are three scripting language elements: declarations, scriptlets, expressions.
    In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?
    Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.
    What are stored procedures? How is it useful?  A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements every time a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.
    How do I include static files within a JSP page?  Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.
    Why does JComponent have add() and remove() methods but Component does not?  because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.
    How do I prevent the output of my JSP or Servlet pages from being cached by the browser?  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.
    How do you restrict page errors display in the JSP page?  You first set "Errorpage" attribute of PAGE directory to the name of the error page (ie Errorpage="error.jsp")in your jsp page .Then in the error jsp page set "isErrorpage=TRUE". When an error occur in your jsp page it will automatically call the error page.
    How can I enable session tracking for JSP pages if the browser has disabled cookies? We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair.  However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.  Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other.  Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages.  Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.  hello1.jsp  hello2.jsp  hello2.jsp  <% Integer i= (Integer )session.getValue("num"); out.println("Num value in session is "+i.intValue());
    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:
    How do I perform browser redirection from a JSP page?  You can use the response implicit object to redirect the browser to a different resource, as: response.sendRedirect("http://www.exforsys.com/path/error.html"); You can also physically alter the Location HTTP header attribute, as shown below: You can also use the:  Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well. If you want to pass any paramateres then you can pass using >
    How does JSP handle run-time exceptions?  You can use the errorPage attribute of the page directive to have uncaught runtime exceptions automatically forwarded to an error processing page. For example: redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive:  the Throwable object describing the exception may be accessed within the error page via the exception implicit object.  Note: You must always use a relative URL as the value for the errorPage attribute.
    How do I use comments within a JSP page?  You can use "JSP-style" comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client.  For example:  --%>  You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:  Of course, you can also use comments supported by your JSP scripting language within your scriptlets.
    Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?  You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable. This has to be consider as "passed-by-value", that means that it's read-only in the EJB.  If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.The "pass-byreference" can be used between EJBs Remote Interfaces, as they are remote references.  While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be "bad practice" in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end.  Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it.
    How can I implement a thread-safe JSP page?  You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page. 
    How can I declare methods within my JSP page? You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions.  Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare.  For example:  Another Example:  file1.jsp:  file2.jsp  <%test(out);% >
    Can I stop JSP execution while in the midst of processing a request?  Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (assuming Java is your scripting language) is to use the return statement when you want to terminate further processing.
    Can a JSP page process HTML FORM data?  Yes. However, unlike Servlet, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as.
    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.
    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
    Is there a way I can set the inactivity lease period on a per-session basis?  Typically, a default inactivity lease period for all sessions is set within your JSPengine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis.  This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created.
    How does a servlet communicate with a JSP page?  The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.  public void doPost (HttpServletRequest request, HttpServletResponse response) { try { govi.FormBean f = new govi.FormBean(); String id = request.getParameter("id"); f.setName(request.getParameter("name")); f.setAddr(request.getParameter("addr")); f.setAge(request.getParameter("age")); //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . . f.setPersonalizationInfo(info); request.setAttribute("fBean",f); getServletConfig().getServletContext().getRequestDispatcher ("/jsp/Bean1.jsp").forward(request, response); } catch (Exception ex) { . . . } } The JSP page Bean1.jsp can then process fBean, a fter first extracting it from the default request  scope via the useBean action. jsp:useBean id="fBean" class="govi.FormBean" scope="request"/ jsp:getProperty name="fBean" property="name" / jsp:getProperty name="fBean" property="addr" / jsp:getProperty name="fBean" property="age" / jsp:getProperty name="fBean" property="personalizationInfo" /
    Can you make use of a ServletOutputStream object from within a JSP page?  No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients.  A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not.  A page author can always disable the default buffering for any page using a page directive as: 
    How do I include static files within a JSP page? Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase.  The following example shows the syntax:  < % @ include file="copyright.html" % >  Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.  How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default? One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSPengine.  In any case, your new super class has to fulfill the contract with the JSP engine by: Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final.  Additionally, your servlet super class also needs to do the following:  The service() method has to invoke the _jspService() method The init() method has to invoke the jspInit() method The destroy() method has to invoke jspDestroy() If any of the above conditions are not satisfied, the JSP engine may throw a translation error. Once the super class has been developed, you can have your JSP extend it as follows:
    Can a JSP page instantiate a serialized bean? No problem! The use Bean action specifies the beanName attribute, which can be used for indicating a serialized bean.  For example:  A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INFjspbeans directory for it to be located by the JSP engine.
    What is JSP?  Let's consider the answer to that from two different perspectives: that of an HTML designer and that of a Java programmer.  If you are an HTML designer, you can look at JSP technology as extending HTML to provide you with the ability to seamlessly embed snippets of Java code within your HTML pages. These bits of Java code generate dynamic content, which is embedded within the other HTML/XML content you author. Even better, JSP technology provides the means by which programmers can create new HTML/XML tags and JavaBeans components, which provide new features for HTML designers without those designers needing to learn how to program.  Note: A common misconception is that Java code embedded in a JSP page is transmitted with the HTML and executed by the user agent (such as a browser). This is not the case. A JSP page is translated into a Java servlet and executed on the server. JSP statements embedded in the JSP page become part of the servlet generated from the JSP page. The resulting servlet is executed on the server. It is never visible to the user agent.  If you are a Java programmer, you can look at JSP technology as a new, higher-level means to writing servlets. Instead of directly writing servlet classes and then emitting HTML from your servlets, you write HTML pages with Java code embedded in them. The JSP environment takes your page and dynamically compiles it. Whenever a user agent requests that page from the Web server, the servlet that was generated from your JSP code is executed, and the results are returned to the user.
    How do I mix JSP and SSI #include?  Answer 1 If you're just including raw HTML, use the #include directive as usual inside your .jsp file.  But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your data.inc file contains jsp code you will have to use  The is used for including non-JSP files.  Answer 2  If you're just including raw HTML, use the #include directive as usual inside your .jsp file. <!--#include file="data.inc"--> But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. Ronel Sumibcay (ronel@LIVESOFTWARE.COM) says: If your data.inc file contains jsp code you will have to use <%@ vinclude="data.inc" %> The <!--#include file="data.inc"--> is used for including non-JSP files.
    How do I mix JSP and SSI #include? What is the difference between include directive & jsp:include action?  Difference between include directive and 1. provides the benefits of automatic recompliation,smaller class size ,since the code corresponding to the included page is not present in the servlet for every included jsp page and option of specifying the additional request parameter. 2.The also supports the use of request time attributes values for dynamically specifying included page which directive does not. 3.the include directive can only incorporate contents from a static document. 4. can be used to include dynamically generated output e.g.. from servlets. 5.include directive offers the option of sharing local variables, better run time efficiency. 6.Because the include directive is processed during translation and compilation, it does not impose any restrictions on output buffering.
    How do you prevent the Creation of a Session in a JSP Page and why? What is the difference between include directive & jsp:include action?  By default, a JSP page will automatically create a session for the request if one does not exist.  However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions. 
    How do I use a scriptlet to initialize a newly instantiated bean? A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.  The following example shows the "today" property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.  value=""/ >
    How can I set a cookie and delete a cookie from within a JSP page?  A cookie, mycookie, can be deleted using the following scriptlet:
    How do you connect to the database from JSP?  A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets.  Further then you can use the resultset object "res" to read data in the following way. 
    What is the page directive is used to prevent a JSP page from automatically creating a session?  <%@ page session="false">
    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);
    Can we implement an interface in a JSP?  No
    What is the difference between ServletContext and PageContext?  ServletContext: Gives the information about the container PageContext: Gives the information about the Request
    What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?  request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.
    How to pass information from JSP to included JSP?  Using <%jsp:param> tag.
    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.
    Can we override the jspInit(), _jspService() and jspDestroy() methods?  We can override jspinit() and jspDestroy() methods but not _jspService().
    Why is _jspService() method starting with an '_' while other life cycle methods do not?  _jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page.
    What happens when a page is statically included in another JSP page?  An include directive tells the JSP engine to include the contents of another file (HTML, JSP, etc.) in the current page. This process of including a file is also called as static include.
    A JSP page, include.jsp, has a instance variable "int a", now this page is statically included in another JSP page, index.jsp, which has a instance variable "int a" declared. What happens when the index.jsp page is requested by the client?  Compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error. 
    Can you override jspInit() method? If yes, In which cases? ye, 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.
    What is the difference between directive include and jsp include? <%@ include> : Used to include static resources during translation time. : Used to include dynamic content or static content during runtime.
    What is the difference between RequestDispatcher and sendRedirect?  RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.
    How does JSP handle runtime exceptions?  Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.
    How can my application get to know when a HttpSession is removed?  Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.  
    What Class.forName will do while loading drivers?  It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
    How to Retrieve Warnings?  SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object  SQLWarning warning = stmt.getWarnings(); if (warning != null) { while (warning != null) { System.out.println(\"Message: \" + warning.getMessage()); System.out.println(\"SQLState: \" + warning.getSQLState()); System.out.print(\"Vendor error code: \"); System.out.println(warning.getErrorCode()); warning = warning.getNextWarning(); } }
    How many JSP scripting elements are there and what are they?  There are three scripting language elements: declarations, scriptlets, expressions.
    In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?  Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.
    Is JSP technology extensible?  YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
    Can we use the constructor, instead of init(), to initialize servlet?  Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.
    How can a servlet refresh automatically if some new data has entered the database?  You can use a client-side Refresh or Server Push.
    The code in a finally clause will never fail to execute, right?  Using System.exit(1); in try block will not allow finally code to execute.
    How many messaging models do JMS provide for and what are they?  JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

No comments:

Post a Comment