6317 Chapter 2 Creating Web Applications
6317 Chapter 2 Creating Web Applications
6317 Chapter 2 Creating Web Applications
A servlet is a Java class that extends the functionality of web server dynamically. Web applications use servlets to create a request-response
programming model. JBoss supports the Java Servlet 2.3 specification.
Methods in a Servlet
A servlet class defines an init method, one or more service methods, and a destroy method. The Web container invokes the init method to
initialize a servlet so that the servlet can process a request. You can write code in the init() method to read server configuration data or initialize
resources, such as database connections. The init method is called only once in entire lifecycle of a servlet.
The service method of a GenericServlet class defines the request processing logic. An HttpServlet, in addition to a service method, can define
methods, such as doGet(), doPost(), doPut(), doDelete(), doTrace(), and doOptions(), to process request information.
A Web server creates a single instance of a servlet and uses this instance to manage multiple requests to the servlet. To manage multiple
requests, multiple threads of the instance are created. Multithreaded servlet processing enhances performance and conserves the Web
container resources. Figure 2-1 shows how a servlet object is used to invoke the init(), service(), doGet(), and destroy() methods:
Page 2 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
Service methods extract information from the request, use the services of the Web server to process the information, and generate a
response. A request object is defined as class that implements the ServletRequest interface, and encapsulates request data. The methods of
a request object access the following request data:
n Parameters that pass information between Web clients and servlets.
n Attributes specified as key value pairs that pass information between the Web container and a servlet, or between servlets that work
together.
n Information about the protocol, localization of the request, and the client and server involved in the request.
For example, a servlet receives request parameters when the end user submits a form. A request can contain global variables, such as
database connection information, that are reused by multiple servlets in an application. Global variables are specified as key value pairs.
Information about the protocol, identity of the client, and the URL of the Web server processing the request are sent as request headers to the
servlet. Listing 2-1 shows the code for a sample servlet class that generates a form:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TestServlet extends HttpServlet
{
PrintWriter pw;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
{
pw=res.getWriter();
res.setContentType("text/html");
pw.println("<body text=blue>");
pw.println("<h1 align=center>Hello World </h1><br><br>");
pw.println("This is a test servlet deployed in JBOSS server");
}
public void destroy()
{
}
}
The above servlet class defines a simple servlet class containing the init(), doGet(), and destroy() methods. The init() method initializes a
Servlet Config object that passes Web server configuration information to the servlet instance. The doGet() method processes the request
object and sends a simple message in the response. You can implement code in the destroy() method to remove any run-time variables or
objects from memory.
Servlet Lifecycle
The Web container in which a servlet is deployed controls the lifecycle of the servlet. When a client request is mapped to a specific servlet, the
container performs the following tasks:
1. Checks for an instance of the servlet, and uses this instance to generate a response. If the instance is not available, the servlet class is
loaded, and a servlet instance is created.
2. Initializes the servlet instance by invoking the init method.
3. Invokes the service() method, and assigns the request and response objects as parameters to this method.
You can parse the contents in a request object to retrieve variables, such as a request URL, HTTP headers, and a query string. The servlet
generates a response that is an instance of a ServletResponse implementation class.
A response object encapsulates HTTP headers, and body of the response. The HTTP headers are written to a response and contain
information, such as destination, content type, the protocol used, and the size of the response. In addition, response headers can contain
status codes that indicate success information or reasons for failure to process the request, and cookies that store application specific
information in the client. The servlet sends the response headers and writes the body of the response to an output stream.
When a servlet needs to be removed from service, or the application is undeployed, or the server is being shut down, the Web server invokes
the destroy method of the Servlet interface. Before invoking the destroy() method, the Web server ensures that all service methods are
processed.
Page 3 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
The servlet API defines a ServletContext interface that encapsulates the context within which Web components execute. A servlet uses the
ServletContext to log events, obtain URLs to resources, or assign attributes used by other servlets executing in the same context. You can
retrieve the context using the getServletContext() method of the ServletContext interface. The ServletContext object enables access to:
n Servlet initialization parameters
n Logging capabilities
n Client state information
Servlet Sessions
When a client sends requests to the Web server, the application associates the series of client requests to a client-server conversation, known
as a session. The application saves the session information, and reuses this information for multiple requests. Servlets use the HttpServlet
class to implement and manage sessions.
To access a session, invoke the getSession() method of the request object. Name value pairs called session variables are associated with
each session. Web components share the session variables that belong to the same ServletContext.
Every session has an associated timeout period after which the resources held by the session, such as variables or shared objects, are
reclaimed by the server. The timeout period is also used to invalidate the session if the client does not continue the conversation. In such a
case, the Web container removes the session variables from memory when a session times out.
A Web server associates a session with a client using an identifier called sessionID during interactions. The application maintains the
sessionID as a cookie that is passed to the Web server with each client request.
The JSP specification implements a servlet-based technology. This specification reduces complexity in applications that use external
resources, such as Java beans or databases. The specification also enables customizing the look and feel of the user interface. You can add
a new type of client without affecting the business logic, or conversely, change the business logic without modifying the user interface.
JSP pages are text-based documents that execute as servlets but create dynamic content, such as HTML, WML, or XML, using predefined
tags called JSP elements. You can place static content in a JSP page or use JSP elements to generate a dynamic content for the response.
The dynamic and static content constitute the response sent to the browser.
The elements that specify information to the Web container that processes the JSP page are:
n Directives: Provide global information to enable sessions, identify error pages, or specify Java import statements, include static contents.
n Expressions: Contain elements that are formatted as strings and included in the page output.
n Actions: Specify elements that perform a function abstracted from the page.
The syntax of a directive is element <%@ directive { attribute="value"} %>. The directive may have multiple attributes. The directives used in
JSP pages are:
n Page: Contains information on the scripting language used, and the Java packages that need to be imported for that page. For example,
to specify a page directive to import the java.util package provide a page directive as:
<%@page import="java.util.* %>
n Include: Specifies the static file to be included. To include the output of a HTML page with the current JSP page, define an include directive
as:
<%@include="first.html" %>
n Taglib: Specifies the URI (Uniform Resource Identifier) for a library of user-defined tags. To specify that the JSP page uses customized
tags defined in a tag library, you need to provide a taglib directive as:
<%@taglib uri="/MyTagLib" %>
In the above directive, /MyTagLib is the path of the custom tag library.
Scriptlets are blocks of Java code between the <% and %> tags. For example, Listing 2-2 shows the scriptlet that prints multiples of the
Page 4 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
numeral, 10:
<%
for (int i = 0; i < 5; i++)
{
c = i+10;
%>
<%= c %>
<%
}
%>
The scriptlet in Listing 2-2 defines a loop to perform an arithmetic operation, and print the resultant value of a variable using a JSP expression.
A JSP page contains declaratives at the top of the page to declare global variables. Access to these global variables is translated to Java
code by the jspService method of the page implementation class. For example, to declare a global string variable, str, the syntax is:
<%! String str=null%>
A JSP page contains an expression to include formatted output in the response. For example the expression <%= str %> displays the value of
the variable, str.
In addition to these elements, the JSP specification provides implicit objects that are used with scriptlets. These implicit objects are request,
response, page context, session, application, out, Exception, and config.
Listing 2-3 shows the code for a sample JSP page using JSP elements, such as page directive and expressions. These elements are used to
generate a form:
Page 5 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
<td><input name="country"></td>
</tr>
<tr>
<td>ZipCode</td>
<td><input name="zip"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register"></td>
</tr>
</form>
</table>
</div>
</body>
</html>
The JSP page in Listing 2-3 generates a form to register an end user for an online book application. This page contains a page directive to
import the java.util package to add the current date to the form. This form uses the page directive to import the java.util package. The
expression in this form is used to display the system date in the form.
A Web server requires a JSP container to process JSP pages. The JSP container intercepts requests and processes all elements of a JSP
page to create a page implementation class, which is a compiled servlet.
The page implementation servlet holds a reference to a JSPPage or HttpJSPPage class, which represents the interface to the compiled JSP
page. The HttpJSPPage class defines the jspInit(), jspDestroy(), and jspService() methods. You can define the jspInit() and jspDestroy()
methods in the JSP page, but the jspService() method is created by the JSP container.
You can process requests to the JSP page by invoking methods of the page implementation servlet. When you modify the JSP page, the JSP
container runs the translation process to regenerate the page implementation servlet.
The Web server handles a JSP page like a servlet. The page implementation class of the JSP is loaded once and called repeatedly, until
server is shut down. A JSP page inherits all the advantages of a servlet, such as platform and vendor independence, integration, efficiency,
scalability, robustness, and security.
JSP Page Lifecycle
The Java servlet technology determines the lifecycle and capabilities of JSP pages. An automatic build process provided by any Java-
compliant Web server compiles JSP pages by translating each type of data on the JSP page differently. The directives in the page control the
translation process that generates the page implementation servlet.
The Web container translates static data on a JSP page to code that writes data into an output stream. The translation process converts
scriptlets to Java code, and inserts this code in the jspService method of the page implementation servlet.
The tasks performed by a Web container when intercepting a request are used to:
1. Check for an instance of the JSP page implementation servlet. If the instance does not exist, load the servlet class.
2. Instantiate a servlet instance.
A page directive specifies the error page to which the JSP forwards control if exceptions occur when executing the JSP page.
You can create JSP pages that contain HTML content, JSP elements, and scriptlets. The scriptlets contain business logic or refer to reusable
Java bean components that encapsulate such logic.
A bean defines properties and methods to access and modify these properties. A page directive contains an import attribute used to plug a
Java bean component in a JSP page. The JSP page contains scriptlets that invoke the methods of the Java bean.
A Java bean, when used in conjunction with JSP, can encapsulate simple Java code or provide a user interface by separating the presentation
logic from the user interface. When business logic is required to enable transactions, use EJBs with JSP pages.
Page 6 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
n Filters: Enables Web applications to intercept requests and filter information from the requests.
n Application lifecycle events: Enables application to respond to events when the ServletContext or the HttpSession class is initialized or
destroyed.
n Internationalization support: Enables applications to specify a character encoding so that the same application can be used in different
geographical regions.
n Inter-JAR dependencies: Enables deployment descriptors to specify inter jar dependencies.
n Error attributes: Provides constants to display the source of error and the exception stack trace in an error page.
Filters are classes that act on one or more servlets. These classes preprocess a request before it reaches a servlet or postprocess a
response before it reaches the client. Preprocessing includes client authentication and logging whereas postprocessing involves image
conversion, data compression, or encryption.
Filters intercept and examine the request, or modify the request headers and data before the servlet receives the request. In addition, filters
customize a response sent from a servlet. You need not directly reference the filter in the servlet class or JSP, but only map the filter class to
the application URL in the deployment descriptor of the Web application.
A filter implements the javax.servlet.Filter interface and defines methods, such as setFilterConfig(), doFilter(), and getFilterConfig(). The
doFilter() method filters requests after the initialization process. The Web container invokes the setFilterConfig() method to initialize a filter
using a FilterConfig object. The FilterConfig object provides initialization parameters and a ServletContext object to the filter.
An application can define a FilterChain object, which consists of multiple filters. The filters in the FilterChain object perform specific filter
operations on request or response data. The doFilter() method is called by a FilterChain object to transfer control to the next filter in the chain.
Creating Filters
To implement filters, you need to define an abstract filter class. Create an abstract filter class called BaseFilter that defines an empty
implementation for the doFilter() method. To create the BaseFilter class:
1. Define a package and import the servlet specific packages.
2. Import the java.io package to read request data and write response data to an output stream.
package myfilters;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public abstract class BaseFilter implements Filter
{
private FilterConfig filterConfig;
Page 7 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
To override the abstract methods of the BaseFilter class, create a class called ConcreteFilter. This class also implements the code for the
filtering mechanism of the doFilter() method. To create a filter implementation class:
1. Define a package and import the servlet specific classes.
2. Import the java.io package to read data from a request and write data to the response.
Page 8 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
package myfilters;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class ConcreteFilter extends BaseFilter
{
private FilterConfig filterConfig;
HttpServletRequest req;
HttpServletResponse res;
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{
long begin= System.currentTimeMillis();
chain.doFilter(request, response);
long end = System.currentTimeMillis();
System.out.println("Time to execute request: " + (end-begin) + "milliseconds");
}
public void init(FilterConfig filterConfig) throws ServletException
{
super.init(filterConfig);
}
public void doMainprocess(ServletRequest request, ServletResponse response,FilterChain chain)
{
try
{
}
catch(Exception iee)
{
}
}
public void doPostprocess(ServletRequest request, ServletResponse response,FilterChain chain)
{
try
{
System.out.println("customizing response");
}
catch(Exception iee)
{
}
}
}
When the servlet specified in the Web deployment descriptor receives requests, the application initiates data filtering. The application uses
the deployment descriptor to identify the associated filter class. To create a servlet class, TargetServlet, which initiates data filtering:
1. Define a package and import the servlet specific classes.
2. Import the java.io package to read request data and write response data to an output stream.
Page 9 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
client.
6. Specify the content type of the response.
package myfilters;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TargetServlet extends HttpServlet
{
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("Hello after executing the filter");
}
}
To use a filter with a JBoss Web application, declare the filter in the Web deployment descriptor, which is a file named web.xml. The web.xml
file contains tags that specify the filter name and class. The deployment descriptor also maps the filter name to the URL of the Web
application.
Listing 2-7 shows the deployment descriptor for the a Web application which uses the ConcreteFilter class:
Page 10 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
<servlet-name>
SimpleServlet
</servlet-name>
<url-pattern>
/FilterApp
</url-pattern>
</servlet-mapping>
</web-app>
The Web.xml file in Listing 2-7 shows the deployment descriptor for the Web application that uses the ConcreteFilter class. All requests to the
application URL specified by the <url-pattern> tag are sent to the filter, specified by the <filter-class> tag. The filter sends filtered application
data to the TargetServlet class specified in the <servlet-class> tag.
The new features of the Servlet2.3 API enable applications to receive notifications of servlet lifecycle events when the ServletContext class or
session is initialized or destroyed. In addition, applications also receive notifications when you add or remove attributes from a ServletContext
or a session.
The Servlet2.3 API defines the ServletContextListener and ServletContextAttributeListener interfaces that are implemented by listener classes
that receive notifications of ServletContext events.
The ServletContextListener interface defines methods implemented by listener classes to receive notification of the ServletContext class
lifecycle events. These methods include:
n ContextInitialized(): Invoked when a ServletContext is created and an application is ready to process requests.
n ContextDestroyed(): Invoked when the context is removed or when the Web server is shutdown.
A listener class needs to implement the ServletContextAttributesListener interface to receive notifications of the ServletContext attribute
events. This interface provides methods, such as:
n attributeAdded(): Invoked when an attribute is added to a servlet context.
The session listener interfaces, such as HttpSessionListener and HttpSessionAttributeListener, provide methods to respond the session
events. The methods of the HttpSessionListener interface are sessionCreated() and sessionDestroyed().
You can use a session listener class to track the number of end users using the Web application. Listener classes, which implement the
HttpSessionAttributesListener interface, receive notifications when session attributes change. The methods of this interface are:
attributeAdded(), attributeRemoved(), and attributeReplaced().
Providing Internationalization Support
Servlet 2.3 enhancements provide support for character encoding, which maps bytes to specific characters. You can specify character
encoding for a foreign language using the setCharacterEncoding() method of the request object.
For example, a servlet that receives form parameters in Japanese reads a parameter called name, using the code:
req.setCharacterEncoding("Shift_JIS");
// Read a parameter using that charset
String name = req.getParameter("name");
The character encoding needs to be set before invoking the getParameter() or the getReader() methods of the request object.
Specifying JAR Dependencies
A Web application can depend on other JAR libraries to operate on the Web server. The earlier servlet specifications included these libraries
in the WEB-INF/lib folder of the application. The new servlet API enables you to specify these dependencies in the META-INF/MANIFEST.MF
entry. The META-INF/MANIFEST.MF entry decreases the size of the Web application because you need not package the dependent JAR
libraries in the application WEB-INF folder.
The Web deployment descriptor includes error tags to specify error pages to be displayed when exceptions or errors occur during servlet
processing. A servlet that encounters an error receives information about the status code of the error, the exception type, and the error
message. The servlet uses this information to generate a customized error page. An error page cannot provide the exception stack trace or
the URI of the servlet that generated this error.
Note When a servlet sends a response, it adds a status code to the response headers. The status code is an integer used to specify if the
Page 11 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
The Servlet 2.3 API provides the javax.servlet.error.exception and javax.servlet.error.request.uri attributes. These attributes are associated with
the request object, and enable the error page to include the stack trace of the exception and the URI of the problem resource.
You can create a servlet class called ErrorServlet, which uses the exception and URI attributes to track errors that occur when processing an
application. The servlet uses the URI of the servlet, status code, and exception type to provide a description of the exception. To create the
ErrorServlet class:
1. Import the servlet specific and the java.io packages.
9. Obtain the status code string, error message, exception type, and create a string used to print the cause of the error.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ErrorServlet extends HttpServlet
{
statuscodeObj = req.getAttribute("javax.servlet.error.status_code");
messageObj = req.getAttribute("javax.servlet.error.message");
typeObj = req.getAttribute("javax.servlet.error.exception_type");
throwable = (Throwable)
req.getAttribute("javax.servlet.error.exception");
uri = (String) req.getAttribute("javax.servlet.error.request_uri");
if (uri == null)
{
uri = req.getRequestURI(); // In case there's no URI given.
}
if (statuscodeObj != null) statuscode = statuscodeObj.toString();
if (messageObj != null) message = messageObj.toString();
if (typeObj != null) type = typeObj.toString();
Page 12 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
Providing Security
You can specify code in servlets to handle secure Hypertext Transfer Protocol Secure (HTTPS) connections using attributes of the request
object, such as javax.servlet.request.cipher_suite and javax.servlet.request.key_size. The javax.servlet.request.cipher_suite attribute specifies
the name of the cipher suite whereas the javax.servlet.request.key_size attribute specifies an integer representing the bit size of the
cryptographic algorithm.
Note A cipher suite is a set of cryptographic algorithms that creates keys and encrypts information. Cryptographic algorithms encrypt data
or authenticate messages.
A servlet uses the cipher_suite and key_size attributes to decide whether or not the connection is sufficiently secure to proceed. An application
may reject connections with small bit sizes, which are unsafe, or untrusted algorithms.
The request object also provides a method called getAuthType() that returns the type of client authentication from a set of static constants
defined in the HttpServletRequest class. These constants are BASIC_AUTH, DIGEST_AUTH , CLIENT_CERT_AUTH , and FORM_AUTH .
For example, the following code is used for basic authentication:
if (req.getAuthType() == req.BASIC_AUTH) {
}
n Restructuring the Tag Library Descriptor (YLD) to map with Web or EJB descriptors.
Flushing Content Using <jsp:include>
In JSP 1.1, the flush attribute was mandatory in the jsp:include action. You had to set this attribute always to true. All content until the jsp:include
tag was included was flushed to the browser. In addition, response headers could not be set.
With the JSP1.2 specifications, you can specify the include action using an optional flush attribute. For example to include a HTML page:
<jsp:include page="somepage.html" />
The above code assumes the default value false for the flush attribute.
Using XML Syntax with JSP
Page 13 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
You can use XML syntax to create JSP pages known as JSP documents. A JSP document has a root element called <jsp:root> that defines
the namespace for the standard JSP elements and tag libraries used in the page. A JSP document also contains actions and scripting
elements represented by XML elements. Listing 2-9 shows a sample JSP document:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"version="1.2">
<jsp:text>
<html>
<head>
<title> Simple JSP Document Using XML Syntax</title>
</head>
<body>
<h1>JSP Using XML Syntax</h1>
</body>
</html>
</jsp:text>
</jsp:root>
In Listing 2-9, the <jsp:root> element is used to specify the namespace and the JSP version. The <jsp:text> tags are used to place static
content in the JSP page.
When a Web container receives a request for a JSP page the first time, it converts it to an XML document called the XML view of the page.
The container then validates the XML view and converts it to a servlet. The XML view is similar to a JSP document except that all static content
in the JSP page are enclosed within the <jsp:text> element, using XML Character Data (CDATA) sections. Listing 2-10 shows the code for a
sample XML view:
Listing 2-10 shows the XML view of a JSP page. The XML view contains a <jsp:directive> tag, which specifies the content type of the
response. In addition, the XML view contains HTML elements, such as <ul> or <li> within CDATA sections. These HTML elements display the
values of a custom tag attribute called user. The JSP 1.2 specification also provides a page validator to validate the content in an XML view.
Using JSP Tag Libraries
JSP custom tags are Java components that are used within a JSP file. A custom tag consists of a star tag with a tag name, a body, attributes,
and an end tag. Attributes and tag body are optional. Java components representing a tag use the attributes and body of the tag as method
parameters. A tag does not need to be initialized or assigned default properties before use. The structure of a custom tag is:
<tagname attributename1=" attributevalue1"
attributename2=" otherattributevalue2">
body of the tag
</ tagname>
Tags enable a JSP page to reference a block of Java code stored in a tag library. You can create JSP tag libraries and use these libraries
with JSP pages in Web applications. Tag libraries enable reuse of code, business, and presentation logic. Tags reduce the use of scriptlets to
implement tasks, such as iteration, condition checking, or initialization, and abstract these tasks within tag attributes. Tag libraries implement
tasks, such as connecting to a database, formatting text, or sending mails.
Tag classes in a tag library can interact or integrate with any other Java code to invoke their functionality through a tag. For example, you can
use a library of Java classes that format text using a set of tags to access these classes.
To create a custom tag you need to write a class that extends the javax.servlet.jsp.tagext.TagSupport class. The methods of this class are
invoked when the Web container encounters the start tag, body, attributes, and end tag in the JSP page. To create a derived class of the
TagSupport class:
Page 14 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
9. Generate a message for the response using the value of the name.
10. Return a constant called SKIP_BODY that enables the application whether or not the body of the tag needs to be processed.
11. Provide a doEndTag() method that processes the end of a tag.
12. Obtain a reference to a JspWriter object.
package taglib;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class TagLibTest extends TagSupport
{
private String name=null;
public void setName(String value)
{
name = value;
}
public String getName()
{
return(name);
}
public int doStartTag()
{
try
{
JspWriter out = pageContext.getOut();
out.println("<body text=\"blue\">");
if (name != null)
out.println("Welcome " + name + " to the JSP Tag Library World ");
else
out.println("<tr><td> JSP Tag Library executed successfully </td></tr>");
}
catch (Exception ex)
{
throw new Error("error");
}
return SKIP_BODY;
}
Page 15 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
}
return SKIP_BODY;
}
}
An XML file called a Tag Library Descriptor (TLD) is used by the Web application runtime to verify a tag and check if it defines attributes or
contains a body. TLDs enable easy discovery and deployment of tag libraries. Each tag library is associated with a TLD that includes a URI
element. The URI element specifies the real path or a symbolic name to the tag library. The symbolic name of the tag library is mapped to the
real path of the Web application deployment descriptor. Listing 2-12 shows the TLD for the TagLibTest class:
In Listing 2-12, the TLD file contains a <tag> element. This element, in turn, contains a child element called <name> that defines a name for the
tag, and a <tagclass> element, which identifies the TagSupport implementation class. The tag element also contains a child element called
<attribute>. The attribute element specifies an attribute called name of the TagLibTest tag. The <required> tag specifies whether it is
mandatory for the tag to include the attribute.
Using a Tag Class
To enable auto-discovery of the tag libraries, add the tag library JAR file in the WEB-INF/lib directory of the application. You also need to
specify the URI of the tag library in the taglib directive in the JSP page that uses the tag. Listing 2-13 shows the JSP page, which uses the
taglisttest tag:
The above JSP page references the taglib tag with the taglib directive added at the top of the page. This directive specifies the TLD name in
the URI attribute and provides a prefix called mytag for the taglibtest tag. The JSP page uses the tag with the mytag prefix and specifies the
value George for the name attribute.
To run a Web application, the Web container searches the WEB-INF directory for TLDs and their associated JARs. For every TLD, the
container creates a map from the URI of the tag library to the TLD. You can add multiple tag libraries in a single JAR file. The Web container
Page 16 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
reads files with a .tld extension to deploy the associated tag libraries.
A JSP page can use a ServletContextListener implementation to maintain resources, such as shared objects or a database connection, for
each servlet context. Shared objects are stored in the ServletContext object as an attribute, and are accessible to all Web components in the
Web application.
3. Override the contextInitialized() method of the ServletContextListener interface, and generate a message from this method.
4. Override the contextDestroyed() method of the ServletContextListener interface, and display a message.
Listing 2-14 shows the MyListener class:
package testpack;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyListener implements ServletContextListener
{
public void contextInitialized(ServletContextEvent sce)
{
System.out.println
("MyListener: contextInitialized");
}
public void contextDestroyed(ServletContextEvent sce)
{
System.out.println
("MyListener: contextDestroyed");
}
}
The above class contains code that displays messages in the Web server console. These messages are generates when a ServletContext
object is created and an application receives a request and when the ServletContext object is destroyed at server shut down.
To register a ServletContextListener class and receive notifications of the servlet lifecycle events, add entries to Web deployment descriptor.
The Web container registers the listener class when it loads the Web application and scans the deployment descriptor s for references to
listener classes.
You need to define a <listener> element in the Web deployment descriptor packaged with the Web application. Listing 2-15 shows the
deployment descriptor for an application that uses the MyListener class:
The Web deployment descriptor contains a <listener> tag and a <listener-class> element to specify the listener class. You need to place the
listener class in a directory called testpack in the WEB-INF/classes directory.
You can implement the HttpSessionListener interface in a class to receive notifications of session events. A session event can be used to
track of the number of active sessions for an application.
Using Validators
The TagLibraryValidator class available in the javax.servlet.jsp.tagext package helps create validator classes that validate a page based on
the information provided in the TLD. The Web container creates a page implementation servlet after validation on a JSP page is complete.
Page 17 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
To create a validator class, extend the TagLibraryValidator class and override the validate method. The validate method uses an XML view of
the JSP page or a JSP document to perform validation. You can associate a validator with a tag library using the <validator> tag in the TLD.
For example, to define a validator class called MyValidator, use the entry:
<validator>
<validator-class>testpack.MyValidator</validator-class>
</validator>
The validate method defined in the validator class uses an XML parser, such as a Java Document Object Model (JDOM) to work with the XML
view of the JSP page. JDOM is an API to read, write, or manipulate XML using Java code.
The application server creates a service controller MBean, which controls the lifecycle of components, registered with the MBean server. In
addition, the application server creates MBean components used to deploy services, such as JMX or JBossMQ and deploy Web or
application components, such as Enterprise Archive (EAR), Java Archive (JAR), and Service Archive (SAR). A SAR is used to package
MBean components.
To configure JBoss components you need to invoke the JBoss management console. Open a browser window and type
http://localhost:8080/jmx-console in the address bar. The JBoss management console provides a view called the agent view that shows the
registered MBeans that constitute the JBoss services. Figure 2-2 shows the agent view of the JBoss management console:
You can view any of the JBoss services by clicking on the links in the agent view. You can start or stop services and modify the configuration of
these services from the agent view.
Configuring Jetty
The Jetty service is available as a SAR MBean component with the JBoss distribution software. The SAR deployment descriptor jboss-
service.xml contains the MBean definition and the configurable attributes of the Jetty service.
Page 18 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
To modify or view these attributes invoke the JBoss management console in the browser and select the Web server link the jboss.web list of
the agent view. Figure 2-3 shows the MBean view of the Jetty service:
n Provide a custom Jetty service: Set the Configuration element attribute for the Jetty service.
n Specify a HTTP listener: Set a HTTP listener to accept connection on the HTTP port.
n Specify HTTP Request Logs: Set the HTTP request log directory and specify the format for the log files.
n Enable Secure Socket Layer (SSL): Set the request protocol as HTTPS.
Configuring Tomcat
A JBoss-Tomcat installation provides a Tomcat service installed in aTomcat-4.1.x directory. This directory contains all the Tomcat libraries.
The JMX MBean server provides an MBean to manage the Tomcat service and a descriptor called tomcat4.service.xml.
You can invoke the Agent view of the Tomcat service using the JBoss management console. Select the Web server link in the Agent view to
view the configurable attributes of the Tomcat Web server.
These attributes are configured to:
n Delete work directories: Set the DeleteWorkDirs attribute to enable Tomcat to delete work directories when the associated application is
undeployed
n Specify Java2 class loading behavior: Set the Web application class loader to load the application classes.
n Specify custom configuration: Set the config attribute to configure attributes, such as the hostname, application context, and listener
classes.
n Specify the HTTP listener: Set the org.apache.catalina.connector.HttpConnector class as the HTTP listener.
n Enable SSL: Use HTTPS protocol using Java Secure Socket Extension (JSSE) and configure a JAAS security domain used to enable
data encryption.
The tomcat-service.xml and tomcat-service.jar files contain information to configure the Tomcat service running in JBoss. The JBoss
application server manages Tomcat and does not use the default webapps or log directories provided by Tomcat. Instead, JBoss uses its own
Page 19 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
The WAR file also needs to have a Web deployment descriptor file, web.xml for the application. You need to specify information about the URL
mapping to the application deployment directory in the deployment descriptor. The URL mapping enables clients to invoke the application by
appending the URL mapping to the URL http://hostname:<http_portnumber/. You also need to specify event listeners, define servlet mappings,
or filter classes used by the application in the web.xml file. Listing 2-16 shows the web.xml file:
In Listing 2-16, the <servlet> tag is used to specify a name for the servlet and specify its class. The <url-pattern> tag specifies /ts as the URL
mapping to the Web application.
The application uses Another Neat Tool (ANT) to compile the servlet and create the deployment directories. ANT also packages the
application files into a WAR file. You can download ANT from the jakarta.apache.org site and unzip the files in a user-defined directory.
The TestServlet class is used to describe the deployment steps for a Web application. This application is deployed in JBoss 3.2.1 installed on
Linux 8.0 operating system.
Page 20 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
export JAVA_HOME
5. Set the ANT_HOME environment variable to the ANT installation directory using the command:
ANT_HOME= /usr/java/ant1.5.3.1
6. Export ANT_HOME using the command:
export ANT_HOME
7. Set the PATH environment variable using the command:
PATH=$JBOSS/bin:$JAVA_HOME/bin:$ANT_HOME/bin:.:
8. Export the PATH environment variable using the command:
export PATH
9. Set the CLASSPATH environment variable using the command:
CLASSPATH=$JBOSS_HOME/server/default/lib/javax.servlet.jar:.:
10. Export the CLASSPATH environment variable using the command:
export CLASSPATH
The build.xml file shown in Listing 2-17 performs the following tasks:
Page 21 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
Figure 2-4 shows the build process with the ANT tool:
The TestServlet is compiled and a WAR file comprising of the class file, and the deployment descriptor is placed in the /usr/java/jboss-
3.2.1/server/default/deploy/ directory.
3. Start JBoss-Jetty using the command:
sh run.sh
Page 22 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
4. Open a browser window and invoke the servlet by specifying the URL: http://localhost:8080/mywebpage/ts. Figure 2-6 shows the output
in the browser window:
When you need to add JBoss-specific information, use the jboss-web.xml file. This file is stored in the WEB-INF directory. For example, you
need to use the jboss-web.xml file to declare a reference to an Enterprise Java Bean (EJB) whose methods are invoked from a Web
component. Listing 2-18 shows the jboss-Web.xml file used to specify a reference to an EJB:
Page 23 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server
</ejb-ref>
</jboss-web>
Listing 2-18 shows an <ejb-ref> element in the jboss-web.xml file to specify an EJB accessed by a Web component.
Page 24 / 24
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited