JSP Standard Questions



Q) Can I invoke a JSP error page from a servlet?
A)
Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets. If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained
The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:
protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e) throws ServletException, IOException
{
request.setAttribute (“javax.servlet.jsp.jspException”, e);
getServletConfig().getServletContext(). getRequestDispatcher(errorPageURL).forward(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try {
// do something
} catch (Exception ex)
{
try {
sendErrorRedirect(request,response,”/jsp/MyErrorPage.jsp”,ex);
} catch (Exception e)
{
e.printStackTrace();
}          }      }

Q) How can you store international / Unicode characters into a cookie?
A)
One way is, before storing the cookie URLEncode it.
URLEnocder.encoder(str);
And use URLDecoder.decode(str) when you get the stored cookie.

Q) What are the implicit objects?
A)
Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:
request
response
pageContext
session
application
out
config
page
exception

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



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

the Throwable object describing the exception may be accessed within the error page via the exception implicit object.

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 a servlet communicate with a JSP page?
A)
The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
public void doPost (HttpServletRequest request, HttpServletResponse response)
{
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter(“id”);
f.setName(request.getParameter(“name”));
f.setAddr(request.getParameter(“addr”));
f.setAge(request.getParameter(“age”));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute(“fBean”,f);
getServletConfig().getServletContext().getRequestDispatcher
(“/jsp/Bean1.jsp”).forward(request, response);
}
catch (Exception ex)
{
. . .
}
}
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.
jsp:useBean id=”fBean” class=”govi.FormBean” scope=”request”/ jsp:getProperty name=”fBean” property=”name” / jsp:getProperty name=”fBean” property=”addr” / jsp:getProperty name=”fBean” property=”age” / jsp:getProperty name=”fBean” property=”personalizationInfo” /

Q) How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?
A)
One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
<%@ page extends=”packageName.ServletName” %>

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=”shoesize” value=”<%=blanknull(shoesize)% >” >

Q) How do you prevent the Creation of a Session in a JSP Page and why?
A)
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.

The page directive is used to prevent a JSP page from automatically creating a session:
<%@ page session=”false”>

Random Posts

  • STRUTS Interview Questions
  • Difference between session.save() and session.saveOrUpdate()
  • Jsp Scriplets and Templets
  • Collection FrameWork
  • Why does EJB needs two interfaces

Post a Comment