JSP Interview Questions With Answers


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()



Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email