JSP Interview Questions



Q) What is the difference between ServletContext and PageContext?
A)
ServletContext: Gives the information about the container
PageContext: Gives the information about the Request

Q) What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
A)
request.getRequestDispatcher(path): In order to create it we need to give the relative path of   the  resource.
context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

Q) How to pass information from JSP to included JSP?
A)
Using <%jsp:param> tag.

Q) What is the difference between directive include and jsp include?
A)
<%@ include> : Used to include static resources during translation time.
: Used to include dynamic content or static content during runtime.

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

Q) How does JSP handle runtime exceptions?
A)
Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

Q) How do you delete a Cookie within a JSP?
A)
Cookie mycook = new Cookie(“name”,”value”);
response.addCookie(mycook);

Cookie killmycook = new Cookie(“mycook”,”value”);
killmycook.setMaxAge(0);
killmycook.setPath(“/”);
killmycook.addCookie(killmycook);

Q) How do I mix JSP and SSI #include?
A)
If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.            <!–#include file=”data.inc”–>
But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the included file. Ronel Sumibcay (ronel@LIVESOFTWARE.COM) says:
If your data.inc  file contains jsp code you will have to use
<%@ vinclude=”data.inc” %>
The <!–#include file=”data.inc”–>  is used for including non-JSP files.

Q) What is the difference between Model 1 and Model 2 architecture?
A)
In Model 1 there is no Controller and in Model 2 there is a Controller.

Q) How can my application get to know when a HttpSession is removed?
A)
Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.
Create an instance of that class and put that instance in HttpSession.

Q) How can I implement a thread-safe JSP page?
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.

Q) How many JSP scripting elements are there and what are they?
A)
There are three scripting language elements:
declarations
scriptlets
expressions

Q) In the Servlet 2.4 specification SingleThreadModel has been deprecates, why?
A)
Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

Q) How do I include static files within a JSP page?
A)
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax: Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

Q) How do I mix JSP and SSI #include?
A)
If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.
<!–#include file=”data.inc”–>
But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the included file. If your data.inc file contains jsp code you will have to use
<%@ vinclude=”data.inc” %>
The <!–#include file=”data.inc”–> is used for including non-JSP files.

Q) Can a JSP page process HTML FORM data?
A)
Yes. However, unlike servlets, 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 as:
<%
String item = request.getParameter(“item”);
int howMany = new Integer(request.getParameter(“units”)).intValue();
%>
or
<%= request.getParameter(“item”) %>

Q) What JSP lifecycle methods can I override?
A)
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(). 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() {
. . .
}
%>

Q) How do I include static files within a JSP page?
A)
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax:

<%@ include file=”copyright.html” %>

Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

Q) How do I perform browser redirection from a JSP page?
A)
You can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect(“http://www.foo.com/path/error.html”);
You can also physically alter the Location HTTP header attribute, as shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = “/newpath/index.html”;
response.setHeader(“Location”,newLocn);
%>
You can also use the:
<jsp:forward page=”/newpage.jsp” /> Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well.
If you want to pass any paramateres then you can pass using <jsp:forward page=”/servlet/login”> <jsp:param name=”username” value=”jsmith” /> </jsp:forward>>

Q) Can a JSP page instantiate a serialized bean?
A) No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:

<jsp:useBean id=”shop” type=”shopping.CD” beanName=”CD” />
<jsp:getProperty name=”shop” property=”album” />

A couple of important points to note. Although you would have to name your serialized file “filename.ser”, you only indicate “filename” as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine.

Q) Can you make use of a ServletOutputStream object from within a JSP page?
A)
No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not. A page author can always disable the default buffering for any page using a page directive as:
<%@ page buffer=”none” %>

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) Can I stop JSP execution while in the midst of processing a request?
A)
Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (asuming Java is your scripting language) is to use the return statement when you want to terminate further processing. For example, consider:

<% if (request.getParameter(“foo”) != null)
{
// generate some html or update bean property
}
else {

/* output some error message or provide redirection back to the input form after creating a memento bean updated with the ‘valid’ form elements that were input. this bean can now be used by the previous form to initialize the input elements that were valid then, return from the body of the _jspService() method to terminate further processing */

return;
}

Q) How can I get to view any compilation/parsing errors at the client while developing JSP pages?
A)
With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:
jsp.initparams=sendErrToClient=true
This will cause any compilation/parsing errors to be sent as part of the response to the client.

Q) Is there a way to reference the “this” variable within a JSP page?
A) Yes, there is. Under JSP 1.0, the page implicit object is equivalent to “this”, and returns a reference to the servlet generated by the JSP page.

Q) How do I instantiate a bean whose constructor accepts parameters using the useBean tag?
A)
Consider the following bean: package bar;
public class FooBean
{
public FooBean(SomeObj arg)
{

}
//getters and setters here
}
The only way you can instantiate this bean within your JSP page is to use a scriptlet. For example, the following snippet creates the bean with session scope:

&l;% SomeObj x = new SomeObj(…);
bar.FooBean foobar = new FooBean(x);
session.putValue(“foobar”,foobar);
%>
You can now access this bean within any other page that is part of the same session as:

&l;%
bar.FooBean foobar = session.getValue(“foobar”);
%>
To give the bean “application scope”, you will have to place it within the ServletContext as:
&l;%
application.setAttribute(“foobar”,foobar);
%>
To give the bean “request scope”, you will have to place it within the request object as:
&l;%
request.setAttribute(“foobar”,foobar);
%>

If you do not place the bean within the request, session or application scope, the bean can be accessed only within the current JSP page (page scope).
Once the bean is instantiated, it can be accessed in the usual way:
jsp:getProperty name=”foobar” property=”someProperty”/ jsp:setProperty name=”foobar” property=”someProperty” value=”someValue”/

Random Posts

  • Define Stateless Session
  • Software  Architecture of EJB
  • How To Delete the textbox using the Javascript
  • Java lang package interview questions
  • Difference between session.save() and session.saveOrUpdate()

Post a Comment