Thursday, March 20, 2008

Interview Questions on JSP

What is the difference between Java Servlets and Java ServerPages (JSP)?

A JSP is a Servlet with a Web page flavor.There are more similarities than differences between the two.JSP uses its own tags which are ultimately using tag libraries implemented in Java.
The source code of a servlet with HTML embedded in out. print (...) statements, gives dynamic features to webpages but that makes a cumbersome process to maintain servelts from web design perspective.If someone has implemented GUI related code inside servlet then each time a small GUI change will result in recompilation of the whole code.Hence business logic centric development should be done inside servlet and JSP gives a choice of combining both in much targeted way.JSP was devised to differentiate the tasks of web designers,responsible for look and feel of the webpages, from web developers who deal in business logic development.So both entities have focused interest met through JSP.In fact, a JSP gets compiled into a servlet.

What is the difference between ' include file = ' and 'jsp:include page = ...'

<@ include file = ...>: The content of included file is textually embedded in the page that has <@ include file=".."> directive.It occurs at compile time. If included file changes, the changed content will not be included in the output. This approach is used in template creations where code from one jsp file is included in multiple jsp files.
<jsp:include page="..">: It is like a function call from one jsp to another jsp. The inclusion of one jsp content to another happens at execution time. This approach is handy for web application modularization.If included file changes then the new contents will be included in the output.

What is the difference between 'jsp:forward' and HttpResponse.sendRedirect()?

jsp:forward is processed at the server end for forwarding a client request to a specified URL while HttpResponse.sendRedirect() method is used at the client end for request redirection.

What are implicit objects in JSP?


The objects which are created by web container and are available in a JSP page for various information extractions from there objects.The different implicit objects in JSPs are(click on image to enlarge):

Explain different constituents of JSP like comments,expressions,declarations,scriptlets.


JSP Comments:
The JSP supports two type of comments :-
-Output
-Hidden
JSP Output Comments are those ones which can be viewed on the HTML file, while Hidden Comments are never shown.

JSP Expressions:
The JSP expression tag is inserts Java values directly into the output. The syntax of the Expression tag is:
<%= expression %>

This kind of tag contains is evaluated, converted to a String, and inserted where the expression appears in the JSP file.

JSP Declarations:
JSP declarations are used to declare variables.To add a declaration, the <%! and %> sequences is used to enclose declarations,and ends in semi-colon. These variables can be used within functions and expressions.It is not a good practice to declare variables in global space as such variable are shared by multiple threads and which may change it's values in an inconsistent manner.To avoid such a scenario one must make these variables as synchronized but then it hampers the performance of the JSP .Usually variables are declared within local scope of Java scriptlets.

JSP Scriptlets:
JSP allows to write block of Java code within scriptlet tags which are <% some Java code goes here %>.It does not contribute anything to HTML page and Java code is evaluated each time when JSP loads.

Here is an example which shows use of JSP Comments,Expression,Declaration and Scriptlet:
[jspfun.PNG]

Explain the life-cycle methods of JSP


JSP has following three life cycle methods:

a) jspInit(): It is the very first method which is called by JSP container to initialize the servlet instance.All JSPs implement the javax.servlet.jsp.JspPage interface that has two methods: jspInit and jspDestroy. It is important to implement when one has to load some database driver for example.

b)_jspService(): The JSP container calls the _jspservice() for each request and it passes the request and the response objects.The _jspService() method corresponds to the body of the JSP page. This method is defined automatically by the JSP container and should never be defined by the JSP page author. That is why _jspService() method can not be overridden.


c) jspDestroy(): When an instance of JSP is going to be destroyed then JSP container calls this method .It is used for cleaning up Both jspInit() and jspDestroy() methods can be overridden within a JSP page.This method helps in reclaiming resources like network and database connections when a JSP instance is destroyed and JSP no longer services any client request.

package javax.servlet.jsp;

public interface JspPage extends javax.servlet.Servlet {

public void jspInit();
public void jspDestroy();
public void _jspService(ServletRequestSubtype request,
ServletResponseSubtype response)
throws ServletException, IOException;
// _jspService - depends on the specific protocol used and
// cannot be expressed in a generic way in Java.
}

