Friday, May 21, 2010

JSP implicit objects

JSP implicit objects
6.5) Given a design goal, write JSP code using the appropriate implicit objects:
(a) request,
(b) response,
(c) out,
(d) session,
(e) config,
(f) application,
(g) page,
( h) pageContext, and
(i) exception.
What are Implicit Objects?When writing Servlets the available objects are fairly obvious as they are the parameters to methods, thus if you are overriding the doPost method you will have a signature of
public void doPost(HttpServletRequest request,
HttpServletResponse response)
When writing JSP pages the implicit objects are created automatically for you within the service method . You just have to know what the implicit objects are, but as most of them match closely to those available in Servlet methods they are not too difficult to memorise. You will have come across one of the implicit objects already with the out object which allows you to send information to the output stream.
Note that the implicit variables are only available within the jspService method and thus are not available within any declarations. Thus for example the following code will cause a compile time error.
<%! public void amethod(){ out.print("Hello"); } %>
The request and response implicit objects The request implicit object is an instance of HttpServletRequest, and response is an instance of HttpServletResponse objects. They are available in a similar way to the request and response object passed to the doGet and doPost methods in servlets.
A typical use for the request is to get the details of HTTP query string such as query names and parameters.
<%= request.getQueryString() %>
Will display the query string after the name of the jsp file itself. Thus if this code is within a file called hello.jsp and is called with the url as follows
http://localhost:8080/chap03/hello.jsp?thisisthequerystring
The output will include thisisthequerystring as part of the page.
The response can be used for the same purposes as the HttpServletResponse in a servlet, such as adding cookies or headers.
The request and response objects are the same as the parameters to doPost and represent instances of HttpServletRequest and HttpServletResponse respectively.
The out implicit object The out implicit object has a type of jsp.JspWriter. The out object can be used in a similar way to System.out is used in plain ordinary Java programs, i.e.
<% out.print("Hello World"); %>
The parameters of out are sent to the output stream, which generally means they end up visible in the browser requesting the JSP page.
sessionThe session implicit object is an instance of
javax.servlet.http.HttpSession
The session concept is a way of allowing multiple requests from the same client to be group together as part of a single “conversation”. This is a way of getting around the basic architectural limitation within HTTP in that it was designed as a stateless protocol, i.e. web servers “forget” about each client as soon as a request has finished execution. The default way of logically linking multiple requests from the same client is by generating a cookie that stores a value unique to the client. After the first request establishes a session, each subsequent request reads that cookie and can thus identify the unique client.
With the session object you do not need the type of code required in a Servlet whereby you have to call the getSession method to access an existing session or start a new one. Typical uses of the session object are for getting and setting attributes. Thus you can add a new attribute to the session with code like the following.
<% session.setAttribute("username","marcusgreen"); %>
config The config implicit object is an instance of
javax.servlet.ServletConfig
And represents the parameters set up within the deployment descriptor. To set up the configuration a servlet is configured within web.xml , but instead of creating a element a element is created containing the name of the JSP page. Parameters are then created using the and tags.
The config object can be used to retrieve parameters using its
getInitParameter(String param)
method.
The config object can be used to retrieve the ServletContext object through its getServletContext method. Thus the following code retrieves information about the currently executing server, and in my own setup it generates the output.
Apache Tomcat/5.5.9
<% ServletContext ct = config.getServletContext(); out.print(ct.getServerInfo()); %>
application The application implicit object is an instance of javax.servlet.ServletContext. It refers to the overall web application environment that the JSP belongs to. According to the API docs
“Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.”
In Apache Tomcat a web application will be contained in an individual directory under the webapps directory. A typical use of the application object is to get access to the application wide initialisation parameters. Because the application and config objects have similar and slightly confusing uses the following code shows how they can be used along with a deployment descriptor (WEB.XML) that sets up the appropriate initialisation parameters for them.
The file index.jsp
<% /*for parameters declared at the application level . *i.e. under the WEB-APP tag of the deployment descriptor */ out.print(application.getInitParameter("myparam")); /*for a specific resource within an application *identified as a servlet in the deployment descriptor */ out.print(config.getInitParameter("myparam2")); %>

The deployment descriptor (WEB.XML)



myparam param1



MyServlet


/index.jsp


myparam2 param2




MyServlet


/index.jsp



The page implicit object The page implicit object is of type Object and it is assigned a reference to the servlet that executing the _jspService() method. Thus in the Servlet generated by tomcat the page object is created as
Object page = this;

Because page is of type Object it is of less direct use than simply accessing the implicit this object. To access any of the methods of the servlet through page it must be first cast to type Servlet. Thus the two following lines of code are equivalent.
<% this.log("log message"); %>
<% ((HttpServlet)page).log("anothermessage"); %>

As you probably will not be using the page object in your own code the main thing to remember for the exam is that it is not the same as the pageContext object and that it is of type Object.
The pageContext implicit object The pageContext object has a type of javax.servlet.jsp.PageContext and according to the API documents
“A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically “http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/PageContext.html
So it can be seen as a convenience object for tasks such as transferring requests to other web resources. Much of its functionality appears to be for the convenience of generating the servlet from the JSP, thus the following example of a servlet generated from the Tomcat container shows how PageContext is used to populate other implicit objects.
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
A typical use of the pageContext is to to include another resource or forward to another resource. Thus the following would forward from the current page to menu.jsp
<% pageContext.forward("menu.jsp"); %>
The exception implicit object The exception implicit object is of type
java.lang.Throwable
This object is only available to pages that have isErrorPage set to true with the directive
<%@ page isErrorPage='true' %>
The exception object refers to the exception triggered by the page that uses this page as an exception handler
The following code demonstrates the use of the exception implicit object. The first page uses the errorPage directive to set up the JSP page to use when an error occurs, and the second page called ErrorPage.jsp uses the isErrorPage directive to set itself up to catch the error.
First page
<%@page errorPage="ErrorPage.jsp" %>
<% int i=10; /*Divide by zero, generates an error */ out.print(i/0); %>

ErrorPage.jsp
<%@ page isErrorPage='true' %>
<% out.print("

Here is the error message

");
out.print(exception.getMessage());
%>
Declarative handling of exceptionsIt is also possible to map HTTP error codes and or Java exception types to an error page in the deployment descriptor. This is done at the web application level by using the tag which is a child of the tag. Thus the following tags would re-direct all SQL exception errors to the /errorpage.jsp page.


java.sql.SQLException


/errorpage.jsp



The following tags would re-direct all HTTP 404 errors to the /errorpage.jsp page

404
/errorPage.jsp

No comments: