Interview Q&A Of JSP

1.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.

2.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.

3.What are the life-cycle methods of JSP?
Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
b)_jspService(): The container calls the jspservice() for each request and it passes the request and the response objects. jspService() method cann't be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.

4.What is the life-cycle of JSP?
When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests.
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:
 Translation
 Compilation
 Loading the class
 Instantiating the class
 jspInit() invocation
 jspService() invocation
 jspDestroy() invocation

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

6.How can I override the jspInit() and jspDestroy() methods within a JSP page?
 The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:
     <%!
         public void jspInit()
        {
             . . .
         }
     %>
     <%!    
         public void jspDestroy()
        {
             . . .   
         }
     %>

7 What is JSP declaration?
JSP Decleratives are the JSP tag used to declare variables. Declaratives are enclosed in the <%! %> tag and ends in semi-colon. You declare variables and functions in the declaration tag and can use anywhere in the JSP. Here is the example of declaratives:
<%@page contentType="text/html" %>
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
</body>
</html>

8.What is JSP Scriptlet?
JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.
Example:
  <%
  //java codes
   String userName=null;
   userName=request.getParameter("userName");
   %>

9.What is a 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. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression

10.What are JSP directives?
 JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page
 They are used to set global values such as a class declaration, method implementation, output content type, etc.
 They do not produce any output to the client.
 Directives are always enclosed within <%@ ….. %> tag.

 1) page directive
    Syntax
    <%@ page attribute="value" %>    
    The attribute are:
    1.1.import
        This attribute use to import the java classes or packages.
    eg.<%@ page import="java.util.*";%>

    1.2.Content-Type
        This attribute use to set types of content display by browser.
        eg.<%@ page Content-Type=image/jpg";%>

    1.3.session
       This attribute use for enable or disable session on page either true or false,default true.
    eg.<%@ page session="true";%>
    
    1.4.buffer
        This attribute ued for set size of buffer.
        eg.<%@ page buffer="none";%>

    1.5.autoFlush
        You can sed either true or false.
        eg.<%@ page autoFlush="true";%>
  
    1.6.errorPage
    This attributes use when any error occurs its redirect to error page.
        eg. <%@ page errorPage="error.jsp";%>

 2)include directive
   A file on a local System will be included with this directive when the  jsp page translated into servlet.this directive used to phisically includes the content of another file.This included file can be html file or jsp file.
   eg.
    <%@include file="hello.jsp"%>

11.What are implicit Objects available to the JSP Page?
Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:
request           :This is the HttpServletRequest object associated with the request.
response         :This is the HttpServletResponse object associated with the response to the client.
out                 :This is the PrintWriter object used to send output to the client.
session           :This is the HttpSession object associated with the request.
application     :This is the ServletContext object associated with application context.
config            :This is the ServletConfig object associated with the page.
pageContext : This encapsulates use of server-specific features like higher performance JspWriters.
page              :This is simply a synonym for this, and is used to call the methods defined by the   translated servlet class.
Exception      :The Exception object allows the exception data to be accessed by designated JSP.


12.What are all the different scope values for the <jsp:useBean> tag?
<jsp:useBean> tag is used to use any java object in the jsp page. Here are the scope values for <jsp:useBean> tag:
a) page
b) request
c) session and
d) application

13.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.

14.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
 %>

15.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.

16.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 is that we are store function in other jsp file and we are calling.

    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>


17.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.

18.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);
    %>

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


20.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(" ");
    %>

21.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.

22.Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

23.What is a output comment?
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
<!--comment[<%=expression%>]-->

Example 1
<!--This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->

Displays in the page source:
<!-- This is a commnet sent to client on January 24, 2004 -->

24.What is a Hidden Comment?
A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.

JSP Syntax
<%-- comment --%>

Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>

25.Difference between forward and sendRedirect?
When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

26.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

27.Question: What do you understand by JSP Actions?
Answer: JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters
There are six JSP Actions:
<jsp:include/>
<jsp:forward/>
<jsp:plugin/>
<jsp:usebean/>
<jsp:setProperty/>
<jsp:getProperty/> 

28.What is the difference between <jsp:include page = ... > and <%@ include file = ... >?.
Both the tag includes the information from one page in another. The differences are as follows:
<jsp:include page = ... >: This is like a function call from one jsp to another jsp. It is executed ( the included page is executed  and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful to for modularizing the web application. If the included file changed then the new content will be included in the output.

<%@ include file = ... >: In this case the content of the included file is textually embedded in the page that have <%@ include file=".."> directive. In this case in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.

29What is the difference between <jsp:forward page = ... > and response.sendRedirect(url),?.
Answer: The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The  response.sendRedirect kills the session variables.

30.what is Difference between Scriptlet and Declaration
Declaration :- Used for declaring variables and methods.

example : <%!  int num =0;  %>

During translation and compilation phase of JSP life cycle all variables declared in jsp declaration become instance variables of servlet class and all methods become instance methods. Since instance variables are automatically initialized, all variables declared in jsp declaration section gets their default values.

Scriptlet:- Used for embedding java code fragments in JSP page.

example : <%  num++; %>

During translation phase of JSP Life cycle all scriptlet become part of _jspService() method. So we cannot declare methods in scriptlet since we cannot have methods inside other methods. As the variables declared inside scriptlet will get translated to local variables they must be initialized before use.

31)how to declare method in jsp with return type and void type and how to used out object in side the user defined method?

1)Method which is return String type.
<%!
public String show()
{
    return "welcome to jsp";   
}
%>

<%
  out.println(show());
%>

Here in jsp declaration tag. i declared one method which return string message. and i call this method in scriplet tag and it will display following  output.
output:welcome to jsp

2)Method which is void type and how to used out object in method
<%!
public void show1(javax.servlet.jsp.JspWriter out)throws Exception
{
    out.println("welcome to jsp");
   
}
%>
<%
   show1(out);
%>

Here in jsp declaration tag. i declared method show1(javax.servlet.jsp.JspWriter out) and i used out implicit object.the out object is not accessible in the  user defined method so if you want to access that out object   then you have to pass out object when you invoking this method and for catching the out object we need to catch by its class name  'javax.servlet.jsp.JspWriter' so now we can used out object in our method and when we used out object object we also need to handle exception.

32)Difference between forward and sendRedirect?
forward
This transfer of control is done by the container internally and browser / client is not involved. This
is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

redirect
Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.

For example, sendRedirect can transfer control from http://poolofjava.blogspot.in to http://anydomain.com but forward cannot do this.

‘session’ is not lost in both forward and redirect.

To feel the difference between forward and sendRedirect visually see the address bar of your browser,
in forward, you will not see the forwarded address (since the browser is not involved)
in redirect, you can see the redirected address.

Technical scenario: redirect should be used

    If you need to transfer control to different domain
    To achieve separation of task.

For example, database update and data display can be separated by redirect. Do the PaymentProcess and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PyamenProcess will not be repeated. But if you use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other than the above two scenarios, forward is efficient to use since it is faster than sendRedirect.



   







   
       




    



2 comments:

  1. Big data service providers should understand the need of Data, and they should work to build more appropriate services to meet the requirements of their clients.

    ReplyDelete