Saturday, August 3, 2013

51 JSP Interview Questions

          JSP Interview Questions

1. What are the advantages of JSP over Servlet?
Ans. JSP is a server side technology to make content generation simple . The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript.

2. What is the life-cycle of JSP?
Ans. 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

3. What is the jspInit() method?
Ans. The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.

4.What is the _jspService() method?
Ans. The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.

5.What is the jspDestroy() method?
Ans. The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.

6. What JSP lifecycle methods can I override?
Ans. 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().

7. How can I override the jspInit() and jspDestroy() methods within a JSP page?
Ans. 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() {
                               . . .          
               }
%>

8. What are implicit objects in JSP?
Ans. Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects.The implicit objects available in JSP are as follows:
  • request
  • response
  • pageContext
  • session
  • application
  • out
  • config
  • page
  • exception
The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.

9. What are the different types of JSP tags?
Ans. The different types of JSP tags are as follows:
10. What are JSP directives?
Ans. 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.
Ex: page directive, include directive, etc.

11. What is page directive?
Ans. A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
Typically, the page directive is found at the top of almost all of our JSP pages.
There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
The syntax of the include directive is: <%@ page attribute="value">
Example:<%@ include file="header.jsp" %>

12. What are the attributes of page directive?
Ans. There are thirteen attributes defined for a page directive of which the important attributes are as follows:
  • import: It specifies the packages that are to be imported.
  • session: It specifies whether a session data is available to the JSP page.
  • contentType: It allows a user to set the content-type for a page.
  • isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.

13. What is the include directive?
Ans.  The include directive is used to statically insert the contents of a resource into the current JSP.
This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
The syntax of the include directive is as follows:
<%@ include file = "FileName" %>
This directive has only one attribute called file that specifies the name of the file to be included.

14. What are the JSP standard actions?
Ans. The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
Ex: include, forward, useBean,etc. object

15. What are the standard actions available in JSP?
Ans. The standard actions available in JSP are as follows:
<jsp:include>: It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.

16. What is the <jsp:useBean> standard action?
Ans. The <jsp:useBean> standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type.

17. What are the scopes available in <jsp:useBean>?
Ans. The scopes available in <jsp:useBean> are as follows:
page scope:: It specifies that the object will be available for the entire JSP page but not outside the page.
request scope: It specifies that the object will be associated with a particular request and exist as long as the request exists.
application scope: It specifies that the object will be available throughout the entire Web application but not outside the application.
session scope: It specifies that the object will be available throughout the session with a particular client.

18. What is the <jsp:forward> standard action?
Ans. The <jsp:forward> standard action forwards a response from a servlet or a JSP page to another page.
The execution of the current page is stopped and control is transferred to the forwarded page.
The syntax of the <jsp:forward> standard action is : 
<jsp:forward page="/targetPage" />

Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context.
If anything is written to the output stream that is not buffered before <jsp:forward>, an IllegalStateException will be thrown.
Note : Whenever we intend to use <jsp:forward> or <jsp:include> in a page, buffering should be enabled. By default buffer is enabled.

19.What is the <jsp:include> standard action?
Ans. The <jsp:include> standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context. The syntax of the <jsp:include> standard action is as follows:
<jsp:include page="targetPage" flush="true"/>
Here, targetPage is the page to be included in the current JSP.

20.What is the difference between include directive and include action?
Include directive
Include action
The include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet.
The include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user.
The include directive is used to statically insert the contents of a resource into the current JSP.
The include standard action enables the current JSP page to include a static or a dynamic resource at runtime.
Use the include directive if the file changes rarely. It’s the fastest mechanism.
Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.

21. What is Expression, Declaration, Scriptlet in jsp?

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

                        <%= emp.getName()%>
          <%= (new java.util.Date()).toLocaleString() %>

You cannot use a semicolon to end an expression.
All the expression code is converting to servlet. All the expressions go inside service() method of the converted servlet.

Declaration Tag :
A declaration declares one or more variables or methods for use  in the JSP source file. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.

<%! int i = 0; %>
<%! int a, b, c; %>

You can add method to declaration part.
<%!
public String trimData(String str){
return str.trim();
}
%>

You can call the method within the jsp.

All the declaration code is converting to servlet. If you add method, the method is in converted servlet. All variables are instance variable in the converted servlet.

Scriptlet Tag :
Scriptlet code is like java logic. you can declare variables in the scriptlet and do the logic.
All the Scriptlet go to inside service() method of the converted servlet.

<%
int n=10;
for(int i=0;i<n;i++){
} %>

 

22. How do I prevent the browser from caching my dynamic content?

Ans. add the code to your jsp.
<% response.setHeader( "Cache-Control", "no-cache" );
response.setHeader( "Pragma", "no-cache" );
response.setIntHeader( "Expires", 0 ); %>

 

23. How do I include static files within a JSP page?

Ans. <%@ include file="header.jsp"%>
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase.

 

24. How do I perform browser redirection from a JSP page?

Ans. 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");

 

25. How does JSP handle run-time exceptions?

Ans. 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:    isErrorPage=true. 

the Throwable object describing the exception may be accessed within the error page via the exception implicit object. And use <%= exception.toString() %>
 In isErrorPage containing jsp file to get the error.

 

26. How can I implement a thread-safe JSP page?

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

 

27. What's the Difference between Forward and Include?

Ans. The <jsp:forward> action enables you to forward the request to a static HTML file, a servlet, or another JSP.

<jsp:forward page="url" />

The JSP that contains the <jsp:forward> action stops processing, clears its buffer, and forwards the request to the target resource. Note that the calling JSP should not write anything to the response prior to the <jsp:forward> action.

You can also pass additional parameters to the target resource using the <jsp:param> tag.

<jsp:forward page="test.htm" >
<jsp:param name="name1" value="value1" />
<jsp:param name="name2" value="value2" />
</jsp:forward>

In this example, test.jsp can access the value of name1 using request.getParameter("name1").

<jsp:include execute the code and force a flush of the buffer in the output stream.
If a.jsp has the code like
<jsp:include page="template.jsp" flush="true" >
<jsp:param name="name1" value="value1" />
</jsp:include>

then template.jsp execute and the output is placed in a.jsp

 

28. In which situation you use static include and dynamic include in jsp?

Ans. static include : Contents are static like
<%@ include file="header.jsp"%> ..Not changing frequently. Don't need to pass parameter.

For example.
a.jsp contain <%@ include file="header.jsp"%>
then all the codes of header.jsp is included in a.jsp.

dynamic include : Need to pass parameter. Need to execute every time.
Dynamic content. Excecute the included jsp and only ouput is pasted to main jsp.

For example..
a.jsp contain following code
<jsp:include page="masterTemplate.jsp" flush="true">
<jsp:param name="rColumn" value="rightDisplay.jsp" />
<jsp:param name="mColumn" value="AlertBody.jsp" />
<jsp:param name="title" value="Alerts" />
</jsp:include>

masterTemplate.jsp execute and output is pasted to a.jsp.

 

29. How do you prevent the Creation of a Session in a JSP Page and why?

Ans. <%@ page session="false">
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.

 

30. How do you delete a Cookie within a JSP?

Ans. cookie.setMaxAge(0);

 

31. How to Protect JSPs from direct access?

Ans. JSPs located in the WEB-INF and its sub-directories are protected from outside access.

32. What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
Ans. Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
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 - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

33. What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
Ans. Variable declared inside declaration part is treated as a global variable. that means after conversion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable and the scope is available to complete jsp and to complete converted servlet class, where as if u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.

34. What is the difference between RequestDispatcher and sendRedirect?
Ans. RequestDispatcher: server-side redirect with request and response objects. sendRedirect: Client-side redirect with new request and response objects.

35. Why is _jspService() method starting with an '_' while other life cycle methods do not?
Ans. _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

36. 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?
Ans. 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.

37. Can a JSP page process HTML FORM data?
Ans. 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.

38. Is there a way I can set the inactivity lease period on a per-session basis?
Ans. 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.

39. What is wrong with using JSP scriptlet tags ?
Ans. Java code embedded within scriptlet tags is ugly and obtrusive.
A non-Java developer cannot modify the embedded Java code, nullifying a major benefit of JSP: empowerment of designers and business people to update page content.
Other JSP pages cannot reuse Java code within JSP scriptlet, so common logic snippets end up being re-implemented in multiple pages.
Retrieving objects out of the HTTP request and session is cumbersome. Casting to the object’s class is required. This then requires that the object’s class be known to the JSP by importing or fully qualifying the class name

40. What does the JSP engine do when presented with a JavaServer Page to process?
Ans: The JSP engine builds a servlet. The HTML portions of the JavaServer Page become Strings transmitted to print methods of a PrintWriter object. The JSP tag portions result in calls to methods of the appropriate JavaBean class whose output is translated into more calls to a println method to place the result in the HTML document

41. Explain the life cycle methods of a JSP?
Ans. Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance.
Servicing: Services the client requests. Container calls this method for each request.
Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.

42. Is JSP variable declaration thread safe?
Ans. No.
 The declaration of variables in JSP is not thread-safe, because the declared variables end up in the generated Servlet as an instance variable, not within the body of the _jspservice() method.
The following declaration is not thread safe: because these are declarations, and will only be evaluated once when the page is loaded
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside the scriplets have the local scope and not shared.
<% int a = 5 %>;

43. What are custom tags? Explain how to build custom tags?
Ans. Custom JSP tag is a tag you define. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. So basically it is a reusable and extensible JSP only solution. The pre-built tags also can speed up Web development.
Step 1 : Create a Custom tag class using only doStartTag()
 package myTagPkg;
  public class MyTag extends TagSupport
   {
            int attr = null;
            public int setAttr(int a ttr) {
            this.attr = a ttr
            }
             public int getAttr(){
                        return attr;}
   
    public int doStartTag() throws JspException {
                         .......
                        return 0;
    }
    
    public void release(){.....}
   }

Step 2: The Tag library descriptor file (*.tld) maps the XML element names to the tag implementations. The code sample MyTagDesc.tld is shown below:
<taglib>
  <tag>
   <name>tag1</name>
   <tagclass>myTagPkg.MyTag</tagclass>
   <bodycontent>empty</bodycontent>
   <attribute>
    <name>attr</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
   </attribute>
  </tag>
</taglib>

Step 3 : The web.xml deployment descriptor maps the URI to the location of the *.tld (Tag Library Descriptor) file. The code sample web.xml file is shown below:
 <web-app>
  <taglib>
   <taglib-uri>/WEB-INF/MyTagURI</taglib-uri>
   <taglib-location>/WEB-INF/tags/MyTagDesc.tld</taglib-location>
  </taglib>
 </web-app>

Step 4 : The JSP file declares and then uses the tag library as shown below:

<%@ taglib uri="/WEB-INF/ MyTagURI" prefix="myTag" %>
< myTag:tag1 attr=”abc” />
<taglib>
  <tag>
   <name>tag1</name>
   <tagclass>myTagPkg.MyTag</tagclass>
   <bodycontent>empty</bodycontent>
   <attribute>
    <name>attr</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
   </attribute>
  </tag>
</taglib>

44. What is the difference between custom JSP tags and JavaBeans?
Ans. In the context of a JSP page, both accomplish similar goals but the differences are:
Custom Tags
JavaBeans
Can manipulate JSP content.
Can't manipulate JSP content.
Custom tags can simplify the complex operations much better than the bean can. But require a bit more work to set up.
Easier to set up.
Used only in JSPs in a relatively self-contained manner.
Can be used in both Servlets and JSPs. You can define a bean in one Servlet and use them in another Servlet or a JSP page.

JavaBeans declaration and usage example:
<jsp:useBean id="identifier" class="packageName.className"/>
<jsp:setProperty name="identifier" property="classField" value="someValue" />
<jsp:getProperty name="identifier" property="classField" />
<%=identifier.getclassField() %>

45. Why is it not a good practice to create HttpSessions in JSPs by default?
Ans) By default, JSP files create HttpSessions. This is in compliance with J2EETM to facilitate the use of JSP implicit objects, which can be referenced in JSP source and tags without explicit declaration. HttpSession is one of those objects. If you do not use HttpSession in your JSP files then you can save some performance overhead with the following JSP page directive:

<%@ page session="false"%>

46. What are the standard actions available in JSP?
Ans) The standard actions available in JSP are as follows:
<jsp:include>: It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.

47. Difference Between include Directive and include Action of JSP
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 response object to calling jsp to included file or JSP or vice versa
In this case it’s possible.

48. 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 , though its not advisable to write java code in jsp instead its better to use expression language and tag library.

49. 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.
                                
50. 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"/>

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

2 comments:

Hema Malini said...

Really nice post. Feeling proud about your sincere hard work. Thanks for sharing and keep updating.
bootstrap interview questions
spring interview questions and answers for experienced
spring interview questions
jsp interview questions

easylearn said...

Thank you so much for the post.The content is very useful.I always love your posts because of the information and knowledge one can gain by reading your post.Thanks for sharing and keep updating still more.
Best Python Training in BTM Layout