Does JSP support XML pages creation?



The answer is Yes. There are two ways you could use XML data in a JSP page:
• Convert the XML elements into server-side objects and then extract the object properties.
• Invoke a transformation on the XML data.

The static XML tags may be included as static template portions of the JSP page.The dynamic generation of XML tags occur through bean components or custom tags that generate XML output.The other mechanism of dynamic XML data use in JSP could be by XML transformation.This technique uses XSLT(a W3C standard for transforming an XML to XML/HTML/PDF) which could be used either for formatting data in a desired fashion or simply extracting the data from an XML.

How can I show various kind of documents to a web client from JSP's and/or servlets?

You can show MS Word, Excel or PDF or any other type of document through your JSP or servlet by using :

response.setContentType("mime/type"); and

in jsp directive

<%@ page contentType="mime/type" %>.


In case of MS Word documents contentType is "application/msword"
In case of Excel it is "application/vnd.ms-excel"
In case of PDF it is "application/pdf"

How will you handle runtime exceptions in your JSPs?

JSP runtime exceptions are handled through the implicit object named "exception". This exception object can be used in a special type of JSP page called an error page, where you display the exception's name and class, its stack trace, and an informative message for your user.
In any JSP which is made eligible for catching exceptions then it must have a mention to error page in @page directive,something like:

<%@ page errorPage="ErrorHandling.jsp" %>

The error page, in this case ' ErrorHandling.jsp', has 'isErrorPage' attribute in page directive which should be set to true. When a JSP page has been declared an errorPage, it is made available an object with name of "exception" of type java.lang.Throwable.

How can you prevent caching in JSP?

Execute the following scriptlet at the beginning of your JSP pages to prevent JSPs from being cached by browsers.You need both the statements to take care of some of the older browser versions.

<%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

If the above fails, try changing the first line to

response.setHeader("Cache-Control","no-store"); //HTTP 1.1



Q: What is a output comment?
A: 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 -->


Q: What is a Hidden Comment?
A: 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>


Q: 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


Q: What is a Declaration?
A: A declaration declares one or more variables or methods for use later in the JSP source file.

A declaration must contain at least one complete declarative statement. 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.

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


Q: What is a Scriptlet?
A: A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can

1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also Expression).

3.Use any of the JSP implicit objects or any object declared with a tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.

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.


Q: What are implicit objects? List them?
A: 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 re listed below

* request
* response
* pageContext
* session
* application
* out
* config
* page
* exception


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


Q: What are the different scope valiues for the ?
A: The different scope values for are

1. page
2. request
3.session
4.application


Q: Explain the life-cycle mehtods in JSP?
A: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.


Q: How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
A: 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
%>


Q: How does JSP handle run-time 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\"%> 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.


Q: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
A: 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. 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 .


Q: How do I use a scriptlet to initialize a newly instantiated bean?
A: A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.

The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.

<jsp:usebean id="foo" class="com.Bar.Foo">

<jsp:setProperty name="foo" property="today"
value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date())%>" / >

<%-- scriptlets calling bean setter methods go here --%>

</jsp:useBean >


Q: 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?
A: 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="lastName" value="<%=blanknull(lastName)% >" >

Q: What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
A: 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.


Q: How can I enable session tracking for JSP pages if the browser has disabled cookies?
A: We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.

hello1.jsp
<%@ page session=\"true\"%>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
< a href="\'<%="url%">\' > hello2.jsp</a>

hello2.jsp
<%@ page session="true"%>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is " + i.intValue());
%>

Q: What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
A: Variable declared inside declaration part is treated as a global variable.that means after convertion 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 in the 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.


Q: Is there a way to execute a JSP from the comandline or from my own application?
A: There is a little tool called JSPExecutor that allows you to do just that. The developers (Hendrik Schreiber & Peter Rossbach ) aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no reponseline or header is generated. Nevertheless you can use it to precompile JSP for your website.

No comments:

Books

  • Hibernate in Action
  • Spring in Action