Sunday, September 13, 2009

JSP Interview questions

JSP Interview questions

Q1) What is a JSP? What is it used for? What do you understand by the term JSP translation phase or compilation phase?

Ans) JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println(“….. ”) statements, where out is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.

The JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file into a JSP Servlet. The translated and compiled JSP Servlet moves to the execution phase (run time) where they can handle requests and send response.

Unless explicitly compiled ahead of time, JSP files are compiled the first time they are accessed. On large production sites, or in situations involving complicated JSP files, compilation may cause unacceptable delays to users first accessing the JSP page. The JSPs can be compiled ahead of time (ie precompiled) using application server tools/settings or by writing your own script.

Q2) 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.

Q3) What are the standard actions available in JSP?

Ans) The standard actions available in JSP are as follows:
: 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.
: It forwards a response from a servlet or a JSP page to another page.
: It makes a JavaBean available to a page and instantiates the bean.
: It sets the properties for a JavaBean.
: It gets the value of a property from a JavaBean component and adds it to the response.
: It is used in conjunction with ;, ; to add a parameter to a request. These parameters are provided using the name-value pairs.
: It is used to include a Java applet or a JavaBean in the current JSP page.

Q5) What are the differences between static and a dynamic include?

Ans)
Static <%@include%>

Dynamic include

During the translation or compilation phase all the included JSP pages are compiled into a single Servlet.

The dynamically included JSP is compiled into a separate Servlet. It is a separate resource, which gets to process the request, and the content generated by this resource is included in the JSP response.

No run time performance overhead.

Has run time performance overhead.

Q6) 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 %>;
Q7) Explain JSP URL mapping? What is URL hiding or protecting the JSP page?

Ans) The JSP resources usually reside directly or under subdirectories (e.g. myPath) of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files, css (cascading style sheets) files, Java Script files, pdf files, image files, html files etc from direct access. The request should be made to a servlet who is responsible for authenticating and authorising the user before returning the protected JSP page or its resources.
Q8) 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:


tag1
myTagPkg.MyTag
empty

attr
false
false





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-INF/MyTagURI
/WEB-INF/tags/MyTagDesc.tld




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” />


tag1
myTagPkg.MyTag
empty

attr
false
false



Q9) 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:



<%=identifier.getclassField() %>
Q10) What is a Expression?

A: 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.
Q11) Difference between forward and sendRedirect?

Ans) 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.
Q12) What are implicit objects? List them?

Ans) Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are listed below:
request
response
pageContext
session
application
out
config
page
exception
Q13) How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

Ans) 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
%>
Q14) How to implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?

Ans) JSPs can be 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 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 .
Q15) Why to use the HttpServlet Init method to perform expensive operations that need only be done once?

Ans) Because the servlet init() method is invoked when servlet instance is loaded, it is the perfect location to carry out expensive operations that need only be performed during initialization. By definition, the init() method is thread-safe. The results of operations in the HttpServlet.init() method can be cached safely in servlet instance variables, which become read-only in the servlet service method.

Q16) 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"%>

No comments:

Post a Comment

Happy Reading!

Ganex Improves .. Headline Animator