JSP Interview Questions and Answers | Realtime Questions and Answers


JSP Interview Questions and Answers | Realtime Questions and Answers

A Complete JSP Interview questions and Answers

Directives 

Page Directive

<%@ Page language="java" extends="className" import="className" session="true|false" buffer="8KB" autoFlush="true/false" isThreadSafe="true/false" info="text" errorPage="jspUrl" isErrorPage="true/false" contentType="mimeType” %>

 

XML syntax: -

<Jsp: directive.page import=” ” />

 

Page directive defines information that will be globally available for that page

Include Directive

<%@ include file="relative URL" %> 

 

XML syntax: -

<Jsp: directive.include file=” ” />

<Jsp: directive.page file=” ” />

 

Include JSP are Servlet at compile time meaning that only once parsed by the compiler, it will act as a “C” "#include" pulling in the text of the included file and compiling it as if it were part of the including file. We can also include “Static” files using this directive.

Taglib Directive

<%@ taglib uri="uriToTagLibrary" prefix="prefixString" %>

 

XML syntax: -

<Jsp: root xmlns:prefix1=”http://..” version=”1.2” />

</Jsp: root>

Taglib directive enables you to create your own custom tags.

 

 Actions

<Jsp: useBean>

<Jsp: useBean id="beanInstanceName" scope="page|request|session|application” class=""/

type="" bean Name=" "</jsp: useBean>

 

UseBean tag is used to associate a java bean with jsp.

<Jsp: setProperty>

 

<Jsp: setProperty name="beanInstanceName” property="*" |"propertyName” param="paramName" value="{string | <%= expression %>}"  />

 

Sets a property value or values in a bean.

 

<Jsp: getProperty>

<Jsp: getProperty name="beanInstanceName" property="propertyName" />

Gets the value of a bean property so that you can display it in a result page.

<Jsp: param>

<Jsp: param name="beanInstanceName" value=" parameterValue " />

It is used to provide other tags with additional information in the form of name, value pairs. This is used to conjunction with jsp:include, jsp:forward, jsp:plugin.

<Jsp: include>

           

 

<Jsp: include page="relativeURL " flush="true" >

        <Jsp: param name="username" value="jsmith" />

</jsp: include>

 

Jsp Include includes the JSP are Servlet at request time, it is not parsed by the compiler, and it Includes a static file or sends a request to a dynamic file.

 

<Jsp: forward>

 

<Jsp: forward page="{relativeURL|<%=expression %>}" >
   <jsp: param name="paramName" value="paramValue"/>
</jsp: forward>

 

When ever the client request will come it will take the request and process the request and the request to be forward to another page and it will also forward the http parameters of the previous page to the destination page. It will work at server side.

<Jsp: plugin>

<Jsp: plugin type="bean/applet" code="classFileName" codebase="classFileDirectoryName" name="instanceName" archive="” align="" height=" " width=" " hspace=" " vspace=" </jsp: plugin>

 

This action is used to generate client browser specific html tags that ensures the java plug in software is available, followed by execution of applet or java bean component specified in tag.

 Implicit Objects

Objects

Type / purpose

Scope

Sum useful methods

Request

Subclass of javax.servlet.http.ServletRequest

 

- Refers to the current request passed to the _jspService() method

Request

- Objects accessible from pages processing the request where they were created.

getAttribute, getParameter, getParameterNames, getParameterValues, setAttribute

Response

Subclass of javax.servlet.http.ServletResponse

 

- Refers to the response sent to the client. It is also passed to the _jspService() method.

Page

Not typically used by JSP page authors

Session

javax.servlet.http.HttpSession

 

- JSP 1.2 specification states that if the session directive is set to false, then using the session keyword results in a fatal translation time error.

Session

- Objects accessible from pages belonging to the same session as the one in which they were created.

getAttribute, getId, setAttribute.

application

javax.servlet.ServletContext

 

- Use it to find information about the servlet engine and the servlet environment.

Application

- Objects accessible from pages belonging to the same application.

getAttribute, getMimeType, getRealPath, setAttribute

Out

javax.servlet.jsp.JspWriter

 

- Refers to the output stream of the JSP page.

Page

clear, clearBuffer, flush, getBufferSize, getRemaining

Config

javax.servlet.ServletConfig

 

- The initialization parameters given in the deployment descriptor can be retrieved from this object.

Page

getInitParameter, getInitParameterNames

page

java.lang.Object.

 

- Refers to the current instance of the servlet generated from the JSP page.

Page

- Objects accessible only within jsp pages where it was created.

Not typically used by JSP page authors

pageContext

 

javax.servlet.jsp.PageContext.

 

- Provides certain convenience methods and stores references to the implicit objects.

Page

findAttribute, getAttribute, getAttributesScope, getAttributeNamesInScope, setAttribute.

exception

java.lang.Throwable.

 

- Available for pages that set the page directive attribute isErrorPage to true. It can be used for exception handling.

Page

getMessage, getLocalizedMessage, printStackTrace, toString

   

 

 

 

Scriptlet

<% Java_code %>

 

XML syntax: -

<Jsp: scriptlet>

   Date today = new Date();

</jsp: scriptlet>

 

A scriptlet can contain variable (or) method declarations (or) expressions. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

Declaration

Ex: <%! int a, b, c; %>

      <%! int accountnumber=23468; %>
      <%! private void processAmount () { ... } %>

 

XML syntax: -

<jsp: declaration>

        int counter=0;

</jsp: Declaration>

A declaration declares one or more variables (or) methods for use later in the JSP source file. This is used for “Global declaration”.

Expressions

Ex: <%= (new java.util.Date()).toLocaleString() %>

 

XML syntax: -

<jsp: expression>

   // -------

</jsp: expression>

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.

Comments

Html comment à Creates a comment that is sent to the client in the viewable page source.

Ex: <! -- <%= expression %> -->

 

Hidden Comment à Documents the JSP file, but is not sent to the client.

Ex: <%-- comment --%>

Comments are removed from the viewable source of your HTML files by using only JSP comment tags. HTML comments remain visible when the user selects view source in the browser.

 

 Q) Diff Explicit Objects & Implicit Objects

 Explicit- Explicit objects are declared and created within the code of your JSP page, accessible to that page and other pages according to the scope setting you choose.

 Explicit objects are typically JavaBean instances declared and created in jsp:useBean action statements. <jsp:useBean id="pageBean" class="mybeans.NameBean" scope="page" />

 Implicit- Implicit objects are created by the underlying JSP mechanism and accessible to Java scriptlets (or) expressions in JSP pages according to the inherent scope setting of the particular object type.

 Q) MVC

Model: - model is a java bean/entity bean that represent the data being transmitted are received

Controller: - Controller is a servlet that performs necessary manipulations to the model.

View: - is a screen representation of the model.

-Major benefits of using the MVC design pattern is separate the view & model this make it is possible to create are change views with out having to change the model.

- 1) The browser makes a request to the controller servlet 2) Servlet performs necessary actions to the java bean model and forward the result to the jsp view. 3) The jsp formats the model for display and send the html results back top the web browser.

 Q) WebApplication scopes?

A) Request, Session, Application.

Request :- Life time is until the response is return to the user

Session :- Until the session timeout (or) session id invalidate.

Application :- Life of container (or) explicitly killed

 Q) Life-cycle of JSP

Page translation

Jsp compilation

Load class

Create Instance

jspInit( ), _jspservice( ), jspDestroy( ) 

 jspInit( )          -container calls the jspInit() to initialize to servlet instance. It is called before any other method, and is called only once for a servlet instance.

_jspservice( ) - container calls _jspservice() for each request, passing it the request and the response objects.

jspDestroy( )  - container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

- Destroy is not called if the container crashes.

- jspInit() & jspDestroy() called only once so we cannot override these methods.

 Q) RequestDispatcher.forward(req, res)

     RequestDispatcher.include(req, res)

     PageContext.forward()

     res.sendRedirect(url)

     <jsp:forward>

             RequestDispatcher.forward(req, res) in forward req, res would be passed to the destination URL and the control will return back to the same method, it will execute at “server side”.

 res.sendRedirect(url) when ever the client request will come just it will take the request and the request to be forwarded to another page. It cannot forward the http parameters of the previous page. This will work at “client side”. If page1.jsp redirects to page2.jsp, the browser's address bar be updated to show page2.jsp.

        PageContext.forward() and RequestDispatcher.forward() are effectively the same. PageContext.forward is a helper method that calls the RequestDispatcher method.

 The difference between the two is that sendRedirect always sends a header back to the client/browser. this header then contains the resource(page/servlet) which you wanted to be redirected. the browser uses this header to make another fresh request. thus sendRedirect has a overhead as to the extra remort trip being incurred. it's like any other Http request being generated by your browser. the advantage is that you can point to any resource(whether on the same domain or some other domain). for eg if sendRedirect was called at www.mydomain.com then it can also be used to redirect a call to a resource on www.theserverside.com.

 In the case of forward() call, the above is not true. resources from the server, where the fwd. call was made, can only be requested for. But the major diff between the two is that forward just routes the request to the new resources which you specify in your forward call. that means this route is made by the servlet engine at the server level only. no headers are sent to the browser which makes this very efficient. also the request and response objects remain the same both from where the forward call was made and the resource which was called.

    RequestDispatcher.include(req, res) RequestDispatcher.include() and <jsp:include> both include content. The included page is inserted into the current page or output stream at the indicated point. It will execute at “server side”.

Jsp: forward> Forwards a client request to an HTML file/JSP file/servlet for processing. When ever the client request will come it will take the request and process the request and the request to be forward to another page, it will also forward the http parameters of the previous page to the destination page. It will execute at “server side” so the browser unaware of the changes. If page1.jsp redirects to page2.jsp, the browser address bar will still show page1.jsp. Forward operations are faster because all processing is done at server side. res.sendRedirect() operations updates the browser history.

Ex -- of RequestDispatcher.forward(req, res)

public class BookStoreServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

// Get the dispatcher; it gets the main page to the user

RequestDispatcher dispatcher = config.getServletContext().getRequestDispatcher("/bookstore.html");

if (dispatcher == null) {

// No dispatcher means the resource (bookstore.html in this case) cannot be found

res.sendError(response.SC_NO_CONTENT);

} else {

// Send the user the bookstore's opening page

dispatcher.forward(request, response);

}

 Q) Diff res.sendRedirect( ) & req.forward( )

             sendRedirect() - sends a redirect response back to the client's browser. The browser will normally interpret this response by initiating a new request to the redirect URL given in the response.

forward() - does not involve the client's browser. It just takes browser's current request, and hands it off to another servlet/jsp to handle. The client doesn't know that they're request is being handled by a different servlet/jsp than they originally called.

For ex, if you want to hide the fact that you're handling the browser request with multiple servlets/jsp, and all of the servlets/jsp are in the same web application, use forward() or include(). If you want the browser to initiate a new request to a different servlet/jsp, or if the servlet/jsp you want to forward to is not in the same web application, use sendRedirect ().

 

Q) Diff <%@ include file="file" %> & <jsp:include page=”abc.jsp” %>

             <%@include file="abc.jsp"%> directive acts like C "#include", pulling in the text of the included file and compiling it as if it were part of the including file. The included file can be any type (including HTML or text). (Or) includes a jsp/servlet at compile time meaning only once parsed by the compiler.

 

<jsp:include page="abc.jsp"> include a jsp/servlet at request time it is not parsed by the compiler.

 

Q) Diff Jsp & Servlet

-Internally when jsp is executed by the server it get converted into the servlet so the way jsp & servlet work is almost similar.

- In jsp we can easily separate the P.L with B.L, but in servlet both are combined.

- One servlet object is communicate with many number of objects, but jsp it is not possible.

 

Q) Can JSP be multi-threaded? How can I implement a thread-safe JSP page?

A) By default the service() method of all the JSP execute in a multithreaded fashion. You can make a page “thread-safe” and have it serve client requests in a single-threaded fashion by setting the page tag’s is Thread Safe attribute to false:         

<%@ page is ThreadSafe=”false” %>

 

Q) How does JSP handle runtime exceptions?

A) 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\" %>.

 Q) How do I prevent the output of my JSP or Servlet pages from being cached by the Web browser? And Proxy server?

A) Web browser caching

    <% response.setHeader("Cache-Control","no-store");
          response.setHeader("Pragma","no-cache");
          response.setDateHeader ("Expires", 0);
     %>

   Proxy server caching

      response.setHeader("Cache-Control","private");

 Q) What's a better approach for enabling thread-safe servlets & JSPs? SingleThreadModel Interface or Synchronization?

A) SingleThreadModel technique is easy to use, and works well for low volume sites. If your users to increase in the future, you may be better off implementing explicit synchronization for your shared data

     Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free.

 Q) Invoking a Servlet from a JSP page? Passing data to a Servlet invoked from a JSP page?

A) Use <jsp:forward page="/relativepath/YourServlet" />

(or)

            response.sendRedirect("http://path/YourServlet").

 Variables also can be sent as:

<jsp:forward page=/relativepath/YourServlet>

     <jsp:param name="name1" value="value1" />

     <jsp:param name="name2" value="value2" />

</jsp:forward>

You may also pass parameters to your servlet by specifying     response.sendRedirect("http://path/YourServlet?param1=val1").

 Q) JSP- to-EJB Session Bean communication?

<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>

<%!

     AccountHome accHome=null;

     public void jspInit() {

     InitialContext cntxt = new InitialContext( );

     Object ref= cntxt.lookup("java: comp/env/ejb/AccountEJB");

     accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);

   }

%>

<%

     Account acct = accHome.create();

     acct.doWhatever(...);

 %>

 Q) How do you pass an InitParameter to a JSP?

<%!

ServletConfig cfg =null;

            public void jspInit(){

                        ServletConfig  cfg=getServletConfig();

           for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();)

 {

                        String name=(String)e.nextElement();

           String value = cfg.getInitParameter(name);

                        System.out.println(name+"="+value);

            }

           }

%>

 Q) How
to view an image stored on database with JSP?

<%@ page language="java" import="java.sql.*,java.util.*"%>

<%

          String image_id = (String) request.getParameter("ID");

          if (image_id != null){

          try

          {

            Class.forName("interbase.interclient.Driver");

Connection con = DriverManager.getConnection("jdbc:interbase://localhost/D:/examp/Database/employee.gdb","java","java");

            Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM IMMAGINE WHERE IMMAGINE_ID = " + image_id);

            if (rs.next())

            {

                        String dim_image = rs.getString("IMMAGINE_DIMENSIONE");

                        byte [] blocco = rs.getBytes("IMMAGINE_IMMAGINE");

                        response.setContentType("image/jpeg");

                        ServletOutputStream op = response.getOutputStream();

                        for(int i=0;i<Integer.parseInt(dim_image);i++)

                        {

                                    op.write(blocco[i]);

                        }

               }

               rs.close();

               stmt.close();

               con.close();

             } catch(Exception e) {

                        out.println("An error occurs : " + e.toString());                                         

         }                         

            }

%>

 Q) How do I pass values
from a list box (with multiple selects) to a Java Bean?

Consider the following HTML, which basically allows the user to select multiple values by means of a checkbox:

 What's your favorite movie?

<form method=post action=Movies.jsp>

<input type=checkbox name=faveMovies   value="2001: A Space Odyssey"> 2001: A Space Odyssey

<input type=checkbox name=faveMovies   value="The Waterboy"> The Waterboy

<input type=checkbox name=faveMovies   value="The Tin Drum">  The Tin Drum

<input type=checkbox name=faveMovies   value="Being John">  Being John Malkovich

<input type=submit>

</form>

To handle HTML elements like checkboxes and lists which can be used to select multiple values, you need to use a bean with indexed properties (arrays). The following bean can be used to store the data selected from the above check box, since it contains an indexed property movies:

 package foo;

public class MovieBean {

    private String[] movies;

    public MovieBean() {

     String movies[] = new String[0];

    }

    public String[] getMovies() {

       return movies;

    }

    public void setMovies(String[] m) {

     this.movies = m;

    }  

}

 Although a good design pattern would be to have the names of the bean properties match those of the HTML input form elements, it need not always be the case, as indicated within this example. The JSP code to process the posted form data is as follows:

 <html> <body>

<%! String[] movies; %>

<jsp:useBean id="movieBean" class="foo.MovieBean">

  <jsp:setProperty name="movieBean" property="movies" param="faveMovies" />

</jsp:useBean>

<% movies = movieBean.getMovies();

   if (movies != null) {

      out.println("You selected: <br>");

      out.println("<ul>");

      for (int i = 0; i < movies.length; i++) {

        out.println ("<li>"+movies[i]+"</li>");

      }

      out.println("</ul>");

    } else

      out.println ("Don't you watch any movies?!");

%>

</body></html>

 Q) Tag Libraries

These all methods are callback methods.

Tag methods: doStartTag()                   
                      doEndTag()
Body Tag     : doAfterBody()