Java Reference
In-Depth Information
Although the generated code is not very impressive, the variables and methods inherited from
TagSupport
will
make this class function as a tag. However, at least one inherited method has to overridden and coded to perform the
needed application functions.
The Tag Handler
As mentioned, CrtEmpBean inherits many methods from
TagSupport
. We will focus on the
doStartTag
and
doEndTag
methods that are inherited from
TagSupport
. It was stated earlier that when the tag is encountered in the
JSP, the server runs the associated tag handler class. Specifically, when the start tag is encountered, the server runs the
doStartTag method and when the end tag is encountered, the doEndTag method is run.
In the example, we want the doStartTag method to:
A.
Run EmpExtractor's getEmployeeInstance to create an Employee object from the request
B.
Define the returned Employee object as a bean with a scope of request
Several things will be needed to do this. First, private variables of type Employee and EmpExtractor are
required. Second, the
HttpServletRequest
class needs to be imported into CrtEmpBean. This is required because
getEmployeeInstance is expecting an
HttpServletRequest
, but the request object is of type
ServletRequest
.
So, the
ServletRequest
object must be cast as an
HttpServletRequest
. Finally, we will be using the ever-helpful
PageContext
object (provided by the server) to get the request and define the Employee object as a request bean
(or, said another way, define the Employee object as an attribute of the request).
The code to get the request object is:
pageContext.getRequest()
Because the returned request must be cast into an
HttpServletRequest
, this statement should be preceded with
the following to cast the request:
(HttpServletRequest)
This results in:
(HttpServletRequest)pageContext.getRequest()
Then the
HttpServletRequest
needs to be passed to EmpExtractor. Do this by embedding the above statement
in the method call as follows (where ee is the EmpExtractor variable):
ee.getEmployeeInstance(
(HttpServletRequest)pageContext.getRequest());
To define the returned Employee object as a request bean, we need to get the request again (using the page
context's getRequest method again). Then use the request's setAttribute method to define the employee object as a
bean called EmpBean. The statement to do that is as follows (where emp is the Employee variable):
pageContext.getRequest().setAttribute("EmpBean", emp);